title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Guide to Car Detection using YOLO | by Bryan Tan | Towards Data Science
You are working on a self-driving car. As a critical component of this project, you’d like to first build a car detection system. To collect data, you’ve mounted a camera to the hood of the car, which takes pictures of the road ahead every few seconds while you drive around. You’ve gathered all these images into a folder and have labelled them by drawing bounding boxes around every car you found. Here’s an example of what your bounding boxes look like: If you have 80 classes that you want the object detector to recognize, you can represent the class label c either as an integer from 1 to 80, or as an 80-dimensional vector (with 80 numbers) — one component of which is 1 and the rest of which are 0. In this article, I will be using both representations, depending on which is more convenient for a particular step. “You Only Look Once” (YOLO) is a popular algorithm because it achieves high accuracy whilst also being able to run in real-time. This algorithm “only looks once” at the image in the sense that it requires only one forward propagation pass through the network to make predictions. After non-max suppression, it then outputs recognized objects together with the bounding boxes. The input is a batch of images, and each image has the shape (m, 608, 608, 3). The output is a list of bounding boxes along with the recognized classes. Each bounding box is represented by 6 numbers — pc, bx, by, bh, bw, c — as explained above. If you expand c into an 80-dimensional vector, each bounding box is then represented by 85 numbers. Anchor boxes are chosen by exploring the training data to choose reasonable height/width ratios that represent the different classes. The dimension for anchor boxes is the second to last dimension in the encoding: m, nH, nW, anchors, classes. The YOLO architecture is: IMAGE (m, 608, 608, 3) -> DEEP CNN -> ENCODING (m, 19, 19, 5, 85). Let’s look in greater detail at what this encoding represents. If the center/midpoint of an object falls into a grid cell, that grid cell is responsible for detecting that object. Since we are using 5 anchor boxes, each of the 19 x 19 cells thus encodes information about 5 boxes. Anchor boxes are defined only by their width and height. For simplicity, we will flatten the last two last dimensions of the shape (19, 19, 5, 85) encoding. So the output of the Deep CNN is (19, 19, 425). Now, for each box (of each cell), we will compute the following element-wise product and extract a probability that the box contains a certain class. The class score is score_ci = p_c * ci — the probability that there is an object p_c times the probability that the object is a certain class ci. In Figure 4, let’s say for box 1 (cell 1), the probability that an object exists is p1 = 0.60. So there’s a 60% chance that an object exists in box 1 (cell 1). The probability that the object is the class category 3 (a car) is c3 = 0.73. The score for box 1 and for category 3 is score_c1,3 = 0.60 * 0.73 = 0.44. Let’s say we calculate the score for all 80 classes in box 1 and find that the score for the car class (class 3) is the maximum. So we’ll assign the score 0.44 and class 3 to this box 1. Here’s one way to visualize what YOLO is predicting on an image: For each of the 19 x 19 grid cells, find the maximum of the probability scores, that is, taking a max across the 80 classes, one maximum for each of the 5 anchor boxes). Colour that grid cell according to what object that grid cell considers the most likely. Doing this results in this picture: Note that this visualization isn’t a core part of the YOLO algorithm itself for making predictions; it’s just a nice way of visualizing an intermediate result of the algorithm. Another way to visualize YOLO’s output is to plot the bounding boxes that it outputs. Doing that results in a visualization like this: In the figure above, we plotted only boxes for which the model had assigned a high probability, but this is still too many boxes. We’d like to reduce the algorithm’s output to a much smaller number of detected objects. To do so, we’ll use non-max suppression. Specifically, we’ll carry out these steps: Get rid of boxes with a low score. Meaning, the box is not very confident about detecting a class; either due to the low probability of any object, or low probability of this particular class. Select only one box when several boxes overlap with each other and detect the same object. We are going to first apply a filter by thresholding. We would like to get rid of any box for which the class “score” is less than a chosen threshold. The model gives us a total of 19 x 19 x 5 x 85 numbers, with each box described by 85 numbers. It is convenient to rearrange the (19, 19, 5, 85), or (19, 19, 425) dimensional tensor into the following variables: box_confidence: tensor of shape (19×19, 5, 1)(19×19, 5, 1) containing p_c — confidence probability that there’s some object — for each of the 5 boxes predicted in each of the 19x19 cells. boxes: tensor of shape (19×19, 5, 4) containing the midpoint and dimensions (bx, by , bh, bw) for each of the 5 boxes in each cell. box_class_probs: tensor of shape (19×19, 5, 80) containing the "class probabilities" (c1, c2,...,c80) for each of the 80 classes for each of the 5 boxes per cell. Implementing yolo_filter_boxes() Compute box scores by doing the element-wise product(p * c) as described in Figure 4.For each box, find the index of the class with the maximum box score, and the corresponding box score.Create a mask by using a threshold. As a heads-up: ([0.9, 0.3, 0.4, 0.5, 0.1] < 0.4) returns: [False, True, False, False, True]. The mask should be True for the boxes you want to keep.Use TensorFlow to apply the mask to box_class_scores, boxes and box_classes to filter out the boxes we don't want. You should be left with just the subset of boxes you want to keep. Compute box scores by doing the element-wise product(p * c) as described in Figure 4. For each box, find the index of the class with the maximum box score, and the corresponding box score. Create a mask by using a threshold. As a heads-up: ([0.9, 0.3, 0.4, 0.5, 0.1] < 0.4) returns: [False, True, False, False, True]. The mask should be True for the boxes you want to keep. Use TensorFlow to apply the mask to box_class_scores, boxes and box_classes to filter out the boxes we don't want. You should be left with just the subset of boxes you want to keep. Useful references Keras argmax Keras max boolean mask Even after filtering by thresholding over the class scores, we might still end up with a lot of overlapping boxes. A second filter for selecting the right boxes is called non-maximum suppression (NMS). Non-max suppression uses the very crucial function called Intersection over Union, or IoU. Implementing iou() In this code, I’ll be using the convention that (0, 0) is the top-left corner of an image; (1, 0) is the upper-right corner; (1, 1) is the lower-right corner. In other words, the (0, 0) origin starts at the top left corner of the image. As x increases, we move to the right. As y increases, we move downwards. I’ll define a box using its two corners: upper left (x1, y1) and lower right (x2, y2) instead of using the midpoint, height and width. This makes it a bit easier to calculate the intersection. To calculate the area of a rectangle, multiply its height (y2 − y1) by its width (x2 − x1). Since (x1, y1) is the top left and (x2, y2) is the bottom right, these differences should be non-negative. Feel free to draw some examples on paper to clarify this conceptually. To find the intersection of the two boxes (xi1, yi1, xi2, yi2): The top left corner of the intersection (xi1, yi1) is found by comparing the top left corners (x1, y1) of the two boxes, then finding a vertex that has an x-coordinate that is closer to the right, and y-coordinate that is closer to the bottom. The bottom right corner of the intersection ( xi2, yi2) is found by comparing the bottom right corners (x2, y2) of the two boxes, then finding a vertex whose x-coordinate is closer to the left, and the y-coordinate that is closer to the top. The two boxes may have no intersection. We can detect this if the intersection coordinates we calculated end up being the top right and/or bottom left corners of an intersection box. Another way to think of this is if you calculated the height (y2 − y1) or width (x2 − x1) and find that at least one of these lengths is negative, then there is no intersection (intersection area is zero). The two boxes may intersect at the edges or vertices, in which case the intersection area is still zero. This happens when either the height or width (or both) of the calculated intersection is zero. We are now ready to implement non-max suppression. The key steps are: Select the box that has the highest score.Compute the overlap of this box with all other boxes, and remove boxes that overlap significantly (iou >= iou_threshold).Go back to step 1 and iterate until there are no more boxes with a lower score than the currently selected box. Select the box that has the highest score. Compute the overlap of this box with all other boxes, and remove boxes that overlap significantly (iou >= iou_threshold). Go back to step 1 and iterate until there are no more boxes with a lower score than the currently selected box. This will remove all boxes that have a large overlap with the selected boxes. Only the “best” boxes remain. Implementing yolo_non_max_suppression() Reference documentation tf.image.non_max_suppression() It’s time to implement a function taking the output of the deep CNN (the 19 x 19 x 5 x 85 dimensional encoding) and filtering through all the boxes using the functions we’ve just implemented. Implementing yolo_eval() This function takes the output of the YOLO encoding and filters the boxes using score threshold and NMS. There’s one implementations detail you need to know. There are a few ways of representing boxes, such as via their corners or via their midpoint and height/width. YOLO converts between a few such formats at different times, using the following functions: boxes = yolo_boxes_to_corners(box_xy, box_wh) which converts the YOLO box coordinates (x, y, w, h) to box corners’ coordinates (x1, y1, x2, y2) to fit the input of yolo_filter_boxes . boxes = scale_boxes(boxes, image_shape) YOLO’s network was trained to run on 608 x 608 images. If you are testing this data on a different size image — for example, a car detection dataset with 720 x 1280 images — this step rescales the boxes so that they can be plotted on top of the original 720 x 1280 image. Input image (608, 608, 3) The input image goes through a CNN, resulting in a (19, 19, 5, 85) dimensional output. After flattening the last two dimensions, the output is a volume of shape (19, 19, 425). Each cell in a 19 x 19 grid over the input image gives 425 numbers: 425 = 5 x 85 because each cell contains predictions for 5 boxes, corresponding to 5 anchor boxes; 85 = 5 + 80 where 5 is because (pc, bx, by, bh, bw) has 5 numbers, and 80 is the number of classes we’d like to detect. We then select only a few boxes based on score-thresholding — discarding boxes that have detected a class with a score less than the threshold, and non-max suppression — computing the Intersection over Union (IOU) and avoiding selecting overlapping boxes. This gives you YOLO’s final output. In this part, we are going to use a pre-trained model and test it on the car detection dataset. We’ll need a session to execute the computation graph and evaluate the tensors: sess = K.get_session() Recall that we were trying to detect 80 classes, and are using 5 anchor boxes. We will read the names and anchors of the 80 classes and 5 boxes that are stored in two files — coco_classes.txt and yolo_anchors.txt (more info in Github repo). The car detection dataset has 720 x 1280 images, which are pre-processed into 608 x 608 images. Training a YOLO model takes a very long time and requires a fairly large dataset of labelled bounding boxes for a large range of target classes. So we are instead going to load an existing pre-trained Keras YOLO model. (more info in Github repo). These weights come from the official YOLO website and were converted using a function written by Allan Zelener. References are at the end of this article. Technically, these are the parameters from the YOLOv2 model, but we will simply refer to it as YOLO in this article. yolo_model = load_model(“model_data/yolo.h5”) This loads the weights of a trained YOLO model. You can take a look at the summary of the layers the model contains in the notebook in the Github repo. Reminder: this model converts a preprocessed batch of input images (shape: (m, 608, 608, 3)) into a tensor of shape (m, 19, 19, 5, 85) as explained in Figure 2. The output of yolo_model is a (m, 19, 19, 5, 85) tensor that needs to pass through non-trivial processing and conversion. The following code does that for us: yolo_outputs = yolo_head(yolo_model.output, anchors, len(class_names)) If you are curious about how yolo_head is implemented, you can find the function definition in the file 'keras_yolo.py' in the Github repo. After adding yolo_outputs to our graph. This set of 4 tensors is ready to be used as input by the yolo_eval function. yolo_outputs gave us all the predicted boxes of yolo_model in the correct format. We’re now ready to perform filtering and selecting only the best boxes by calling yolo_eval, which we had previously implemented, to do this. scores, boxes, classes = yolo_eval(yolo_outputs, image_shape) Let the fun begin. We have created a graph that can be summarized as follows: yolo_model.input is given to yolo_model. The model is used to compute the output yolo_model.output.yolo_model.output is processed by yolo_head. It gives you yolo_outputs.yolo_outputs goes through a filtering function, yolo_eval. It outputs your predictions: scores, boxes, classes. yolo_model.input is given to yolo_model. The model is used to compute the output yolo_model.output. yolo_model.output is processed by yolo_head. It gives you yolo_outputs. yolo_outputs goes through a filtering function, yolo_eval. It outputs your predictions: scores, boxes, classes. Implementing predict() predict()runs the graph to test YOLO on an image. You will need to run a TensorFlow session, to have it compute scores, boxes, classes. The code below also uses the following function: image, image_data = preprocess_image("images/" + image_file, model_image_size = (608, 608)) which outputs: image: a python (PIL) representation of your image used for drawing boxes. You won’t need to use it. image_data: a numpy-array representing the image. This will be the input to the CNN. Testing the function on a test image: out_scores, out_boxes, out_classes = predict(sess, “test.jpg”) The model we’ve just run is actually able to detect 80 different classes listed in coco_classes.txt. Feel free to try with on with your own images by downloading the files in the Github repo. If we were to run the session in a for loop over all the images. Here’s what we would get: YOLO is a state-of-the-art object detection model that is fast and accurate. It runs an input image through a CNN which outputs a 19 x 19 x 5 x 85 dimensional volume. The encoding can be seen as a grid where each of the 19 x 19 cells contains information about 5 boxes. Filter through all the boxes using non-max suppression. Specifically, use score thresholding on the probability of detecting a class to keep only accurate (high probability) boxes, and Intersection over Union (IoU) thresholding to eliminate overlapping boxes. Because training a YOLO model from randomly initialized weights is non-trivial and requires a large dataset as well as a lot of computation, we used previously trained model parameters in this exercise. If you wish, you can also try fine-tuning the YOLO model with your own dataset, though this would be a fairly non-trivial exercise. Special thanks to deeplearning.ai. All figures by courtesy of deeplearning.ai. The ideas presented in this article came primarily from the two YOLO papers. The implementation here also took significant inspiration and used many components from Allan Zelener’s GitHub repository. The pre-trained weights used in this exercise came from the official YOLO website. Joseph Redmon, Santosh Divvala, Ross Girshick, Ali Farhadi — You Only Look Once: Unified, Real-Time Object Detection (2015) Joseph Redmon, Ali Farhadi — YOLO9000: Better, Faster, Stronger (2016) Allan Zelener — YAD2K: Yet Another Darknet 2 Keras The official YOLO website (https://pjreddie.com/darknet/yolo/) Car detection dataset: The Drive.ai Sample Dataset (provided by drive.ai) is licensed under a Creative Commons Attribution 4.0 International License. Github repo: https://github.com/TheClub4/car-detection-yolov2
[ { "code": null, "e": 447, "s": 171, "text": "You are working on a self-driving car. As a critical component of this project, you’d like to first build a car detection system. To collect data, you’ve mounted a camera to the hood of the car, which takes pictures of the road ahead every few seconds while you drive around." }, { "code": null, "e": 628, "s": 447, "text": "You’ve gathered all these images into a folder and have labelled them by drawing bounding boxes around every car you found. Here’s an example of what your bounding boxes look like:" }, { "code": null, "e": 994, "s": 628, "text": "If you have 80 classes that you want the object detector to recognize, you can represent the class label c either as an integer from 1 to 80, or as an 80-dimensional vector (with 80 numbers) — one component of which is 1 and the rest of which are 0. In this article, I will be using both representations, depending on which is more convenient for a particular step." }, { "code": null, "e": 1370, "s": 994, "text": "“You Only Look Once” (YOLO) is a popular algorithm because it achieves high accuracy whilst also being able to run in real-time. This algorithm “only looks once” at the image in the sense that it requires only one forward propagation pass through the network to make predictions. After non-max suppression, it then outputs recognized objects together with the bounding boxes." }, { "code": null, "e": 1449, "s": 1370, "text": "The input is a batch of images, and each image has the shape (m, 608, 608, 3)." }, { "code": null, "e": 1715, "s": 1449, "text": "The output is a list of bounding boxes along with the recognized classes. Each bounding box is represented by 6 numbers — pc, bx, by, bh, bw, c — as explained above. If you expand c into an 80-dimensional vector, each bounding box is then represented by 85 numbers." }, { "code": null, "e": 1849, "s": 1715, "text": "Anchor boxes are chosen by exploring the training data to choose reasonable height/width ratios that represent the different classes." }, { "code": null, "e": 1958, "s": 1849, "text": "The dimension for anchor boxes is the second to last dimension in the encoding: m, nH, nW, anchors, classes." }, { "code": null, "e": 2051, "s": 1958, "text": "The YOLO architecture is: IMAGE (m, 608, 608, 3) -> DEEP CNN -> ENCODING (m, 19, 19, 5, 85)." }, { "code": null, "e": 2114, "s": 2051, "text": "Let’s look in greater detail at what this encoding represents." }, { "code": null, "e": 2231, "s": 2114, "text": "If the center/midpoint of an object falls into a grid cell, that grid cell is responsible for detecting that object." }, { "code": null, "e": 2389, "s": 2231, "text": "Since we are using 5 anchor boxes, each of the 19 x 19 cells thus encodes information about 5 boxes. Anchor boxes are defined only by their width and height." }, { "code": null, "e": 2537, "s": 2389, "text": "For simplicity, we will flatten the last two last dimensions of the shape (19, 19, 5, 85) encoding. So the output of the Deep CNN is (19, 19, 425)." }, { "code": null, "e": 2687, "s": 2537, "text": "Now, for each box (of each cell), we will compute the following element-wise product and extract a probability that the box contains a certain class." }, { "code": null, "e": 2833, "s": 2687, "text": "The class score is score_ci = p_c * ci — the probability that there is an object p_c times the probability that the object is a certain class ci." }, { "code": null, "e": 2993, "s": 2833, "text": "In Figure 4, let’s say for box 1 (cell 1), the probability that an object exists is p1 = 0.60. So there’s a 60% chance that an object exists in box 1 (cell 1)." }, { "code": null, "e": 3071, "s": 2993, "text": "The probability that the object is the class category 3 (a car) is c3 = 0.73." }, { "code": null, "e": 3146, "s": 3071, "text": "The score for box 1 and for category 3 is score_c1,3 = 0.60 * 0.73 = 0.44." }, { "code": null, "e": 3333, "s": 3146, "text": "Let’s say we calculate the score for all 80 classes in box 1 and find that the score for the car class (class 3) is the maximum. So we’ll assign the score 0.44 and class 3 to this box 1." }, { "code": null, "e": 3398, "s": 3333, "text": "Here’s one way to visualize what YOLO is predicting on an image:" }, { "code": null, "e": 3568, "s": 3398, "text": "For each of the 19 x 19 grid cells, find the maximum of the probability scores, that is, taking a max across the 80 classes, one maximum for each of the 5 anchor boxes)." }, { "code": null, "e": 3657, "s": 3568, "text": "Colour that grid cell according to what object that grid cell considers the most likely." }, { "code": null, "e": 3693, "s": 3657, "text": "Doing this results in this picture:" }, { "code": null, "e": 3870, "s": 3693, "text": "Note that this visualization isn’t a core part of the YOLO algorithm itself for making predictions; it’s just a nice way of visualizing an intermediate result of the algorithm." }, { "code": null, "e": 4005, "s": 3870, "text": "Another way to visualize YOLO’s output is to plot the bounding boxes that it outputs. Doing that results in a visualization like this:" }, { "code": null, "e": 4224, "s": 4005, "text": "In the figure above, we plotted only boxes for which the model had assigned a high probability, but this is still too many boxes. We’d like to reduce the algorithm’s output to a much smaller number of detected objects." }, { "code": null, "e": 4308, "s": 4224, "text": "To do so, we’ll use non-max suppression. Specifically, we’ll carry out these steps:" }, { "code": null, "e": 4501, "s": 4308, "text": "Get rid of boxes with a low score. Meaning, the box is not very confident about detecting a class; either due to the low probability of any object, or low probability of this particular class." }, { "code": null, "e": 4592, "s": 4501, "text": "Select only one box when several boxes overlap with each other and detect the same object." }, { "code": null, "e": 4743, "s": 4592, "text": "We are going to first apply a filter by thresholding. We would like to get rid of any box for which the class “score” is less than a chosen threshold." }, { "code": null, "e": 4955, "s": 4743, "text": "The model gives us a total of 19 x 19 x 5 x 85 numbers, with each box described by 85 numbers. It is convenient to rearrange the (19, 19, 5, 85), or (19, 19, 425) dimensional tensor into the following variables:" }, { "code": null, "e": 5143, "s": 4955, "text": "box_confidence: tensor of shape (19×19, 5, 1)(19×19, 5, 1) containing p_c — confidence probability that there’s some object — for each of the 5 boxes predicted in each of the 19x19 cells." }, { "code": null, "e": 5275, "s": 5143, "text": "boxes: tensor of shape (19×19, 5, 4) containing the midpoint and dimensions (bx, by , bh, bw) for each of the 5 boxes in each cell." }, { "code": null, "e": 5438, "s": 5275, "text": "box_class_probs: tensor of shape (19×19, 5, 80) containing the \"class probabilities\" (c1, c2,...,c80) for each of the 80 classes for each of the 5 boxes per cell." }, { "code": null, "e": 5471, "s": 5438, "text": "Implementing yolo_filter_boxes()" }, { "code": null, "e": 6024, "s": 5471, "text": "Compute box scores by doing the element-wise product(p * c) as described in Figure 4.For each box, find the index of the class with the maximum box score, and the corresponding box score.Create a mask by using a threshold. As a heads-up: ([0.9, 0.3, 0.4, 0.5, 0.1] < 0.4) returns: [False, True, False, False, True]. The mask should be True for the boxes you want to keep.Use TensorFlow to apply the mask to box_class_scores, boxes and box_classes to filter out the boxes we don't want. You should be left with just the subset of boxes you want to keep." }, { "code": null, "e": 6110, "s": 6024, "text": "Compute box scores by doing the element-wise product(p * c) as described in Figure 4." }, { "code": null, "e": 6213, "s": 6110, "text": "For each box, find the index of the class with the maximum box score, and the corresponding box score." }, { "code": null, "e": 6398, "s": 6213, "text": "Create a mask by using a threshold. As a heads-up: ([0.9, 0.3, 0.4, 0.5, 0.1] < 0.4) returns: [False, True, False, False, True]. The mask should be True for the boxes you want to keep." }, { "code": null, "e": 6580, "s": 6398, "text": "Use TensorFlow to apply the mask to box_class_scores, boxes and box_classes to filter out the boxes we don't want. You should be left with just the subset of boxes you want to keep." }, { "code": null, "e": 6598, "s": 6580, "text": "Useful references" }, { "code": null, "e": 6611, "s": 6598, "text": "Keras argmax" }, { "code": null, "e": 6621, "s": 6611, "text": "Keras max" }, { "code": null, "e": 6634, "s": 6621, "text": "boolean mask" }, { "code": null, "e": 6836, "s": 6634, "text": "Even after filtering by thresholding over the class scores, we might still end up with a lot of overlapping boxes. A second filter for selecting the right boxes is called non-maximum suppression (NMS)." }, { "code": null, "e": 6927, "s": 6836, "text": "Non-max suppression uses the very crucial function called Intersection over Union, or IoU." }, { "code": null, "e": 6946, "s": 6927, "text": "Implementing iou()" }, { "code": null, "e": 7256, "s": 6946, "text": "In this code, I’ll be using the convention that (0, 0) is the top-left corner of an image; (1, 0) is the upper-right corner; (1, 1) is the lower-right corner. In other words, the (0, 0) origin starts at the top left corner of the image. As x increases, we move to the right. As y increases, we move downwards." }, { "code": null, "e": 7449, "s": 7256, "text": "I’ll define a box using its two corners: upper left (x1, y1) and lower right (x2, y2) instead of using the midpoint, height and width. This makes it a bit easier to calculate the intersection." }, { "code": null, "e": 7648, "s": 7449, "text": "To calculate the area of a rectangle, multiply its height (y2 − y1) by its width (x2 − x1). Since (x1, y1) is the top left and (x2, y2) is the bottom right, these differences should be non-negative." }, { "code": null, "e": 7783, "s": 7648, "text": "Feel free to draw some examples on paper to clarify this conceptually. To find the intersection of the two boxes (xi1, yi1, xi2, yi2):" }, { "code": null, "e": 8027, "s": 7783, "text": "The top left corner of the intersection (xi1, yi1) is found by comparing the top left corners (x1, y1) of the two boxes, then finding a vertex that has an x-coordinate that is closer to the right, and y-coordinate that is closer to the bottom." }, { "code": null, "e": 8269, "s": 8027, "text": "The bottom right corner of the intersection ( xi2, yi2) is found by comparing the bottom right corners (x2, y2) of the two boxes, then finding a vertex whose x-coordinate is closer to the left, and the y-coordinate that is closer to the top." }, { "code": null, "e": 8658, "s": 8269, "text": "The two boxes may have no intersection. We can detect this if the intersection coordinates we calculated end up being the top right and/or bottom left corners of an intersection box. Another way to think of this is if you calculated the height (y2 − y1) or width (x2 − x1) and find that at least one of these lengths is negative, then there is no intersection (intersection area is zero)." }, { "code": null, "e": 8858, "s": 8658, "text": "The two boxes may intersect at the edges or vertices, in which case the intersection area is still zero. This happens when either the height or width (or both) of the calculated intersection is zero." }, { "code": null, "e": 8928, "s": 8858, "text": "We are now ready to implement non-max suppression. The key steps are:" }, { "code": null, "e": 9203, "s": 8928, "text": "Select the box that has the highest score.Compute the overlap of this box with all other boxes, and remove boxes that overlap significantly (iou >= iou_threshold).Go back to step 1 and iterate until there are no more boxes with a lower score than the currently selected box." }, { "code": null, "e": 9246, "s": 9203, "text": "Select the box that has the highest score." }, { "code": null, "e": 9368, "s": 9246, "text": "Compute the overlap of this box with all other boxes, and remove boxes that overlap significantly (iou >= iou_threshold)." }, { "code": null, "e": 9480, "s": 9368, "text": "Go back to step 1 and iterate until there are no more boxes with a lower score than the currently selected box." }, { "code": null, "e": 9588, "s": 9480, "text": "This will remove all boxes that have a large overlap with the selected boxes. Only the “best” boxes remain." }, { "code": null, "e": 9628, "s": 9588, "text": "Implementing yolo_non_max_suppression()" }, { "code": null, "e": 9652, "s": 9628, "text": "Reference documentation" }, { "code": null, "e": 9683, "s": 9652, "text": "tf.image.non_max_suppression()" }, { "code": null, "e": 9875, "s": 9683, "text": "It’s time to implement a function taking the output of the deep CNN (the 19 x 19 x 5 x 85 dimensional encoding) and filtering through all the boxes using the functions we’ve just implemented." }, { "code": null, "e": 9900, "s": 9875, "text": "Implementing yolo_eval()" }, { "code": null, "e": 10005, "s": 9900, "text": "This function takes the output of the YOLO encoding and filters the boxes using score threshold and NMS." }, { "code": null, "e": 10260, "s": 10005, "text": "There’s one implementations detail you need to know. There are a few ways of representing boxes, such as via their corners or via their midpoint and height/width. YOLO converts between a few such formats at different times, using the following functions:" }, { "code": null, "e": 10306, "s": 10260, "text": "boxes = yolo_boxes_to_corners(box_xy, box_wh)" }, { "code": null, "e": 10444, "s": 10306, "text": "which converts the YOLO box coordinates (x, y, w, h) to box corners’ coordinates (x1, y1, x2, y2) to fit the input of yolo_filter_boxes ." }, { "code": null, "e": 10484, "s": 10444, "text": "boxes = scale_boxes(boxes, image_shape)" }, { "code": null, "e": 10756, "s": 10484, "text": "YOLO’s network was trained to run on 608 x 608 images. If you are testing this data on a different size image — for example, a car detection dataset with 720 x 1280 images — this step rescales the boxes so that they can be plotted on top of the original 720 x 1280 image." }, { "code": null, "e": 10782, "s": 10756, "text": "Input image (608, 608, 3)" }, { "code": null, "e": 10869, "s": 10782, "text": "The input image goes through a CNN, resulting in a (19, 19, 5, 85) dimensional output." }, { "code": null, "e": 11244, "s": 10869, "text": "After flattening the last two dimensions, the output is a volume of shape (19, 19, 425). Each cell in a 19 x 19 grid over the input image gives 425 numbers: 425 = 5 x 85 because each cell contains predictions for 5 boxes, corresponding to 5 anchor boxes; 85 = 5 + 80 where 5 is because (pc, bx, by, bh, bw) has 5 numbers, and 80 is the number of classes we’d like to detect." }, { "code": null, "e": 11500, "s": 11244, "text": "We then select only a few boxes based on score-thresholding — discarding boxes that have detected a class with a score less than the threshold, and non-max suppression — computing the Intersection over Union (IOU) and avoiding selecting overlapping boxes." }, { "code": null, "e": 11536, "s": 11500, "text": "This gives you YOLO’s final output." }, { "code": null, "e": 11712, "s": 11536, "text": "In this part, we are going to use a pre-trained model and test it on the car detection dataset. We’ll need a session to execute the computation graph and evaluate the tensors:" }, { "code": null, "e": 11735, "s": 11712, "text": "sess = K.get_session()" }, { "code": null, "e": 12072, "s": 11735, "text": "Recall that we were trying to detect 80 classes, and are using 5 anchor boxes. We will read the names and anchors of the 80 classes and 5 boxes that are stored in two files — coco_classes.txt and yolo_anchors.txt (more info in Github repo). The car detection dataset has 720 x 1280 images, which are pre-processed into 608 x 608 images." }, { "code": null, "e": 12591, "s": 12072, "text": "Training a YOLO model takes a very long time and requires a fairly large dataset of labelled bounding boxes for a large range of target classes. So we are instead going to load an existing pre-trained Keras YOLO model. (more info in Github repo). These weights come from the official YOLO website and were converted using a function written by Allan Zelener. References are at the end of this article. Technically, these are the parameters from the YOLOv2 model, but we will simply refer to it as YOLO in this article." }, { "code": null, "e": 12637, "s": 12591, "text": "yolo_model = load_model(“model_data/yolo.h5”)" }, { "code": null, "e": 12789, "s": 12637, "text": "This loads the weights of a trained YOLO model. You can take a look at the summary of the layers the model contains in the notebook in the Github repo." }, { "code": null, "e": 12950, "s": 12789, "text": "Reminder: this model converts a preprocessed batch of input images (shape: (m, 608, 608, 3)) into a tensor of shape (m, 19, 19, 5, 85) as explained in Figure 2." }, { "code": null, "e": 13109, "s": 12950, "text": "The output of yolo_model is a (m, 19, 19, 5, 85) tensor that needs to pass through non-trivial processing and conversion. The following code does that for us:" }, { "code": null, "e": 13180, "s": 13109, "text": "yolo_outputs = yolo_head(yolo_model.output, anchors, len(class_names))" }, { "code": null, "e": 13320, "s": 13180, "text": "If you are curious about how yolo_head is implemented, you can find the function definition in the file 'keras_yolo.py' in the Github repo." }, { "code": null, "e": 13438, "s": 13320, "text": "After adding yolo_outputs to our graph. This set of 4 tensors is ready to be used as input by the yolo_eval function." }, { "code": null, "e": 13662, "s": 13438, "text": "yolo_outputs gave us all the predicted boxes of yolo_model in the correct format. We’re now ready to perform filtering and selecting only the best boxes by calling yolo_eval, which we had previously implemented, to do this." }, { "code": null, "e": 13724, "s": 13662, "text": "scores, boxes, classes = yolo_eval(yolo_outputs, image_shape)" }, { "code": null, "e": 13802, "s": 13724, "text": "Let the fun begin. We have created a graph that can be summarized as follows:" }, { "code": null, "e": 14084, "s": 13802, "text": "yolo_model.input is given to yolo_model. The model is used to compute the output yolo_model.output.yolo_model.output is processed by yolo_head. It gives you yolo_outputs.yolo_outputs goes through a filtering function, yolo_eval. It outputs your predictions: scores, boxes, classes." }, { "code": null, "e": 14184, "s": 14084, "text": "yolo_model.input is given to yolo_model. The model is used to compute the output yolo_model.output." }, { "code": null, "e": 14256, "s": 14184, "text": "yolo_model.output is processed by yolo_head. It gives you yolo_outputs." }, { "code": null, "e": 14368, "s": 14256, "text": "yolo_outputs goes through a filtering function, yolo_eval. It outputs your predictions: scores, boxes, classes." }, { "code": null, "e": 14391, "s": 14368, "text": "Implementing predict()" }, { "code": null, "e": 14527, "s": 14391, "text": "predict()runs the graph to test YOLO on an image. You will need to run a TensorFlow session, to have it compute scores, boxes, classes." }, { "code": null, "e": 14576, "s": 14527, "text": "The code below also uses the following function:" }, { "code": null, "e": 14668, "s": 14576, "text": "image, image_data = preprocess_image(\"images/\" + image_file, model_image_size = (608, 608))" }, { "code": null, "e": 14683, "s": 14668, "text": "which outputs:" }, { "code": null, "e": 14784, "s": 14683, "text": "image: a python (PIL) representation of your image used for drawing boxes. You won’t need to use it." }, { "code": null, "e": 14869, "s": 14784, "text": "image_data: a numpy-array representing the image. This will be the input to the CNN." }, { "code": null, "e": 14907, "s": 14869, "text": "Testing the function on a test image:" }, { "code": null, "e": 14970, "s": 14907, "text": "out_scores, out_boxes, out_classes = predict(sess, “test.jpg”)" }, { "code": null, "e": 15162, "s": 14970, "text": "The model we’ve just run is actually able to detect 80 different classes listed in coco_classes.txt. Feel free to try with on with your own images by downloading the files in the Github repo." }, { "code": null, "e": 15253, "s": 15162, "text": "If we were to run the session in a for loop over all the images. Here’s what we would get:" }, { "code": null, "e": 15330, "s": 15253, "text": "YOLO is a state-of-the-art object detection model that is fast and accurate." }, { "code": null, "e": 15420, "s": 15330, "text": "It runs an input image through a CNN which outputs a 19 x 19 x 5 x 85 dimensional volume." }, { "code": null, "e": 15523, "s": 15420, "text": "The encoding can be seen as a grid where each of the 19 x 19 cells contains information about 5 boxes." }, { "code": null, "e": 15783, "s": 15523, "text": "Filter through all the boxes using non-max suppression. Specifically, use score thresholding on the probability of detecting a class to keep only accurate (high probability) boxes, and Intersection over Union (IoU) thresholding to eliminate overlapping boxes." }, { "code": null, "e": 16118, "s": 15783, "text": "Because training a YOLO model from randomly initialized weights is non-trivial and requires a large dataset as well as a lot of computation, we used previously trained model parameters in this exercise. If you wish, you can also try fine-tuning the YOLO model with your own dataset, though this would be a fairly non-trivial exercise." }, { "code": null, "e": 16153, "s": 16118, "text": "Special thanks to deeplearning.ai." }, { "code": null, "e": 16197, "s": 16153, "text": "All figures by courtesy of deeplearning.ai." }, { "code": null, "e": 16480, "s": 16197, "text": "The ideas presented in this article came primarily from the two YOLO papers. The implementation here also took significant inspiration and used many components from Allan Zelener’s GitHub repository. The pre-trained weights used in this exercise came from the official YOLO website." }, { "code": null, "e": 16604, "s": 16480, "text": "Joseph Redmon, Santosh Divvala, Ross Girshick, Ali Farhadi — You Only Look Once: Unified, Real-Time Object Detection (2015)" }, { "code": null, "e": 16675, "s": 16604, "text": "Joseph Redmon, Ali Farhadi — YOLO9000: Better, Faster, Stronger (2016)" }, { "code": null, "e": 16726, "s": 16675, "text": "Allan Zelener — YAD2K: Yet Another Darknet 2 Keras" }, { "code": null, "e": 16789, "s": 16726, "text": "The official YOLO website (https://pjreddie.com/darknet/yolo/)" }, { "code": null, "e": 16939, "s": 16789, "text": "Car detection dataset: The Drive.ai Sample Dataset (provided by drive.ai) is licensed under a Creative Commons Attribution 4.0 International License." } ]
Data Structures | Heap | Question 5 - GeeksforGeeks
28 Jun, 2021 Consider a binary max-heap implemented using an array. Which one of the following array represents a binary max-heap? (GATE CS 2009)(A) 25,12,16,13,10,8,14(B) 25,12,16,13,10,8,14(C) 25,14,16,13,10,8,12(D) 25,14,12,13,10,8,16Answer: (C)Explanation: A tree is max-heap if data at every node in the tree is greater than or equal to it’s children’ s data. In array representation of heap tree, a node at index i has its left child at index 2i + 1 and right child at index 2i + 2. 25 / \ / \ 14 16 / \ / \ / \ / \ 13 10 8 12 Quiz of this Question Data Structures Data Structures-Heap Heap Quizzes Data Structures Data Structures Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Advantages and Disadvantages of Linked List C program to implement Adjacency Matrix of a given Graph Difference between Singly linked list and Doubly linked list Introduction to Data Structures | 10 most commonly used Data Structures FIFO vs LIFO approach in Programming Bit manipulation | Swap Endianness of a number Data Structures | Queue | Question 11 Data Structures | Stack | Question 4 Advantages of vector over array in C++ Program to create Custom Vector Class in C++
[ { "code": null, "e": 24816, "s": 24788, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25168, "s": 24816, "text": "Consider a binary max-heap implemented using an array. Which one of the following array represents a binary max-heap? (GATE CS 2009)(A) 25,12,16,13,10,8,14(B) 25,12,16,13,10,8,14(C) 25,14,16,13,10,8,12(D) 25,14,12,13,10,8,16Answer: (C)Explanation: A tree is max-heap if data at every node in the tree is greater than or equal to it’s children’ s data." }, { "code": null, "e": 25292, "s": 25168, "text": "In array representation of heap tree, a node at index i has its left child at index 2i + 1 and right child at index 2i + 2." }, { "code": null, "e": 25436, "s": 25292, "text": " 25\n / \\\n / \\\n 14 16\n / \\ / \\\n / \\ / \\\n13 10 8 12" }, { "code": null, "e": 25458, "s": 25436, "text": "Quiz of this Question" }, { "code": null, "e": 25474, "s": 25458, "text": "Data Structures" }, { "code": null, "e": 25495, "s": 25474, "text": "Data Structures-Heap" }, { "code": null, "e": 25508, "s": 25495, "text": "Heap Quizzes" }, { "code": null, "e": 25524, "s": 25508, "text": "Data Structures" }, { "code": null, "e": 25540, "s": 25524, "text": "Data Structures" }, { "code": null, "e": 25638, "s": 25540, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25682, "s": 25638, "text": "Advantages and Disadvantages of Linked List" }, { "code": null, "e": 25739, "s": 25682, "text": "C program to implement Adjacency Matrix of a given Graph" }, { "code": null, "e": 25800, "s": 25739, "text": "Difference between Singly linked list and Doubly linked list" }, { "code": null, "e": 25872, "s": 25800, "text": "Introduction to Data Structures | 10 most commonly used Data Structures" }, { "code": null, "e": 25909, "s": 25872, "text": "FIFO vs LIFO approach in Programming" }, { "code": null, "e": 25956, "s": 25909, "text": "Bit manipulation | Swap Endianness of a number" }, { "code": null, "e": 25994, "s": 25956, "text": "Data Structures | Queue | Question 11" }, { "code": null, "e": 26031, "s": 25994, "text": "Data Structures | Stack | Question 4" }, { "code": null, "e": 26070, "s": 26031, "text": "Advantages of vector over array in C++" } ]
Fetching top news using news API in Python
News API is very famous API for searching and fetching news articles from any web site, using this API anyone can fetch top 10 heading line of news from any web site. But using this API, one thing is required which is the API key. import requests def Topnews(): # BBC news api my_api_key="Api_number” my_url = = " https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=my_api_key" my_open_bbc_page = requests.get(my_url).json() my_article = my_open_bbc_page["articles"] my_results = [] for ar in my_article: my_results.append(ar["title"]) for i in range(len(my_results)): print(i + 1, my_results[i]) # Driver Code if __name__ == '__main__': # function call Topnews() Using pandas DataFrame is much easier to work with down the road, we can easily convert from JSON to DataFrame using pd.DataFrame.from_dict and .appy([pd.Series]).
[ { "code": null, "e": 1229, "s": 1062, "text": "News API is very famous API for searching and fetching news articles from any web site, using this API anyone can fetch top 10 heading line of news from any web site." }, { "code": null, "e": 1293, "s": 1229, "text": "But using this API, one thing is required which is the API key." }, { "code": null, "e": 1802, "s": 1293, "text": "import requests \ndef Topnews():\n # BBC news api\n my_api_key=\"Api_number”\n my_url = = \" https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=my_api_key\"\n my_open_bbc_page = requests.get(my_url).json()\n my_article = my_open_bbc_page[\"articles\"]\n my_results = []\n for ar in my_article:\n my_results.append(ar[\"title\"])\n for i in range(len(my_results)):\n print(i + 1, my_results[i]) \n# Driver Code\nif __name__ == '__main__':\n # function call\n Topnews()" }, { "code": null, "e": 1966, "s": 1802, "text": "Using pandas DataFrame is much easier to work with down the road, we can easily convert from JSON to DataFrame using pd.DataFrame.from_dict and .appy([pd.Series])." } ]
How to create Text to Speech in an Android App using Kotlin?
This example demonstrates how to create Text to Speech in an Android App using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:text="Tutorials Point" android:textAlignment="center" android:textColor="@android:color/holo_green_dark" android:textSize="32sp" android:textStyle="bold" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@android:color/holo_red_light" android:textSize="24sp" android:textStyle="bold|italic" /> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerInParent="true" android:orientation="vertical"> <ImageView android:id="@+id/speakImageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="?selectableItemBackground" android:src="@android:drawable/ic_btn_speak_now" /> </LinearLayout> </RelativeLayout> Step 3 − Add the following code to MainActivity.kt import android.app.Activity import android.content.Intent import android.os.Bundle import android.speech.RecognizerIntent import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import java.util.* import kotlin.collections.ArrayList class MainActivity : AppCompatActivity() { private val REQUESTCODE = 100 lateinit var textView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" textView = findViewById(R.id.textView) val speakImageView: ImageView = findViewById(R.id.speakImageView) speakImageView.setOnClickListener { val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH) intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()) intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Need to Speak") startActivityForResult(intent, REQUESTCODE) Toast.makeText(applicationContext, "Sorry your device not supported", Toast.LENGTH_SHORT).show() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK && null != data) { val result: ArrayList<String> = data.getStringArrayListExtra(RecognizerIntent .EXTRA_RESULTS) textView.text = result[0] } } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.kotlipapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − NOTE− Test in your own device for better results Click here to download the project code.
[ { "code": null, "e": 1149, "s": 1062, "text": "This example demonstrates how to create Text to Speech in an Android App using Kotlin." }, { "code": null, "e": 1277, "s": 1149, "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": 1342, "s": 1277, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2947, "s": 1342, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"16dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:textColor=\"@android:color/holo_red_light\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold|italic\" />\n </LinearLayout>\n <LinearLayout\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentBottom=\"true\"\n android:layout_centerInParent=\"true\"\n android:orientation=\"vertical\">\n <ImageView\n android:id=\"@+id/speakImageView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:background=\"?selectableItemBackground\"\n android:src=\"@android:drawable/ic_btn_speak_now\" />\n </LinearLayout>\n</RelativeLayout>" }, { "code": null, "e": 2998, "s": 2947, "text": "Step 3 − Add the following code to MainActivity.kt" }, { "code": null, "e": 4614, "s": 2998, "text": "import android.app.Activity\nimport android.content.Intent\nimport android.os.Bundle\nimport android.speech.RecognizerIntent\nimport android.widget.ImageView\nimport android.widget.TextView\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nimport java.util.*\nimport kotlin.collections.ArrayList\nclass MainActivity : AppCompatActivity() {\n private val REQUESTCODE = 100\n lateinit var textView: TextView\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n textView = findViewById(R.id.textView)\n val speakImageView: ImageView = findViewById(R.id.speakImageView)\n speakImageView.setOnClickListener {\n val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)\n intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,\n RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)\n intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault())\n intent.putExtra(RecognizerIntent.EXTRA_PROMPT, \"Need to Speak\")\n startActivityForResult(intent, REQUESTCODE)\n Toast.makeText(applicationContext, \"Sorry your device not supported\", Toast.LENGTH_SHORT).show()\n }\n }\n override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {\n super.onActivityResult(requestCode, resultCode, data)\n if (resultCode == Activity.RESULT_OK && null != data) {\n val result: ArrayList<String> = data.getStringArrayListExtra(RecognizerIntent .EXTRA_RESULTS) textView.text = result[0]\n }\n }\n}" }, { "code": null, "e": 4669, "s": 4614, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5345, "s": 4669, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.kotlipapp\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5696, "s": 5345, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 5745, "s": 5696, "text": "NOTE− Test in your own device for better results" }, { "code": null, "e": 5786, "s": 5745, "text": "Click here to download the project code." } ]
How to change the partial plot background using ggplot2 in R?
To change the partial plot background, we can create a rectangle using geom_rect function by defining both the axes values and alpha for transparency, the color will be changed by using fill argument. The value of alpha will completely hide the grey background and we can play with its value based on our need. Live Demo Consider the below data frame − x<−rpois(20,5) y<−rpois(20,5) df<−data.frame(x,y) df x y 1 5 4 2 4 5 3 4 3 4 6 2 5 7 5 6 2 4 7 3 8 8 7 5 9 2 3 10 5 3 11 7 7 12 5 4 13 8 2 14 6 4 15 3 8 16 2 9 17 5 2 18 8 5 19 2 8 20 6 6 Loading ggplot2 package and creating a point chart between x and y − library(ggplot2) ggplot(df,aes(x,y))+geom_point() Creating a rectangle inside the plot to change the background of the plot − ggplot(df,aes(x,y))+geom_point()+geom_rect(aes(xmin=3,xmax=7,ymin=0,ymax=10),fill="green",alpha=0.05)
[ { "code": null, "e": 1373, "s": 1062, "text": "To change the partial plot background, we can create a rectangle using geom_rect function by defining both the axes values and alpha for transparency, the color will be changed by using fill argument. The value of alpha will completely hide the grey background and we can play with its value based on our need." }, { "code": null, "e": 1384, "s": 1373, "text": " Live Demo" }, { "code": null, "e": 1416, "s": 1384, "text": "Consider the below data frame −" }, { "code": null, "e": 1469, "s": 1416, "text": "x<−rpois(20,5)\ny<−rpois(20,5)\ndf<−data.frame(x,y)\ndf" }, { "code": null, "e": 1604, "s": 1469, "text": "x y\n1 5 4\n2 4 5\n3 4 3\n4 6 2\n5 7 5\n6 2 4\n7 3 8\n8 7 5\n9 2 3\n10 5 3\n11 7 7\n12 5 4\n13 8 2\n14 6 4\n15 3 8\n16 2 9\n17 5 2\n18 8 5\n19 2 8\n20 6 6" }, { "code": null, "e": 1673, "s": 1604, "text": "Loading ggplot2 package and creating a point chart between x and y −" }, { "code": null, "e": 1723, "s": 1673, "text": "library(ggplot2)\nggplot(df,aes(x,y))+geom_point()" }, { "code": null, "e": 1799, "s": 1723, "text": "Creating a rectangle inside the plot to change the background of the plot −" }, { "code": null, "e": 1901, "s": 1799, "text": "ggplot(df,aes(x,y))+geom_point()+geom_rect(aes(xmin=3,xmax=7,ymin=0,ymax=10),fill=\"green\",alpha=0.05)" } ]
How to detect if a specific key pressed using Python? - GeeksforGeeks
02 Dec, 2020 In this article, we will learn how can we detect if a specific key is pressed by the user or not. Detecting a key is very important for a coder, as the whole execution of the program is just dependent on a single/pattern key press. You may experience in your day-to-day life that the whole ATM transaction can be either accepted or denied when you press the enter key just after your PIN. In the same way, you will see many live examples in your day-to-day life. The whole Module is divided into 3 segments, The 1st segment deal with simple integers, 2nd Alphanumerical characters and In 3rd we will use a python module to detect a key. Method 1: Using pynput. In this method, we will use pynput python module to detecting any key press. “pynput.keyboard” contains classes for controlling and monitoring the keyboard. It Calls pynput.keyboard.Listener. stop from anywhere, or return False from a callback to stop the listener. This library allows you to control and monitor input devices. Approach: Import key, Listener from pynput.keyboard Create a with Statement: The with statement is used to wrap the execution of a block with methods defined by a context manager. Define functions For installation run this code into your terminal. pip install pynput Example 1: Here you will see which key is being pressed. Python3 from pynput.keyboard import Key, Listener def show(key): print('\nYou Entered {0}'.format( key)) if key == Key.delete: # Stop listener return False # Collect all event until releasedwith Listener(on_press = show) as listener: listener.join() Output: Example 2: Here you can detect a specific key is being been pressed or not. Python3 from pynput.keyboard import Key, Listener def show(key): if key == Key.tab: print("good") if key != Key.tab: print("try again") # by pressing 'delete' button # you can terminate the loop if key == Key.delete: return False # Collect all event until releasedwith Listener(on_press = show) as listener: listener.join() Output: Method 2: Here we are taking an input from a user and detecting that the user has entered the specified Alphanumerical(characters representing the numbers 0 – 9, the letters A – Z (both uppercase and lowercase), and some common symbols such as @ # * and &.) or not. Approach: Take user input Create a loop Use condition Print output Code: Python3 for _ in range(3): user_input = input(" Please enter your lucky word or type 'END' to terminate loop: ") if user_input == "geek": print("You are really a geek") break elif user_input == "END": break else: print("Try Again") Output: 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? Selecting rows in pandas DataFrame based on conditions Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24318, "s": 24290, "text": "\n02 Dec, 2020" }, { "code": null, "e": 24956, "s": 24318, "text": "In this article, we will learn how can we detect if a specific key is pressed by the user or not. Detecting a key is very important for a coder, as the whole execution of the program is just dependent on a single/pattern key press. You may experience in your day-to-day life that the whole ATM transaction can be either accepted or denied when you press the enter key just after your PIN. In the same way, you will see many live examples in your day-to-day life. The whole Module is divided into 3 segments, The 1st segment deal with simple integers, 2nd Alphanumerical characters and In 3rd we will use a python module to detect a key." }, { "code": null, "e": 24980, "s": 24956, "text": "Method 1: Using pynput." }, { "code": null, "e": 25308, "s": 24980, "text": "In this method, we will use pynput python module to detecting any key press. “pynput.keyboard” contains classes for controlling and monitoring the keyboard. It Calls pynput.keyboard.Listener. stop from anywhere, or return False from a callback to stop the listener. This library allows you to control and monitor input devices." }, { "code": null, "e": 25318, "s": 25308, "text": "Approach:" }, { "code": null, "e": 25360, "s": 25318, "text": "Import key, Listener from pynput.keyboard" }, { "code": null, "e": 25488, "s": 25360, "text": "Create a with Statement: The with statement is used to wrap the execution of a block with methods defined by a context manager." }, { "code": null, "e": 25505, "s": 25488, "text": "Define functions" }, { "code": null, "e": 25556, "s": 25505, "text": "For installation run this code into your terminal." }, { "code": null, "e": 25575, "s": 25556, "text": "pip install pynput" }, { "code": null, "e": 25632, "s": 25575, "text": "Example 1: Here you will see which key is being pressed." }, { "code": null, "e": 25640, "s": 25632, "text": "Python3" }, { "code": "from pynput.keyboard import Key, Listener def show(key): print('\\nYou Entered {0}'.format( key)) if key == Key.delete: # Stop listener return False # Collect all event until releasedwith Listener(on_press = show) as listener: listener.join()", "e": 25914, "s": 25640, "text": null }, { "code": null, "e": 25922, "s": 25914, "text": "Output:" }, { "code": null, "e": 25998, "s": 25922, "text": "Example 2: Here you can detect a specific key is being been pressed or not." }, { "code": null, "e": 26006, "s": 25998, "text": "Python3" }, { "code": "from pynput.keyboard import Key, Listener def show(key): if key == Key.tab: print(\"good\") if key != Key.tab: print(\"try again\") # by pressing 'delete' button # you can terminate the loop if key == Key.delete: return False # Collect all event until releasedwith Listener(on_press = show) as listener: listener.join()", "e": 26390, "s": 26006, "text": null }, { "code": null, "e": 26398, "s": 26390, "text": "Output:" }, { "code": null, "e": 26409, "s": 26398, "text": "Method 2: " }, { "code": null, "e": 26665, "s": 26409, "text": "Here we are taking an input from a user and detecting that the user has entered the specified Alphanumerical(characters representing the numbers 0 – 9, the letters A – Z (both uppercase and lowercase), and some common symbols such as @ # * and &.) or not." }, { "code": null, "e": 26675, "s": 26665, "text": "Approach:" }, { "code": null, "e": 26691, "s": 26675, "text": "Take user input" }, { "code": null, "e": 26705, "s": 26691, "text": "Create a loop" }, { "code": null, "e": 26719, "s": 26705, "text": "Use condition" }, { "code": null, "e": 26732, "s": 26719, "text": "Print output" }, { "code": null, "e": 26738, "s": 26732, "text": "Code:" }, { "code": null, "e": 26746, "s": 26738, "text": "Python3" }, { "code": "for _ in range(3): user_input = input(\" Please enter your lucky word or type 'END' to terminate loop: \") if user_input == \"geek\": print(\"You are really a geek\") break elif user_input == \"END\": break else: print(\"Try Again\")", "e": 27022, "s": 26746, "text": null }, { "code": null, "e": 27030, "s": 27022, "text": "Output:" }, { "code": null, "e": 27045, "s": 27030, "text": "python-utility" }, { "code": null, "e": 27052, "s": 27045, "text": "Python" }, { "code": null, "e": 27150, "s": 27052, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27182, "s": 27150, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27238, "s": 27182, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27280, "s": 27238, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27335, "s": 27280, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27377, "s": 27335, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27399, "s": 27377, "text": "Defaultdict in Python" }, { "code": null, "e": 27438, "s": 27399, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27469, "s": 27438, "text": "Python | os.path.join() method" }, { "code": null, "e": 27498, "s": 27469, "text": "Create a directory in Python" } ]
Arrow operator -> in C/C++ with Examples - GeeksforGeeks
06 Sep, 2021 An Arrow operator in C/C++ allows to access elements in Structures and Unions. It is used with a pointer variable pointing to a structure or union. The arrow operator is formed by using a minus sign, followed by the greater than symbol as shown below. Syntax: (pointer_name)->(variable_name) Operation: The -> operator in C or C++ gives the value held by variable_name to structure or union variable pointer_name.Difference between Dot(.) and Arrow(->) operator: The Dot(.) operator is used to normally access members of a structure or union. The Arrow(->) operator exists to access the members of the structure or the unions using pointers. Examples: Arrow operator in structure: C++ C // C++ program to show Arrow operator// used in structure#include <iostream>using namespace std; // Creating the structurestruct student { char name[80]; int age; float percentage;}; // Creating the structure objectstruct student* emp = NULL; // Driver codeint main(){ // Assigning memory to struct variable emp emp = (struct student*) malloc(sizeof(struct student)); // Assigning value to age variable // of emp using arrow operator emp->age = 18; // Printing the assigned value to the variable cout <<" "<< emp->age; return 0;} // This code is contributed by shivanisinghss2110 // C program to show Arrow operator// used in structure #include <stdio.h>#include <stdlib.h> // Creating the structurestruct student { char name[80]; int age; float percentage;}; // Creating the structure objectstruct student* emp = NULL; // Driver codeint main(){ // Assigning memory to struct variable emp emp = (struct student*) malloc(sizeof(struct student)); // Assigning value to age variable // of emp using arrow operator emp->age = 18; // Printing the assigned value to the variable printf("%d", emp->age); return 0;} 18 Arrow operator in unions: C++ C // C++ program to show Arrow operator// used in structure#include <iostream>using namespace std; // Creating the unionunion student { char name[80]; int age; float percentage;}; // Creating the union objectunion student* emp = NULL; // Driver codeint main(){ // Assigning memory to struct variable emp emp = (union student*) malloc(sizeof(union student)); // Assigning value to age variable // of emp using arrow operator emp->age = 18; // DIsplaying the assigned value to the variable cout <<""<< emp->age;} // This code is contributed by shivanisinghss2110 // C program to show Arrow operator// used in structure #include <stdio.h>#include <stdlib.h> // Creating the unionunion student { char name[80]; int age; float percentage;}; // Creating the union objectunion student* emp = NULL; // Driver codeint main(){ // Assigning memory to struct variable emp emp = (union student*) malloc(sizeof(union student)); // Assigning value to age variable // of emp using arrow operator emp->age = 18; // DIsplaying the assigned value to the variable printf("%d", emp->age);} 18 tanvibugdani shivanisinghss2110 C Language C Programs Competitive Programming Program Output Programming Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Multidimensional Arrays in C / C++ rand() and srand() in C/C++ fork() in C Core Dump (Segmentation fault) in C/C++ Left Shift and Right Shift Operators in C/C++ Strings in C UDP Server-Client implementation in C 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++?
[ { "code": null, "e": 24324, "s": 24296, "text": "\n06 Sep, 2021" }, { "code": null, "e": 24586, "s": 24324, "text": "An Arrow operator in C/C++ allows to access elements in Structures and Unions. It is used with a pointer variable pointing to a structure or union. The arrow operator is formed by using a minus sign, followed by the greater than symbol as shown below. Syntax: " }, { "code": null, "e": 24618, "s": 24586, "text": "(pointer_name)->(variable_name)" }, { "code": null, "e": 24791, "s": 24618, "text": "Operation: The -> operator in C or C++ gives the value held by variable_name to structure or union variable pointer_name.Difference between Dot(.) and Arrow(->) operator: " }, { "code": null, "e": 24871, "s": 24791, "text": "The Dot(.) operator is used to normally access members of a structure or union." }, { "code": null, "e": 24970, "s": 24871, "text": "The Arrow(->) operator exists to access the members of the structure or the unions using pointers." }, { "code": null, "e": 24981, "s": 24970, "text": "Examples: " }, { "code": null, "e": 25010, "s": 24981, "text": "Arrow operator in structure:" }, { "code": null, "e": 25014, "s": 25010, "text": "C++" }, { "code": null, "e": 25016, "s": 25014, "text": "C" }, { "code": "// C++ program to show Arrow operator// used in structure#include <iostream>using namespace std; // Creating the structurestruct student { char name[80]; int age; float percentage;}; // Creating the structure objectstruct student* emp = NULL; // Driver codeint main(){ // Assigning memory to struct variable emp emp = (struct student*) malloc(sizeof(struct student)); // Assigning value to age variable // of emp using arrow operator emp->age = 18; // Printing the assigned value to the variable cout <<\" \"<< emp->age; return 0;} // This code is contributed by shivanisinghss2110", "e": 25642, "s": 25016, "text": null }, { "code": "// C program to show Arrow operator// used in structure #include <stdio.h>#include <stdlib.h> // Creating the structurestruct student { char name[80]; int age; float percentage;}; // Creating the structure objectstruct student* emp = NULL; // Driver codeint main(){ // Assigning memory to struct variable emp emp = (struct student*) malloc(sizeof(struct student)); // Assigning value to age variable // of emp using arrow operator emp->age = 18; // Printing the assigned value to the variable printf(\"%d\", emp->age); return 0;}", "e": 26213, "s": 25642, "text": null }, { "code": null, "e": 26216, "s": 26213, "text": "18" }, { "code": null, "e": 26244, "s": 26218, "text": "Arrow operator in unions:" }, { "code": null, "e": 26248, "s": 26244, "text": "C++" }, { "code": null, "e": 26250, "s": 26248, "text": "C" }, { "code": "// C++ program to show Arrow operator// used in structure#include <iostream>using namespace std; // Creating the unionunion student { char name[80]; int age; float percentage;}; // Creating the union objectunion student* emp = NULL; // Driver codeint main(){ // Assigning memory to struct variable emp emp = (union student*) malloc(sizeof(union student)); // Assigning value to age variable // of emp using arrow operator emp->age = 18; // DIsplaying the assigned value to the variable cout <<\"\"<< emp->age;} // This code is contributed by shivanisinghss2110", "e": 26848, "s": 26250, "text": null }, { "code": "// C program to show Arrow operator// used in structure #include <stdio.h>#include <stdlib.h> // Creating the unionunion student { char name[80]; int age; float percentage;}; // Creating the union objectunion student* emp = NULL; // Driver codeint main(){ // Assigning memory to struct variable emp emp = (union student*) malloc(sizeof(union student)); // Assigning value to age variable // of emp using arrow operator emp->age = 18; // DIsplaying the assigned value to the variable printf(\"%d\", emp->age);}", "e": 27395, "s": 26848, "text": null }, { "code": null, "e": 27398, "s": 27395, "text": "18" }, { "code": null, "e": 27413, "s": 27400, "text": "tanvibugdani" }, { "code": null, "e": 27432, "s": 27413, "text": "shivanisinghss2110" }, { "code": null, "e": 27443, "s": 27432, "text": "C Language" }, { "code": null, "e": 27454, "s": 27443, "text": "C Programs" }, { "code": null, "e": 27478, "s": 27454, "text": "Competitive Programming" }, { "code": null, "e": 27493, "s": 27478, "text": "Program Output" }, { "code": null, "e": 27514, "s": 27493, "text": "Programming Language" }, { "code": null, "e": 27612, "s": 27514, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27621, "s": 27612, "text": "Comments" }, { "code": null, "e": 27634, "s": 27621, "text": "Old Comments" }, { "code": null, "e": 27669, "s": 27634, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 27697, "s": 27669, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 27709, "s": 27697, "text": "fork() in C" }, { "code": null, "e": 27749, "s": 27709, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 27795, "s": 27749, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 27808, "s": 27795, "text": "Strings in C" }, { "code": null, "e": 27846, "s": 27808, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 27887, "s": 27846, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 27922, "s": 27887, "text": "Header files in C/C++ and its uses" } ]
How to set the margins of a Matplotlib figure?
To set the margins of a matplotlib figure, we can use margins() method. Set the figure size and adjust the padding between and around the subplots. Create t and y data points using numpy. Add a subplot to the current figure at index 1. Plot t and y data points using plot() method. Set the title of the plot. Add a subplot to the current figure at index 2. Plot t and y data points using plot() method. Set the title of the plot. Set margins of the plot using margins(x=0, y=0). To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True t = np.linspace(-2, 2, 10) y = np.exp(-t) plt.subplot(121) plt.plot(t, y) plt.title("Without margins") plt.subplot(122) plt.plot(t, y) plt.title("With x=0 and y=0 margins") plt.margins(x=0, y=0) plt.show()
[ { "code": null, "e": 1134, "s": 1062, "text": "To set the margins of a matplotlib figure, we can use margins() method." }, { "code": null, "e": 1210, "s": 1134, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1250, "s": 1210, "text": "Create t and y data points using numpy." }, { "code": null, "e": 1298, "s": 1250, "text": "Add a subplot to the current figure at index 1." }, { "code": null, "e": 1344, "s": 1298, "text": "Plot t and y data points using plot() method." }, { "code": null, "e": 1371, "s": 1344, "text": "Set the title of the plot." }, { "code": null, "e": 1419, "s": 1371, "text": "Add a subplot to the current figure at index 2." }, { "code": null, "e": 1465, "s": 1419, "text": "Plot t and y data points using plot() method." }, { "code": null, "e": 1492, "s": 1465, "text": "Set the title of the plot." }, { "code": null, "e": 1541, "s": 1492, "text": "Set margins of the plot using margins(x=0, y=0)." }, { "code": null, "e": 1583, "s": 1541, "text": "To display the figure, use show() method." }, { "code": null, "e": 1934, "s": 1583, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nt = np.linspace(-2, 2, 10)\ny = np.exp(-t)\nplt.subplot(121)\nplt.plot(t, y)\nplt.title(\"Without margins\")\nplt.subplot(122)\nplt.plot(t, y)\nplt.title(\"With x=0 and y=0 margins\")\nplt.margins(x=0, y=0)\nplt.show()" } ]
How to initialize an array using lambda expression in Java?
An array is a fixed size element of the same type. The lambda expressions can also be used to initialize arrays in Java. But generic array initializes cannot be used. interface Algebra { int operate(int a, int b); } public class LambdaWithArray1 { public static void main(String[] args) { // Initialization of an array in Lambda Expression Algebra alg[] = new Algebra[] { (a, b) -> a+b, (a, b) -> a-b, (a, b) -> a*b, (a, b) -> a/b }; System.out.println("The addition of a and b is: " + alg[0].operate(30, 20)); System.out.println("The subtraction of a and b is: " + alg[1].operate(30, 20)); System.out.println("The multiplication of a and b is: " + alg[2].operate(30, 20)); System.out.println("The division of a and b is: " + alg[3].operate(30, 20)); } } The addition of a and b is: 50 The subtraction of a and b is: 10 The multiplication of a and b is: 600 The division of a and b is: 1 interface CustomArray<V> { V arrayValue(); } public class LambdaWithArray2 { public static void main(String args[]) { // Initilaize an array in Lambda Expression CustomArray<String>[] strArray = new CustomArray[] { () -> "Adithya", () -> "Jai", () -> "Raja", () -> "Surya" }; System.out.println(strArray[0].arrayValue()); System.out.println(strArray[1].arrayValue()); System.out.println(strArray[2].arrayValue()); System.out.println(strArray[3].arrayValue()); } } Adithya Jai Raja Surya
[ { "code": null, "e": 1229, "s": 1062, "text": "An array is a fixed size element of the same type. The lambda expressions can also be used to initialize arrays in Java. But generic array initializes cannot be used." }, { "code": null, "e": 2058, "s": 1229, "text": "interface Algebra {\n int operate(int a, int b);\n}\npublic class LambdaWithArray1 {\n public static void main(String[] args) {\n // Initialization of an array in Lambda Expression\n Algebra alg[] = new Algebra[] {\n (a, b) -> a+b,\n (a, b) -> a-b,\n (a, b) -> a*b,\n (a, b) -> a/b\n };\n System.out.println(\"The addition of a and b is: \" + alg[0].operate(30, 20));\n System.out.println(\"The subtraction of a and b is: \" + alg[1].operate(30, 20));\n System.out.println(\"The multiplication of a and b is: \" + alg[2].operate(30, 20));\n System.out.println(\"The division of a and b is: \" + alg[3].operate(30, 20));\n }\n}" }, { "code": null, "e": 2191, "s": 2058, "text": "The addition of a and b is: 50\nThe subtraction of a and b is: 10\nThe multiplication of a and b is: 600\nThe division of a and b is: 1" }, { "code": null, "e": 2961, "s": 2191, "text": "interface CustomArray<V> {\n V arrayValue();\n}\npublic class LambdaWithArray2 {\n public static void main(String args[]) {\n // Initilaize an array in Lambda Expression\n CustomArray<String>[] strArray = new CustomArray[] {\n () -> \"Adithya\",\n () -> \"Jai\",\n () -> \"Raja\",\n () -> \"Surya\"\n };\n System.out.println(strArray[0].arrayValue());\n System.out.println(strArray[1].arrayValue());\n System.out.println(strArray[2].arrayValue());\n System.out.println(strArray[3].arrayValue());\n }\n}" }, { "code": null, "e": 2984, "s": 2961, "text": "Adithya\nJai\nRaja\nSurya" } ]
Insert Data from Database to Spreadsheet
How to insert data from a database to a spread sheet using Java. Following is the program to insert data from a database to a spread sheet using Java. import java.io.File; import java.io.FileOutputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class InsertDataFromDataBaseToSpreadSheet { public static void main(String[] args) throws Exception { //Connecting to the database Class.forName("com.mysql.jdbc.Driver"); Connection connect = DriverManager.getConnection( "jdbc:mysql://localhost:3306/details", "root" , "password"); //Getting data from the table emp_tbl Statement statement = connect.createStatement(); ResultSet resultSet = statement.executeQuery("select * from student_data"); //Creating a Work Book XSSFWorkbook workbook = new XSSFWorkbook(); //Creating a Spread Sheet XSSFSheet spreadsheet = workbook.createSheet("employe db"); XSSFRow row = spreadsheet.createRow(1); XSSFCell cell; cell = row.createCell(1); cell.setCellValue("EMP ID"); cell = row.createCell(2); cell.setCellValue("EMP NAME"); cell = row.createCell(3); cell.setCellValue("DEG"); cell = row.createCell(4); cell.setCellValue("SALARY"); cell = row.createCell(5); cell.setCellValue("DEPT"); int i = 2; while(resultSet.next()) { row = spreadsheet.createRow(i); cell = row.createCell(1); cell.setCellValue(resultSet.getInt("ID")); cell = row.createCell(2); cell.setCellValue(resultSet.getString("NAME")); cell = row.createCell(3); cell.setCellValue(resultSet.getString("BRANCH")); cell = row.createCell(4); cell.setCellValue(resultSet.getString("PERCENTAGE")); cell = row.createCell(5); cell.setCellValue(resultSet.getString("EMAIL")); i++; } FileOutputStream out = new FileOutputStream( new File("C:/poiexcel/exceldatabase.xlsx")); workbook.write(out); out.close(); System.out.println("exceldatabase.xlsx written successfully"); } } mysql> select * from student_data; +----+--------+--------+------------+---------------------+ | ID | NAME | BRANCH | PERCENTAGE | EMAIL | +----+--------+--------+------------+---------------------+ | 1 | Ram | IT | 85 | [email protected] | | 2 | Rahim | EEE | 95 | [email protected] | | 3 | Robert | ECE | 90 | [email protected] | +----+--------+--------+------------+---------------------+ 3 rows in set (0.00 sec) Print Add Notes Bookmark this page
[ { "code": null, "e": 2133, "s": 2068, "text": "How to insert data from a database to a spread sheet using Java." }, { "code": null, "e": 2219, "s": 2133, "text": "Following is the program to insert data from a database to a spread sheet using Java." }, { "code": null, "e": 4561, "s": 2219, "text": "import java.io.File;\nimport java.io.FileOutputStream;\n\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\n\nimport org.apache.poi.xssf.usermodel.XSSFCell;\nimport org.apache.poi.xssf.usermodel.XSSFRow;\nimport org.apache.poi.xssf.usermodel.XSSFSheet;\nimport org.apache.poi.xssf.usermodel.XSSFWorkbook;\n\npublic class InsertDataFromDataBaseToSpreadSheet {\n public static void main(String[] args) throws Exception {\n\n //Connecting to the database\n Class.forName(\"com.mysql.jdbc.Driver\");\n Connection connect = DriverManager.getConnection(\n \"jdbc:mysql://localhost:3306/details\", \"root\" , \"password\");\n\n //Getting data from the table emp_tbl\n Statement statement = connect.createStatement();\n ResultSet resultSet = statement.executeQuery(\"select * from student_data\");\n\n //Creating a Work Book\n XSSFWorkbook workbook = new XSSFWorkbook();\n\n //Creating a Spread Sheet\n XSSFSheet spreadsheet = workbook.createSheet(\"employe db\");\n XSSFRow row = spreadsheet.createRow(1);\n XSSFCell cell;\n \n cell = row.createCell(1);\n cell.setCellValue(\"EMP ID\");\n \n cell = row.createCell(2);\n cell.setCellValue(\"EMP NAME\");\n \n cell = row.createCell(3);\n cell.setCellValue(\"DEG\");\n \n cell = row.createCell(4);\n cell.setCellValue(\"SALARY\");\n \n cell = row.createCell(5);\n cell.setCellValue(\"DEPT\");\n int i = 2;\n\n while(resultSet.next()) {\n row = spreadsheet.createRow(i);\n cell = row.createCell(1);\n cell.setCellValue(resultSet.getInt(\"ID\"));\n \n cell = row.createCell(2);\n cell.setCellValue(resultSet.getString(\"NAME\"));\n \n cell = row.createCell(3);\n cell.setCellValue(resultSet.getString(\"BRANCH\"));\n \n cell = row.createCell(4);\n cell.setCellValue(resultSet.getString(\"PERCENTAGE\"));\n \n cell = row.createCell(5);\n cell.setCellValue(resultSet.getString(\"EMAIL\"));\n i++;\n }\n \n FileOutputStream out = new FileOutputStream(\n new File(\"C:/poiexcel/exceldatabase.xlsx\"));\n \n workbook.write(out);\n out.close();\n \n System.out.println(\"exceldatabase.xlsx written successfully\");\n }\n}" }, { "code": null, "e": 5050, "s": 4561, "text": "mysql> select * from student_data; \n+----+--------+--------+------------+---------------------+ \n| ID | NAME | BRANCH | PERCENTAGE | EMAIL | \n+----+--------+--------+------------+---------------------+ \n| 1 | Ram | IT | 85 | [email protected] | \n| 2 | Rahim | EEE | 95 | [email protected] | \n| 3 | Robert | ECE | 90 | [email protected] | \n+----+--------+--------+------------+---------------------+ \n3 rows in set (0.00 sec)\n" }, { "code": null, "e": 5057, "s": 5050, "text": " Print" }, { "code": null, "e": 5068, "s": 5057, "text": " Add Notes" } ]
Natural Sort in JavaScript
We have an array that contains some numbers and some strings, we are required to sort the array such that the numbers get sorted and get placed before every string and then the string should be placed sorted alphabetically. Let’s say this is our array − const arr = [1, 'fdf', 'afv', 6, 47, 7, 'svd', 'bdf', 9]; The output should look like this − [1, 6, 7, 9, 47, 'afv', 'bdf', 'fdf', 'svd'] Therefore, let’s write the code for this − const arr = [1, 'fdf', 'afv', 6, 47, 7, 'svd', 'bdf', 9]; const sorter = (a, b) => { if(typeof a === 'number' && typeof b === 'number'){ return a - b; }else if(typeof a === 'number' && typeof b !== 'number'){ return -1; }else if(typeof a !== 'number' && typeof b === 'number'){ return 1; }else{ return a > b ? 1 : -1; } } arr.sort(sorter); console.log(arr); The output in the console will be − [ 1, 6, 7, 9, 47, 'afv', 'bdf', 'fdf', 'svd' ]
[ { "code": null, "e": 1286, "s": 1062, "text": "We have an array that contains some numbers and some strings, we are required to sort the\narray such that the numbers get sorted and get placed before every string and then the string\nshould be placed sorted alphabetically." }, { "code": null, "e": 1316, "s": 1286, "text": "Let’s say this is our array −" }, { "code": null, "e": 1374, "s": 1316, "text": "const arr = [1, 'fdf', 'afv', 6, 47, 7, 'svd', 'bdf', 9];" }, { "code": null, "e": 1409, "s": 1374, "text": "The output should look like this −" }, { "code": null, "e": 1454, "s": 1409, "text": "[1, 6, 7, 9, 47, 'afv', 'bdf', 'fdf', 'svd']" }, { "code": null, "e": 1497, "s": 1454, "text": "Therefore, let’s write the code for this −" }, { "code": null, "e": 1894, "s": 1497, "text": "const arr = [1, 'fdf', 'afv', 6, 47, 7, 'svd', 'bdf', 9];\nconst sorter = (a, b) => {\n if(typeof a === 'number' && typeof b === 'number'){\n return a - b;\n }else if(typeof a === 'number' && typeof b !== 'number'){\n return -1;\n }else if(typeof a !== 'number' && typeof b === 'number'){\n return 1;\n }else{\n return a > b ? 1 : -1;\n }\n}\narr.sort(sorter);\nconsole.log(arr);" }, { "code": null, "e": 1930, "s": 1894, "text": "The output in the console will be −" }, { "code": null, "e": 1986, "s": 1930, "text": "[\n 1, 6, 7,\n 9, 47, 'afv',\n 'bdf', 'fdf', 'svd'\n]" } ]
Is it possible to select text boxes with JavaScript?
Yes, select text box with JavaScript using the select() method. At first, let us create an input text − Enter your Name:<input type="text" id="txtName" value="John"> <br> <button type="button" onclick="check()">Select Text Box</button> Now, let us select the text box on button click − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale=1.0"> <title>Document</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head> <body> Enter your Name:<input type="text" id="txtName" value="John"> <br> <button type="button" onclick="check()">Select Text Box</button> <script> function check(){ document.getElementById("txtName").select(); } </script> </body> </html> To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor. This will produce the following output − When you click the button “Select Text Box”, it will select the text box. This will produce the following output −
[ { "code": null, "e": 1166, "s": 1062, "text": "Yes, select text box with JavaScript using the select() method. At first, let us create an input\ntext −" }, { "code": null, "e": 1298, "s": 1166, "text": "Enter your Name:<input type=\"text\" id=\"txtName\" value=\"John\">\n<br>\n<button type=\"button\" onclick=\"check()\">Select Text Box</button>" }, { "code": null, "e": 1348, "s": 1298, "text": "Now, let us select the text box on button click −" }, { "code": null, "e": 1359, "s": 1348, "text": " Live Demo" }, { "code": null, "e": 1996, "s": 1359, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n</head>\n<body>\nEnter your Name:<input type=\"text\" id=\"txtName\" value=\"John\">\n<br>\n<button type=\"button\" onclick=\"check()\">Select Text Box</button>\n<script>\n function check(){\n document.getElementById(\"txtName\").select();\n }\n</script>\n</body>\n</html>" }, { "code": null, "e": 2158, "s": 1996, "text": "To run the above program, save the file name “anyName.html(index.html)” and right click on the\nfile. Select the option “Open with Live Server” in VS Code editor." }, { "code": null, "e": 2199, "s": 2158, "text": "This will produce the following output −" }, { "code": null, "e": 2314, "s": 2199, "text": "When you click the button “Select Text Box”, it will select the text box. This will produce the\nfollowing output −" } ]
PyQt5 - How to hide the items from drop down box in Combo Box - GeeksforGeeks
22 Apr, 2020 In this article we will see how we can hide the items of the combo box from the drop down box i.e from view box. In order to do so we have to get the view object of combo box and had to hide it. In order to hide the items we have to do the following steps – 1. Create Combo box2. Add items to the combo box3. Get the view object of combo box4. Hide the view object Syntax : # getting view part of combo box view = self.combo_box.view() # hiding the view part view.setHidden(True) Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 150, 30) # geek list geek_list = ["Sayian", "Super Sayian", "Super Sayian 2", "Super Sayian B"] # making it editable self.combo_box.setEditable(True) # adding list of items to combo box self.combo_box.addItems(geek_list) # getting view part of combo box view = self.combo_box.view() # making view box hidden view.setHidden(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt5-ComboBox Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Convert integer to string in Python
[ { "code": null, "e": 26259, "s": 26231, "text": "\n22 Apr, 2020" }, { "code": null, "e": 26454, "s": 26259, "text": "In this article we will see how we can hide the items of the combo box from the drop down box i.e from view box. In order to do so we have to get the view object of combo box and had to hide it." }, { "code": null, "e": 26517, "s": 26454, "text": "In order to hide the items we have to do the following steps –" }, { "code": null, "e": 26624, "s": 26517, "text": "1. Create Combo box2. Add items to the combo box3. Get the view object of combo box4. Hide the view object" }, { "code": null, "e": 26633, "s": 26624, "text": "Syntax :" }, { "code": null, "e": 26741, "s": 26633, "text": "# getting view part of combo box\nview = self.combo_box.view()\n\n# hiding the view part\nview.setHidden(True)\n" }, { "code": null, "e": 26769, "s": 26741, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 150, 30) # geek list geek_list = [\"Sayian\", \"Super Sayian\", \"Super Sayian 2\", \"Super Sayian B\"] # making it editable self.combo_box.setEditable(True) # adding list of items to combo box self.combo_box.addItems(geek_list) # getting view part of combo box view = self.combo_box.view() # making view box hidden view.setHidden(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 28003, "s": 26769, "text": null }, { "code": null, "e": 28012, "s": 28003, "text": "Output :" }, { "code": null, "e": 28034, "s": 28012, "text": "Python PyQt5-ComboBox" }, { "code": null, "e": 28045, "s": 28034, "text": "Python-gui" }, { "code": null, "e": 28057, "s": 28045, "text": "Python-PyQt" }, { "code": null, "e": 28064, "s": 28057, "text": "Python" }, { "code": null, "e": 28162, "s": 28064, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28180, "s": 28162, "text": "Python Dictionary" }, { "code": null, "e": 28215, "s": 28180, "text": "Read a file line by line in Python" }, { "code": null, "e": 28247, "s": 28215, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28269, "s": 28247, "text": "Enumerate() in Python" }, { "code": null, "e": 28311, "s": 28269, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28341, "s": 28311, "text": "Iterate over a list in Python" }, { "code": null, "e": 28367, "s": 28341, "text": "Python String | replace()" }, { "code": null, "e": 28411, "s": 28367, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28440, "s": 28411, "text": "*args and **kwargs in Python" } ]
Box Stacking Problem | DP-22 - GeeksforGeeks
30 Jun, 2021 You are given a set of n types of rectangular 3-D boxes, where the i^th box has height h(i), width w(i) and depth d(i) (all real numbers). You want to create a stack of boxes which is as tall as possible, but you can only stack a box on top of another box if the dimensions of the 2-D base of the lower box are each strictly larger than those of the 2-D base of the higher box. Of course, you can rotate a box so that any side functions as its base. It is also allowable to use multiple instances of the same type of box. Source: http://people.csail.mit.edu/bdean/6.046/dp/. The link also has a video for an explanation of the solution. The Box Stacking problem is a variation of LIS problem. We need to build a maximum height stack. Following are the key points to note in the problem statement: 1) A box can be placed on top of another box only if both width and depth of the upper placed box are smaller than width and depth of the lower box respectively. 2) We can rotate boxes such that width is smaller than depth. For example, if there is a box with dimensions {1x2x3} where 1 is height, 2×3 is base, then there can be three possibilities, {1x2x3}, {2x1x3} and {3x1x2} 3) We can use multiple instances of boxes. What it means is, we can have two different rotations of a box as part of our maximum height stack.Following is the solution based on DP solution of LIS problem. Method 1 : dynamic programming using tabulation 1) Generate all 3 rotations of all boxes. The size of rotation array becomes 3 times the size of the original array. For simplicity, we consider width as always smaller than or equal to depth. 2) Sort the above generated 3n boxes in decreasing order of base area.3) After sorting the boxes, the problem is same as LIS with following optimal substructure property. MSH(i) = Maximum possible Stack Height with box i at top of stack MSH(i) = { Max ( MSH(j) ) + height(i) } where j < i and width(j) > width(i) and depth(j) > depth(i). If there is no such j then MSH(i) = height(i)4) To get overall maximum height, we return max(MSH(i)) where 0 < i < nFollowing is the implementation of the above solution. C++ Java Python3 /* Dynamic Programming implementation of Box Stacking problem */#include<stdio.h>#include<stdlib.h> /* Representation of a box */struct Box{ // h --> height, w --> width, d --> depth int h, w, d; // for simplicity of solution, always keep w <= d}; // A utility function to get minimum of two integersint min (int x, int y){ return (x < y)? x : y; } // A utility function to get maximum of two integersint max (int x, int y){ return (x > y)? x : y; } /* Following function is needed for library function qsort(). We use qsort() to sort boxes in decreasing order of base area. Refer following link for help of qsort() and compare() http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */int compare (const void *a, const void * b){ return ( (*(Box *)b).d * (*(Box *)b).w ) - ( (*(Box *)a).d * (*(Box *)a).w );} /* Returns the height of the tallest stack that can be formed with give type of boxes */int maxStackHeight( Box arr[], int n ){ /* Create an array of all rotations of given boxes For example, for a box {1, 2, 3}, we consider three instances{{1, 2, 3}, {2, 1, 3}, {3, 1, 2}} */ Box rot[3*n]; int index = 0; for (int i = 0; i < n; i++) { // Copy the original box rot[index].h = arr[i].h; rot[index].d = max(arr[i].d, arr[i].w); rot[index].w = min(arr[i].d, arr[i].w); index++; // First rotation of box rot[index].h = arr[i].w; rot[index].d = max(arr[i].h, arr[i].d); rot[index].w = min(arr[i].h, arr[i].d); index++; // Second rotation of box rot[index].h = arr[i].d; rot[index].d = max(arr[i].h, arr[i].w); rot[index].w = min(arr[i].h, arr[i].w); index++; } // Now the number of boxes is 3n n = 3*n; /* Sort the array 'rot[]' in non-increasing order of base area */ qsort (rot, n, sizeof(rot[0]), compare); // Uncomment following two lines to print all rotations // for (int i = 0; i < n; i++ ) // printf("%d x %d x %d\n", rot[i].h, rot[i].w, rot[i].d); /* Initialize msh values for all indexes msh[i] --> Maximum possible Stack Height with box i on top */ int msh[n]; for (int i = 0; i < n; i++ ) msh[i] = rot[i].h; /* Compute optimized msh values in bottom up manner */ for (int i = 1; i < n; i++ ) for (int j = 0; j < i; j++ ) if ( rot[i].w < rot[j].w && rot[i].d < rot[j].d && msh[i] < msh[j] + rot[i].h ) { msh[i] = msh[j] + rot[i].h; } /* Pick maximum of all msh values */ int max = -1; for ( int i = 0; i < n; i++ ) if ( max < msh[i] ) max = msh[i]; return max;} /* Driver program to test above function */int main(){ Box arr[] = { {4, 6, 7}, {1, 2, 3}, {4, 5, 6}, {10, 12, 32} }; int n = sizeof(arr)/sizeof(arr[0]); printf("The maximum possible height of stack is %d\n", maxStackHeight (arr, n) ); return 0;} /* Dynamic Programming implementationof Box Stacking problem in Java*/import java.util.*; public class GFG { /* Representation of a box */ static class Box implements Comparable<Box>{ // h --> height, w --> width, // d --> depth int h, w, d, area; // for simplicity of solution, // always keep w <= d /*Constructor to initialise object*/ public Box(int h, int w, int d) { this.h = h; this.w = w; this.d = d; } /*To sort the box array on the basis of area in decreasing order of area */ @Override public int compareTo(Box o) { return o.area-this.area; } } /* Returns the height of the tallest stack that can be formed with give type of boxes */ static int maxStackHeight( Box arr[], int n){ Box[] rot = new Box[n*3]; /* New Array of boxes is created - considering all 3 possible rotations, with width always greater than equal to width */ for(int i = 0;i < n;i++){ Box box = arr[i]; /* Original Box*/ rot[3*i] = new Box(box.h, Math.max(box.w,box.d), Math.min(box.w,box.d)); /* First rotation of box*/ rot[3*i + 1] = new Box(box.w, Math.max(box.h,box.d), Math.min(box.h,box.d)); /* Second rotation of box*/ rot[3*i + 2] = new Box(box.d, Math.max(box.w,box.h), Math.min(box.w,box.h)); } /* Calculating base area of each of the boxes.*/ for(int i = 0; i < rot.length; i++) rot[i].area = rot[i].w * rot[i].d; /* Sorting the Boxes on the bases of Area in non Increasing order.*/ Arrays.sort(rot); int count = 3 * n; /* Initialize msh values for all indexes msh[i] --> Maximum possible Stack Height with box i on top */ int[]msh = new int[count]; for (int i = 0; i < count; i++ ) msh[i] = rot[i].h; /* Computing optimized msh[] values in bottom up manner */ for(int i = 0; i < count; i++){ msh[i] = 0; Box box = rot[i]; int val = 0; for(int j = 0; j < i; j++){ Box prevBox = rot[j]; if(box.w < prevBox.w && box.d < prevBox.d){ val = Math.max(val, msh[j]); } } msh[i] = val + box.h; } int max = -1; /* Pick maximum of all msh values */ for(int i = 0; i < count; i++){ max = Math.max(max, msh[i]); } return max; } /* Driver program to test above function */ public static void main(String[] args) { Box[] arr = new Box[4]; arr[0] = new Box(4, 6, 7); arr[1] = new Box(1, 2, 3); arr[2] = new Box(4, 5, 6); arr[3] = new Box(10, 12, 32); System.out.println("The maximum possible "+ "height of stack is " + maxStackHeight(arr,4)); }} // This code is contributed by Divyam # Dynamic Programming implementation# of Box Stacking problemclass Box: # Representation of a box def __init__(self, h, w, d): self.h = h self.w = w self.d = d def __lt__(self, other): return self.d * self.w < other.d * other.w def maxStackHeight(arr, n): # Create an array of all rotations of # given boxes. For example, for a box {1, 2, 3}, # we consider three instances{{1, 2, 3}, # {2, 1, 3}, {3, 1, 2}} rot = [Box(0, 0, 0) for _ in range(3 * n)] index = 0 for i in range(n): # Copy the original box rot[index].h = arr[i].h rot[index].d = max(arr[i].d, arr[i].w) rot[index].w = min(arr[i].d, arr[i].w) index += 1 # First rotation of the box rot[index].h = arr[i].w rot[index].d = max(arr[i].h, arr[i].d) rot[index].w = min(arr[i].h, arr[i].d) index += 1 # Second rotation of the box rot[index].h = arr[i].d rot[index].d = max(arr[i].h, arr[i].w) rot[index].w = min(arr[i].h, arr[i].w) index += 1 # Now the number of boxes is 3n n *= 3 # Sort the array 'rot[]' in non-increasing # order of base area rot.sort(reverse = True) # Uncomment following two lines to print # all rotations # for i in range(n): # print(rot[i].h, 'x', rot[i].w, 'x', rot[i].d) # Initialize msh values for all indexes # msh[i] --> Maximum possible Stack Height # with box i on top msh = [0] * n for i in range(n): msh[i] = rot[i].h # Compute optimized msh values # in bottom up manner for i in range(1, n): for j in range(0, i): if (rot[i].w < rot[j].w and rot[i].d < rot[j].d): if msh[i] < msh[j] + rot[i].h: msh[i] = msh[j] + rot[i].h maxm = -1 for i in range(n): maxm = max(maxm, msh[i]) return maxm # Driver Codeif __name__ == "__main__": arr = [Box(4, 6, 7), Box(1, 2, 3), Box(4, 5, 6), Box(10, 12, 32)] n = len(arr) print("The maximum possible height of stack is", maxStackHeight(arr, n)) # This code is contributed by vibhu4agarwal The maximum possible height of stack is 60 In the above program, given input boxes are {4, 6, 7}, {1, 2, 3}, {4, 5, 6}, {10, 12, 32}. Following are all rotations of the boxes in decreasing order of base area. 10 x 12 x 32 12 x 10 x 32 32 x 10 x 12 4 x 6 x 7 4 x 5 x 6 6 x 4 x 7 5 x 4 x 6 7 x 4 x 6 6 x 4 x 5 1 x 2 x 3 2 x 1 x 3 3 x 1 x 2 The height 60 is obtained by boxes { {3, 1, 2}, {1, 2, 3}, {6, 4, 5}, {4, 5, 6}, {4, 6, 7}, {32, 10, 12}, {10, 12, 32}}Time Complexity: O(n^2) Auxiliary Space: O(n) Method 2 : dynamic programming using memoization (top-down) C++ /* Dynamic Programming top-down implementation of Box * Stacking problem */#include <bits/stdc++.h>using namespace std; /* Representation of a box */class Box {public: int length; int width; int height;}; // dp arrayint dp[303]; /* boxes -> vector of Box bottom_box_index -> index of the bottom box index -> index of current box*//* NOTE: we can use only one variable in place of bottom_box_index and index but it has been avoided to make it simple */int findMaxHeight(vector<Box>& boxes, int bottom_box_index, int index){ // base case if (index < 0) return 0; if (dp[index] != -1) return dp[index]; int maximumHeight = 0; // recurse for (int i = index; i >= 0; i--) { // if there is no bottom box if (bottom_box_index == -1 // or if length & width of new box is < that of // bottom box || (boxes[i].length < boxes[bottom_box_index].length && boxes[i].width < boxes[bottom_box_index].width)) maximumHeight = max(maximumHeight, findMaxHeight(boxes, i, i - 1) + boxes[i].height); } return dp[index] = maximumHeight;} /* wrapper function for recursive calls whichReturns the height of the tallest stack that can beformed with give type of boxes */int maxStackHeight(int height[], int width[], int length[], int types){ // creating a vector of type Box class vector<Box> boxes; // Initialize dp array with -1 memset(dp, -1, sizeof(dp)); Box box; /* Create an array of all rotations of given boxes For example, for a box {1, 2, 3}, we consider three instances{{1, 2, 3}, {2, 1, 3}, {3, 1, 2}} */ for (int i = 0; i < types; i++) { // copy original box box.height = height[i]; box.length = max(length[i], width[i]); box.width = min(length[i], width[i]); boxes.push_back(box); // First rotation of box box.height = width[i]; box.length = max(length[i], height[i]); box.width = min(length[i], height[i]); boxes.push_back(box); // Second rotation of box box.height = length[i]; box.length = max(width[i], height[i]); box.width = min(width[i], height[i]); boxes.push_back(box); } // sort by area in ascending order .. because we will be dealing with this vector in reverse sort(boxes.begin(), boxes.end(), [](Box b1, Box b2) { // if area of box1 < area of box2 return (b1.length * b1.width) < (b2.length * b2.width); }); // Uncomment following two lines to print all rotations //for (int i = boxes.size() - 1; i >= 0; i-- ) // printf("%d x %d x %d\n", boxes[i].length, boxes[i].width, boxes[i].height); return findMaxHeight(boxes, -1, boxes.size() - 1);} int main(){ // where length, width and height of a particular box // are at ith index of the following arrays int length[] = { 4, 1, 4, 10 }; int width[] = { 6, 2, 5, 12 }; int height[] = { 7, 3, 6, 32 }; int n = sizeof(length) / sizeof(length[0]); printf("The maximum possible height of stack is %d\n", maxStackHeight(height, length, width, n)); return 0;} The maximum possible height of stack is 60 In the above program, for boxes of dimensions of {4, 6, 7}, {1, 2, 3}, {4, 5, 6}, {10, 12, 32} on giving the input as {4, 1, 4, 10} for length, {6, 2, 5, 12} for width and {7, 3, 6, 32} for height. Following rotations are possible for the boxes in decreasing order of base area. 32 x 12 x 10 <- 32 x 10 x 12 12 x 10 x 32 <- 7 x 6 x 4 <- 6 x 5 x 4 <- 7 x 4 x 6 6 x 4 x 5 6 x 4 x 7 5 x 4 x 6 <- 3 x 2 x 1 <- 3 x 1 x 2 2 x 1 x 3 <- The maximum possible height of stack is 60 The height 60 is obtained by boxes { {2, 1, 3}, {3, 2, 1}, {5, 4, 6}, {6, 5, 4}, {7, 6, 4}, {12, 10, 32}, {32, 12, 10}} YouTubeGeeksforGeeks507K subscribersBox Stacking Problem | Dynamic Programming (Set 22) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:27•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=KgWy0fY0dRM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vibhu4agarwal dumbledee aj941ga khushboogoyal499 arorakashish0911 Amazon Codenation Microsoft Dynamic Programming Amazon Microsoft Codenation Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Subset Sum Problem | DP-25 Coin Change | DP-7 Matrix Chain Multiplication | DP-8 Longest Palindromic Substring | Set 1 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Edit Distance | DP-5 Sieve of Eratosthenes Overlapping Subproblems Property in Dynamic Programming | DP-1
[ { "code": null, "e": 26499, "s": 26471, "text": "\n30 Jun, 2021" }, { "code": null, "e": 27137, "s": 26499, "text": "You are given a set of n types of rectangular 3-D boxes, where the i^th box has height h(i), width w(i) and depth d(i) (all real numbers). You want to create a stack of boxes which is as tall as possible, but you can only stack a box on top of another box if the dimensions of the 2-D base of the lower box are each strictly larger than those of the 2-D base of the higher box. Of course, you can rotate a box so that any side functions as its base. It is also allowable to use multiple instances of the same type of box. Source: http://people.csail.mit.edu/bdean/6.046/dp/. The link also has a video for an explanation of the solution. " }, { "code": null, "e": 27883, "s": 27139, "text": "The Box Stacking problem is a variation of LIS problem. We need to build a maximum height stack. Following are the key points to note in the problem statement: 1) A box can be placed on top of another box only if both width and depth of the upper placed box are smaller than width and depth of the lower box respectively. 2) We can rotate boxes such that width is smaller than depth. For example, if there is a box with dimensions {1x2x3} where 1 is height, 2×3 is base, then there can be three possibilities, {1x2x3}, {2x1x3} and {3x1x2} 3) We can use multiple instances of boxes. What it means is, we can have two different rotations of a box as part of our maximum height stack.Following is the solution based on DP solution of LIS problem." }, { "code": null, "e": 27931, "s": 27883, "text": "Method 1 : dynamic programming using tabulation" }, { "code": null, "e": 28635, "s": 27931, "text": "1) Generate all 3 rotations of all boxes. The size of rotation array becomes 3 times the size of the original array. For simplicity, we consider width as always smaller than or equal to depth. 2) Sort the above generated 3n boxes in decreasing order of base area.3) After sorting the boxes, the problem is same as LIS with following optimal substructure property. MSH(i) = Maximum possible Stack Height with box i at top of stack MSH(i) = { Max ( MSH(j) ) + height(i) } where j < i and width(j) > width(i) and depth(j) > depth(i). If there is no such j then MSH(i) = height(i)4) To get overall maximum height, we return max(MSH(i)) where 0 < i < nFollowing is the implementation of the above solution. " }, { "code": null, "e": 28639, "s": 28635, "text": "C++" }, { "code": null, "e": 28644, "s": 28639, "text": "Java" }, { "code": null, "e": 28652, "s": 28644, "text": "Python3" }, { "code": "/* Dynamic Programming implementation of Box Stacking problem */#include<stdio.h>#include<stdlib.h> /* Representation of a box */struct Box{ // h --> height, w --> width, d --> depth int h, w, d; // for simplicity of solution, always keep w <= d}; // A utility function to get minimum of two integersint min (int x, int y){ return (x < y)? x : y; } // A utility function to get maximum of two integersint max (int x, int y){ return (x > y)? x : y; } /* Following function is needed for library function qsort(). We use qsort() to sort boxes in decreasing order of base area. Refer following link for help of qsort() and compare() http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */int compare (const void *a, const void * b){ return ( (*(Box *)b).d * (*(Box *)b).w ) - ( (*(Box *)a).d * (*(Box *)a).w );} /* Returns the height of the tallest stack that can be formed with give type of boxes */int maxStackHeight( Box arr[], int n ){ /* Create an array of all rotations of given boxes For example, for a box {1, 2, 3}, we consider three instances{{1, 2, 3}, {2, 1, 3}, {3, 1, 2}} */ Box rot[3*n]; int index = 0; for (int i = 0; i < n; i++) { // Copy the original box rot[index].h = arr[i].h; rot[index].d = max(arr[i].d, arr[i].w); rot[index].w = min(arr[i].d, arr[i].w); index++; // First rotation of box rot[index].h = arr[i].w; rot[index].d = max(arr[i].h, arr[i].d); rot[index].w = min(arr[i].h, arr[i].d); index++; // Second rotation of box rot[index].h = arr[i].d; rot[index].d = max(arr[i].h, arr[i].w); rot[index].w = min(arr[i].h, arr[i].w); index++; } // Now the number of boxes is 3n n = 3*n; /* Sort the array 'rot[]' in non-increasing order of base area */ qsort (rot, n, sizeof(rot[0]), compare); // Uncomment following two lines to print all rotations // for (int i = 0; i < n; i++ ) // printf(\"%d x %d x %d\\n\", rot[i].h, rot[i].w, rot[i].d); /* Initialize msh values for all indexes msh[i] --> Maximum possible Stack Height with box i on top */ int msh[n]; for (int i = 0; i < n; i++ ) msh[i] = rot[i].h; /* Compute optimized msh values in bottom up manner */ for (int i = 1; i < n; i++ ) for (int j = 0; j < i; j++ ) if ( rot[i].w < rot[j].w && rot[i].d < rot[j].d && msh[i] < msh[j] + rot[i].h ) { msh[i] = msh[j] + rot[i].h; } /* Pick maximum of all msh values */ int max = -1; for ( int i = 0; i < n; i++ ) if ( max < msh[i] ) max = msh[i]; return max;} /* Driver program to test above function */int main(){ Box arr[] = { {4, 6, 7}, {1, 2, 3}, {4, 5, 6}, {10, 12, 32} }; int n = sizeof(arr)/sizeof(arr[0]); printf(\"The maximum possible height of stack is %d\\n\", maxStackHeight (arr, n) ); return 0;}", "e": 31569, "s": 28652, "text": null }, { "code": "/* Dynamic Programming implementationof Box Stacking problem in Java*/import java.util.*; public class GFG { /* Representation of a box */ static class Box implements Comparable<Box>{ // h --> height, w --> width, // d --> depth int h, w, d, area; // for simplicity of solution, // always keep w <= d /*Constructor to initialise object*/ public Box(int h, int w, int d) { this.h = h; this.w = w; this.d = d; } /*To sort the box array on the basis of area in decreasing order of area */ @Override public int compareTo(Box o) { return o.area-this.area; } } /* Returns the height of the tallest stack that can be formed with give type of boxes */ static int maxStackHeight( Box arr[], int n){ Box[] rot = new Box[n*3]; /* New Array of boxes is created - considering all 3 possible rotations, with width always greater than equal to width */ for(int i = 0;i < n;i++){ Box box = arr[i]; /* Original Box*/ rot[3*i] = new Box(box.h, Math.max(box.w,box.d), Math.min(box.w,box.d)); /* First rotation of box*/ rot[3*i + 1] = new Box(box.w, Math.max(box.h,box.d), Math.min(box.h,box.d)); /* Second rotation of box*/ rot[3*i + 2] = new Box(box.d, Math.max(box.w,box.h), Math.min(box.w,box.h)); } /* Calculating base area of each of the boxes.*/ for(int i = 0; i < rot.length; i++) rot[i].area = rot[i].w * rot[i].d; /* Sorting the Boxes on the bases of Area in non Increasing order.*/ Arrays.sort(rot); int count = 3 * n; /* Initialize msh values for all indexes msh[i] --> Maximum possible Stack Height with box i on top */ int[]msh = new int[count]; for (int i = 0; i < count; i++ ) msh[i] = rot[i].h; /* Computing optimized msh[] values in bottom up manner */ for(int i = 0; i < count; i++){ msh[i] = 0; Box box = rot[i]; int val = 0; for(int j = 0; j < i; j++){ Box prevBox = rot[j]; if(box.w < prevBox.w && box.d < prevBox.d){ val = Math.max(val, msh[j]); } } msh[i] = val + box.h; } int max = -1; /* Pick maximum of all msh values */ for(int i = 0; i < count; i++){ max = Math.max(max, msh[i]); } return max; } /* Driver program to test above function */ public static void main(String[] args) { Box[] arr = new Box[4]; arr[0] = new Box(4, 6, 7); arr[1] = new Box(1, 2, 3); arr[2] = new Box(4, 5, 6); arr[3] = new Box(10, 12, 32); System.out.println(\"The maximum possible \"+ \"height of stack is \" + maxStackHeight(arr,4)); }} // This code is contributed by Divyam", "e": 34949, "s": 31569, "text": null }, { "code": "# Dynamic Programming implementation# of Box Stacking problemclass Box: # Representation of a box def __init__(self, h, w, d): self.h = h self.w = w self.d = d def __lt__(self, other): return self.d * self.w < other.d * other.w def maxStackHeight(arr, n): # Create an array of all rotations of # given boxes. For example, for a box {1, 2, 3}, # we consider three instances{{1, 2, 3}, # {2, 1, 3}, {3, 1, 2}} rot = [Box(0, 0, 0) for _ in range(3 * n)] index = 0 for i in range(n): # Copy the original box rot[index].h = arr[i].h rot[index].d = max(arr[i].d, arr[i].w) rot[index].w = min(arr[i].d, arr[i].w) index += 1 # First rotation of the box rot[index].h = arr[i].w rot[index].d = max(arr[i].h, arr[i].d) rot[index].w = min(arr[i].h, arr[i].d) index += 1 # Second rotation of the box rot[index].h = arr[i].d rot[index].d = max(arr[i].h, arr[i].w) rot[index].w = min(arr[i].h, arr[i].w) index += 1 # Now the number of boxes is 3n n *= 3 # Sort the array 'rot[]' in non-increasing # order of base area rot.sort(reverse = True) # Uncomment following two lines to print # all rotations # for i in range(n): # print(rot[i].h, 'x', rot[i].w, 'x', rot[i].d) # Initialize msh values for all indexes # msh[i] --> Maximum possible Stack Height # with box i on top msh = [0] * n for i in range(n): msh[i] = rot[i].h # Compute optimized msh values # in bottom up manner for i in range(1, n): for j in range(0, i): if (rot[i].w < rot[j].w and rot[i].d < rot[j].d): if msh[i] < msh[j] + rot[i].h: msh[i] = msh[j] + rot[i].h maxm = -1 for i in range(n): maxm = max(maxm, msh[i]) return maxm # Driver Codeif __name__ == \"__main__\": arr = [Box(4, 6, 7), Box(1, 2, 3), Box(4, 5, 6), Box(10, 12, 32)] n = len(arr) print(\"The maximum possible height of stack is\", maxStackHeight(arr, n)) # This code is contributed by vibhu4agarwal", "e": 37120, "s": 34949, "text": null }, { "code": null, "e": 37163, "s": 37120, "text": "The maximum possible height of stack is 60" }, { "code": null, "e": 37330, "s": 37163, "text": "In the above program, given input boxes are {4, 6, 7}, {1, 2, 3}, {4, 5, 6}, {10, 12, 32}. Following are all rotations of the boxes in decreasing order of base area. " }, { "code": null, "e": 37495, "s": 37330, "text": " 10 x 12 x 32\n 12 x 10 x 32\n 32 x 10 x 12\n 4 x 6 x 7\n 4 x 5 x 6\n 6 x 4 x 7\n 5 x 4 x 6\n 7 x 4 x 6\n 6 x 4 x 5\n 1 x 2 x 3\n 2 x 1 x 3\n 3 x 1 x 2" }, { "code": null, "e": 37660, "s": 37495, "text": "The height 60 is obtained by boxes { {3, 1, 2}, {1, 2, 3}, {6, 4, 5}, {4, 5, 6}, {4, 6, 7}, {32, 10, 12}, {10, 12, 32}}Time Complexity: O(n^2) Auxiliary Space: O(n)" }, { "code": null, "e": 37720, "s": 37660, "text": "Method 2 : dynamic programming using memoization (top-down)" }, { "code": null, "e": 37724, "s": 37720, "text": "C++" }, { "code": "/* Dynamic Programming top-down implementation of Box * Stacking problem */#include <bits/stdc++.h>using namespace std; /* Representation of a box */class Box {public: int length; int width; int height;}; // dp arrayint dp[303]; /* boxes -> vector of Box bottom_box_index -> index of the bottom box index -> index of current box*//* NOTE: we can use only one variable in place of bottom_box_index and index but it has been avoided to make it simple */int findMaxHeight(vector<Box>& boxes, int bottom_box_index, int index){ // base case if (index < 0) return 0; if (dp[index] != -1) return dp[index]; int maximumHeight = 0; // recurse for (int i = index; i >= 0; i--) { // if there is no bottom box if (bottom_box_index == -1 // or if length & width of new box is < that of // bottom box || (boxes[i].length < boxes[bottom_box_index].length && boxes[i].width < boxes[bottom_box_index].width)) maximumHeight = max(maximumHeight, findMaxHeight(boxes, i, i - 1) + boxes[i].height); } return dp[index] = maximumHeight;} /* wrapper function for recursive calls whichReturns the height of the tallest stack that can beformed with give type of boxes */int maxStackHeight(int height[], int width[], int length[], int types){ // creating a vector of type Box class vector<Box> boxes; // Initialize dp array with -1 memset(dp, -1, sizeof(dp)); Box box; /* Create an array of all rotations of given boxes For example, for a box {1, 2, 3}, we consider three instances{{1, 2, 3}, {2, 1, 3}, {3, 1, 2}} */ for (int i = 0; i < types; i++) { // copy original box box.height = height[i]; box.length = max(length[i], width[i]); box.width = min(length[i], width[i]); boxes.push_back(box); // First rotation of box box.height = width[i]; box.length = max(length[i], height[i]); box.width = min(length[i], height[i]); boxes.push_back(box); // Second rotation of box box.height = length[i]; box.length = max(width[i], height[i]); box.width = min(width[i], height[i]); boxes.push_back(box); } // sort by area in ascending order .. because we will be dealing with this vector in reverse sort(boxes.begin(), boxes.end(), [](Box b1, Box b2) { // if area of box1 < area of box2 return (b1.length * b1.width) < (b2.length * b2.width); }); // Uncomment following two lines to print all rotations //for (int i = boxes.size() - 1; i >= 0; i-- ) // printf(\"%d x %d x %d\\n\", boxes[i].length, boxes[i].width, boxes[i].height); return findMaxHeight(boxes, -1, boxes.size() - 1);} int main(){ // where length, width and height of a particular box // are at ith index of the following arrays int length[] = { 4, 1, 4, 10 }; int width[] = { 6, 2, 5, 12 }; int height[] = { 7, 3, 6, 32 }; int n = sizeof(length) / sizeof(length[0]); printf(\"The maximum possible height of stack is %d\\n\", maxStackHeight(height, length, width, n)); return 0;}", "e": 41023, "s": 37724, "text": null }, { "code": null, "e": 41066, "s": 41023, "text": "The maximum possible height of stack is 60" }, { "code": null, "e": 41347, "s": 41066, "text": "In the above program, for boxes of dimensions of {4, 6, 7}, {1, 2, 3}, {4, 5, 6}, {10, 12, 32} on giving the input as {4, 1, 4, 10} for length, {6, 2, 5, 12} for width and {7, 3, 6, 32} for height. Following rotations are possible for the boxes in decreasing order of base area. " }, { "code": null, "e": 41559, "s": 41347, "text": "32 x 12 x 10 <-\n32 x 10 x 12\n12 x 10 x 32 <-\n7 x 6 x 4 <-\n6 x 5 x 4 <-\n7 x 4 x 6\n6 x 4 x 5\n6 x 4 x 7\n5 x 4 x 6 <-\n3 x 2 x 1 <-\n3 x 1 x 2\n2 x 1 x 3 <-\nThe maximum possible height of stack is 60" }, { "code": null, "e": 41679, "s": 41559, "text": "The height 60 is obtained by boxes { {2, 1, 3}, {3, 2, 1}, {5, 4, 6}, {6, 5, 4}, {7, 6, 4}, {12, 10, 32}, {32, 12, 10}}" }, { "code": null, "e": 42529, "s": 41679, "text": "YouTubeGeeksforGeeks507K subscribersBox Stacking Problem | Dynamic Programming (Set 22) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:27•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=KgWy0fY0dRM\" 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": 42655, "s": 42529, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 42669, "s": 42655, "text": "vibhu4agarwal" }, { "code": null, "e": 42679, "s": 42669, "text": "dumbledee" }, { "code": null, "e": 42687, "s": 42679, "text": "aj941ga" }, { "code": null, "e": 42704, "s": 42687, "text": "khushboogoyal499" }, { "code": null, "e": 42721, "s": 42704, "text": "arorakashish0911" }, { "code": null, "e": 42728, "s": 42721, "text": "Amazon" }, { "code": null, "e": 42739, "s": 42728, "text": "Codenation" }, { "code": null, "e": 42749, "s": 42739, "text": "Microsoft" }, { "code": null, "e": 42769, "s": 42749, "text": "Dynamic Programming" }, { "code": null, "e": 42776, "s": 42769, "text": "Amazon" }, { "code": null, "e": 42786, "s": 42776, "text": "Microsoft" }, { "code": null, "e": 42797, "s": 42786, "text": "Codenation" }, { "code": null, "e": 42817, "s": 42797, "text": "Dynamic Programming" }, { "code": null, "e": 42915, "s": 42817, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42946, "s": 42915, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 42979, "s": 42946, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 43006, "s": 42979, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 43025, "s": 43006, "text": "Coin Change | DP-7" }, { "code": null, "e": 43060, "s": 43025, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 43098, "s": 43060, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 43166, "s": 43098, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 43187, "s": 43166, "text": "Edit Distance | DP-5" }, { "code": null, "e": 43209, "s": 43187, "text": "Sieve of Eratosthenes" } ]
Bind function and placeholders in C++ - GeeksforGeeks
28 Jun, 2021 Sometimes we need to manipulate the operation of a function according to the need, i.e changing some arguments to default etc. Predefining a function to have default arguments restricts the versatility of a function and forces us to use the default arguments and that too with similar value each time. From C++11 onwards, the introduction of bind function has made this task easier. How does bind() work?Bind function with the help of placeholders, helps to manipulate the position and number of values to be used by the function and modifies the function according to the desired output. What are placeholders?Placeholders are namespace which direct the position of a value in a function. They are represented by _1, _2, _3... // C++ code to demonstrate bind() and// placeholders#include <iostream>#include <functional> // for bind()using namespace std; // for placeholdersusing namespace std::placeholders; // Driver function to demonstrate bind()void func(int a, int b, int c){ cout << (a - b - c) << endl;} int main(){ // for placeholders using namespace std::placeholders; // Use of bind() to bind the function // _1 is for first parameter and assigned // to 'a' in above declaration. // 2 is assigned to b // 3 is assigned to c auto fn1 = bind(func, _1, 2, 3); // 2 is assigned to a. // _1 is for first parameter and assigned // to 'b' in above declaration. // 3 is assigned to c. auto fn2 = bind(func, 2, _1, 3); // calling of modified functions fn1(10); fn2(10); return 0;} Output: 5 -11 In the above code, bind() modified the call of a function to take 1 argument and returned the desired output. Properties of placeholders 1. The position of placeholder determines the value position in function call statement // C++ code to demonstrate placeholder// property 1#include <iostream>#include <functional> // for bind()using namespace std; // for placeholdersusing namespace std::placeholders; // Driver function to demonstrate bind()void func(int a, int b, int c){ cout << (a - b - c) << endl;} int main (){ // for placeholders using namespace std::placeholders; // Second parameter to fn1() is assigned // to 'a' in fun(). // 2 is assigned to 'b' in fun // First parameter to fn1() is assigned // to 'c' in fun(). auto fn1 = bind(func, _2, 2, _1); // calling of function cout << "The value of function is : "; fn1(1, 13); // First parameter to fn2() is assigned // to 'a' in fun(). // 2 is assigned to 'b' in fun // Second parameter to fn2() is assigned // to 'c' in fun(). auto fn2 = bind(func, _1, 2, _2); // calling of same function cout << "The value of function after changing" " placeholder position is : "; fn2(1, 13); return 0;} Output: The value of function is : 10 The value of function after changing placeholder position is : -14 In the above code, even though the position of 1 and 13 were same in function call, the change in position of placeholders changed the way function was called. 2. The number of placeholders determine the number of arguments required to pass in functionWe can use any no. of placeholders in function call statement (obviously less than the maximum number of arguments). The rest values are replaced by the user defined default values. // C++ code to demonstrate placeholder // property 2#include <iostream> #include <functional> // for bind()using namespace std; // for placeholdersusing namespace std::placeholders; // Driver function to demonstrate bind()void func(int a,int b, int c){ cout << (a - b - c) << endl;} int main() { // for placeholders using namespace std::placeholders; // 1 placeholder auto fn1 = bind(func, _1, 2, 4); // calling of function with 1 argument cout << "The value of function with 1 " "placeholder is : "; fn1(10); // 2 placeholders auto fn2 = bind(func,_1,2,_2); // calling of function with 2 arguments cout << "The value of function with 2" " placeholders is : "; fn2(13, 1); // 3 placeholders auto fn3 = bind(func,_1, _3, _2); // calling of function with 3 arguments cout << "The value of function with 3 " "placeholders is : "; fn3(13, 1, 4); return 0; } Output: The value of function with 1 placeholder is : 4 The value of function with 2 placeholders is : 10 The value of function with 3 placeholders is : 8 In the above code, clearly the no. of placeholders equated the number of arguments required to call the function. The binding of function is directed by number and position of placeholders. This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. CPP-Library C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Converting Strings to Numbers in C/C++ Core Dump (Segmentation fault) in C/C++ Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 25831, "s": 25803, "text": "\n28 Jun, 2021" }, { "code": null, "e": 26214, "s": 25831, "text": "Sometimes we need to manipulate the operation of a function according to the need, i.e changing some arguments to default etc. Predefining a function to have default arguments restricts the versatility of a function and forces us to use the default arguments and that too with similar value each time. From C++11 onwards, the introduction of bind function has made this task easier." }, { "code": null, "e": 26420, "s": 26214, "text": "How does bind() work?Bind function with the help of placeholders, helps to manipulate the position and number of values to be used by the function and modifies the function according to the desired output." }, { "code": null, "e": 26559, "s": 26420, "text": "What are placeholders?Placeholders are namespace which direct the position of a value in a function. They are represented by _1, _2, _3..." }, { "code": "// C++ code to demonstrate bind() and// placeholders#include <iostream>#include <functional> // for bind()using namespace std; // for placeholdersusing namespace std::placeholders; // Driver function to demonstrate bind()void func(int a, int b, int c){ cout << (a - b - c) << endl;} int main(){ // for placeholders using namespace std::placeholders; // Use of bind() to bind the function // _1 is for first parameter and assigned // to 'a' in above declaration. // 2 is assigned to b // 3 is assigned to c auto fn1 = bind(func, _1, 2, 3); // 2 is assigned to a. // _1 is for first parameter and assigned // to 'b' in above declaration. // 3 is assigned to c. auto fn2 = bind(func, 2, _1, 3); // calling of modified functions fn1(10); fn2(10); return 0;}", "e": 27380, "s": 26559, "text": null }, { "code": null, "e": 27388, "s": 27380, "text": "Output:" }, { "code": null, "e": 27395, "s": 27388, "text": "5\n-11\n" }, { "code": null, "e": 27505, "s": 27395, "text": "In the above code, bind() modified the call of a function to take 1 argument and returned the desired output." }, { "code": null, "e": 27532, "s": 27505, "text": "Properties of placeholders" }, { "code": null, "e": 27620, "s": 27532, "text": "1. The position of placeholder determines the value position in function call statement" }, { "code": "// C++ code to demonstrate placeholder// property 1#include <iostream>#include <functional> // for bind()using namespace std; // for placeholdersusing namespace std::placeholders; // Driver function to demonstrate bind()void func(int a, int b, int c){ cout << (a - b - c) << endl;} int main (){ // for placeholders using namespace std::placeholders; // Second parameter to fn1() is assigned // to 'a' in fun(). // 2 is assigned to 'b' in fun // First parameter to fn1() is assigned // to 'c' in fun(). auto fn1 = bind(func, _2, 2, _1); // calling of function cout << \"The value of function is : \"; fn1(1, 13); // First parameter to fn2() is assigned // to 'a' in fun(). // 2 is assigned to 'b' in fun // Second parameter to fn2() is assigned // to 'c' in fun(). auto fn2 = bind(func, _1, 2, _2); // calling of same function cout << \"The value of function after changing\" \" placeholder position is : \"; fn2(1, 13); return 0;}", "e": 28634, "s": 27620, "text": null }, { "code": null, "e": 28642, "s": 28634, "text": "Output:" }, { "code": null, "e": 28740, "s": 28642, "text": "The value of function is : 10\nThe value of function after changing placeholder position is : -14\n" }, { "code": null, "e": 28900, "s": 28740, "text": "In the above code, even though the position of 1 and 13 were same in function call, the change in position of placeholders changed the way function was called." }, { "code": null, "e": 29176, "s": 28902, "text": "2. The number of placeholders determine the number of arguments required to pass in functionWe can use any no. of placeholders in function call statement (obviously less than the maximum number of arguments). The rest values are replaced by the user defined default values." }, { "code": "// C++ code to demonstrate placeholder // property 2#include <iostream> #include <functional> // for bind()using namespace std; // for placeholdersusing namespace std::placeholders; // Driver function to demonstrate bind()void func(int a,int b, int c){ cout << (a - b - c) << endl;} int main() { // for placeholders using namespace std::placeholders; // 1 placeholder auto fn1 = bind(func, _1, 2, 4); // calling of function with 1 argument cout << \"The value of function with 1 \" \"placeholder is : \"; fn1(10); // 2 placeholders auto fn2 = bind(func,_1,2,_2); // calling of function with 2 arguments cout << \"The value of function with 2\" \" placeholders is : \"; fn2(13, 1); // 3 placeholders auto fn3 = bind(func,_1, _3, _2); // calling of function with 3 arguments cout << \"The value of function with 3 \" \"placeholders is : \"; fn3(13, 1, 4); return 0; }", "e": 30194, "s": 29176, "text": null }, { "code": null, "e": 30202, "s": 30194, "text": "Output:" }, { "code": null, "e": 30350, "s": 30202, "text": "The value of function with 1 placeholder is : 4\nThe value of function with 2 placeholders is : 10\nThe value of function with 3 placeholders is : 8\n" }, { "code": null, "e": 30540, "s": 30350, "text": "In the above code, clearly the no. of placeholders equated the number of arguments required to call the function. The binding of function is directed by number and position of placeholders." }, { "code": null, "e": 30837, "s": 30540, "text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 30962, "s": 30837, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 30974, "s": 30962, "text": "CPP-Library" }, { "code": null, "e": 30985, "s": 30974, "text": "C Language" }, { "code": null, "e": 30989, "s": 30985, "text": "C++" }, { "code": null, "e": 30993, "s": 30989, "text": "CPP" }, { "code": null, "e": 31091, "s": 30993, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31108, "s": 31091, "text": "Substring in C++" }, { "code": null, "e": 31143, "s": 31108, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 31189, "s": 31143, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 31228, "s": 31189, "text": "Converting Strings to Numbers in C/C++" }, { "code": null, "e": 31268, "s": 31228, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 31286, "s": 31268, "text": "Vector in C++ STL" }, { "code": null, "e": 31332, "s": 31286, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 31351, "s": 31332, "text": "Inheritance in C++" }, { "code": null, "e": 31394, "s": 31351, "text": "Map in C++ Standard Template Library (STL)" } ]
Bootstrap 5 Collapse - GeeksforGeeks
05 May, 2022 Bootstrap 5 is the latest major release by Bootstrap in which they have revamped the UI and made various changes. Collapse is used to toggle the visibility of content across your project with a few classes and the JavaScript plugins which comes with Bootstrap 5. The working of collapse component is based on class changes which are applied. For example, .collapse to hide the content .collapsing is applied during transitions and .collapse.show shows the content.Syntax: <div class="collapse"> Contents... <div> Example 1: This example uses show the working of collapsible div with button and link in Bootstrap 5. HTML <!DOCTYPE html><html><head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"> </script></head><body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <p> <a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" role="button"> Link with href </a> <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample"> Button with data-target </button> </p> <div class="collapse" id="collapseExample"> <div class="card card-body"> GeeksforGeeks </div> </div> </div></body></html> Output: Example 2: This example uses show the working of collapsible cards in Bootstrap 5. HTML <!DOCTYPE html><html><head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"> </script></head><body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="accordion" id="accordionExample"> <div class="card"> <div class="card-header" id="headingThree"> <h2 class="mb-0"> <button class="btn btn-link btn-block text-left collapsed" type="button" data-toggle="collapse" data-target="#collapseThree"> Click Here </button> </h2> </div> <div id="collapseThree" class="collapse" data-parent="#accordionExample"> <div class="card-body"> This is Bootstrap Collapse | GeeksforGeeks </div> </div> </div> </div> </div></body></html> Output: Example 3: This example uses show the working of multiple collapsible divs in Bootstrap 5. HTML <!DOCTYPE html><html><head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"> </script></head><body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <p> <a class="btn btn-primary" data-toggle="collapse" href="#multiCollapseExample1" role="button"> Toggle firs element </a> <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#multiCollapseExample2"> Toggle second element </button> <button class="btn btn-primary" type="button" data-toggle="collapse" data-target=".multi-collapse"> Toggle both elements </button> </p> <div class="row"> <div class="col"> <div class="collapse multi-collapse" id="multiCollapseExample1"> <div class="card card-body"> This is first element </div> </div> </div> <div class="col"> <div class="collapse multi-collapse" id="multiCollapseExample2"> <div class="card card-body"> This is second element </div> </div> </div> </div> </div></body></html> Output: sahilintern Bootstrap-Misc Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to change navigation bar color in Bootstrap ? Form validation using jQuery How to pass data into a bootstrap modal? How to align navbar items to the right in Bootstrap 4 ? How to Show Images on Click using HTML ? 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": 29710, "s": 29682, "text": "\n05 May, 2022" }, { "code": null, "e": 30182, "s": 29710, "text": "Bootstrap 5 is the latest major release by Bootstrap in which they have revamped the UI and made various changes. Collapse is used to toggle the visibility of content across your project with a few classes and the JavaScript plugins which comes with Bootstrap 5. The working of collapse component is based on class changes which are applied. For example, .collapse to hide the content .collapsing is applied during transitions and .collapse.show shows the content.Syntax:" }, { "code": null, "e": 30223, "s": 30182, "text": "<div class=\"collapse\"> Contents... <div>" }, { "code": null, "e": 30325, "s": 30223, "text": "Example 1: This example uses show the working of collapsible div with button and link in Bootstrap 5." }, { "code": null, "e": 30330, "s": 30325, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\"> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"> </script></head><body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <p> <a class=\"btn btn-primary\" data-toggle=\"collapse\" href=\"#collapseExample\" role=\"button\"> Link with href </a> <button class=\"btn btn-primary\" type=\"button\" data-toggle=\"collapse\" data-target=\"#collapseExample\"> Button with data-target </button> </p> <div class=\"collapse\" id=\"collapseExample\"> <div class=\"card card-body\"> GeeksforGeeks </div> </div> </div></body></html>", "e": 31790, "s": 30330, "text": null }, { "code": null, "e": 31798, "s": 31790, "text": "Output:" }, { "code": null, "e": 31882, "s": 31798, "text": " Example 2: This example uses show the working of collapsible cards in Bootstrap 5." }, { "code": null, "e": 31887, "s": 31882, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\"> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"> </script></head><body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"accordion\" id=\"accordionExample\"> <div class=\"card\"> <div class=\"card-header\" id=\"headingThree\"> <h2 class=\"mb-0\"> <button class=\"btn btn-link btn-block text-left collapsed\" type=\"button\" data-toggle=\"collapse\" data-target=\"#collapseThree\"> Click Here </button> </h2> </div> <div id=\"collapseThree\" class=\"collapse\" data-parent=\"#accordionExample\"> <div class=\"card-body\"> This is Bootstrap Collapse | GeeksforGeeks </div> </div> </div> </div> </div></body></html>", "e": 33650, "s": 31887, "text": null }, { "code": null, "e": 33658, "s": 33650, "text": "Output:" }, { "code": null, "e": 33750, "s": 33658, "text": " Example 3: This example uses show the working of multiple collapsible divs in Bootstrap 5." }, { "code": null, "e": 33755, "s": 33750, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\"> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"> </script></head><body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <p> <a class=\"btn btn-primary\" data-toggle=\"collapse\" href=\"#multiCollapseExample1\" role=\"button\"> Toggle firs element </a> <button class=\"btn btn-primary\" type=\"button\" data-toggle=\"collapse\" data-target=\"#multiCollapseExample2\"> Toggle second element </button> <button class=\"btn btn-primary\" type=\"button\" data-toggle=\"collapse\" data-target=\".multi-collapse\"> Toggle both elements </button> </p> <div class=\"row\"> <div class=\"col\"> <div class=\"collapse multi-collapse\" id=\"multiCollapseExample1\"> <div class=\"card card-body\"> This is first element </div> </div> </div> <div class=\"col\"> <div class=\"collapse multi-collapse\" id=\"multiCollapseExample2\"> <div class=\"card card-body\"> This is second element </div> </div> </div> </div> </div></body></html>", "e": 35905, "s": 33755, "text": null }, { "code": null, "e": 35913, "s": 35905, "text": "Output:" }, { "code": null, "e": 35925, "s": 35913, "text": "sahilintern" }, { "code": null, "e": 35940, "s": 35925, "text": "Bootstrap-Misc" }, { "code": null, "e": 35950, "s": 35940, "text": "Bootstrap" }, { "code": null, "e": 35967, "s": 35950, "text": "Web Technologies" }, { "code": null, "e": 36065, "s": 35967, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36115, "s": 36065, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 36144, "s": 36115, "text": "Form validation using jQuery" }, { "code": null, "e": 36185, "s": 36144, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 36241, "s": 36185, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 36282, "s": 36241, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 36322, "s": 36282, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 36355, "s": 36322, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 36400, "s": 36355, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 36443, "s": 36400, "text": "How to fetch data from an API in ReactJS ?" } ]
Min Cost Path | DP-6 - GeeksforGeeks
21 Oct, 2021 Given a cost matrix cost[][] and a position (m, n) in cost[][], write a function that returns cost of minimum cost path to reach (m, n) from (0, 0). Each cell of the matrix represents a cost to traverse through that cell. The total cost of a path to reach (m, n) is the sum of all the costs on that path (including both source and destination). You can only traverse down, right and diagonally lower cells from a given cell, i.e., from a given cell (i, j), cells (i+1, j), (i, j+1), and (i+1, j+1) can be traversed. You may assume that all costs are positive integers. For example, in the following figure, what is the minimum cost path to (2, 2)? The path with minimum cost is highlighted in the following figure. The path is (0, 0) –> (0, 1) –> (1, 2) –> (2, 2). The cost of the path is 8 (1 + 2 + 2 + 3). Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. 1) Optimal Substructure The path to reach (m, n) must be through one of the 3 cells: (m-1, n-1) or (m-1, n) or (m, n-1). So minimum cost to reach (m, n) can be written as “minimum of the 3 cells plus cost[m][n]”.minCost(m, n) = min (minCost(m-1, n-1), minCost(m-1, n), minCost(m, n-1)) + cost[m][n] 2) Overlapping Subproblems Following is a simple recursive implementation of the MCP (Minimum Cost Path) problem. The implementation simply follows the recursive structure mentioned above. C++ C Java Python3 C# PHP Javascript // A Naive recursive implementation// of MCP(Minimum Cost Path) problem#include <bits/stdc++.h>using namespace std; #define R 3#define C 3 int min(int x, int y, int z); // Returns cost of minimum cost path// from (0,0) to (m, n) in mat[R][C]int minCost(int cost[R][C], int m, int n){ if (n < 0 || m < 0) return INT_MAX; else if (m == 0 && n == 0) return cost[m][n]; else return cost[m][n] + min(minCost(cost, m - 1, n - 1), minCost(cost, m - 1, n), minCost(cost, m, n - 1));} // A utility function that returns// minimum of 3 integersint min(int x, int y, int z){ if (x < y) return (x < z) ? x : z; else return (y < z) ? y : z;} // Driver codeint main(){ int cost[R][C] = { { 1, 2, 3 }, { 4, 8, 2 }, { 1, 5, 3 } }; cout << minCost(cost, 2, 2) << endl; return 0;} // This code is contributed by nikhilchhipa9 /* A Naive recursive implementation of MCP(Minimum Cost Path) problem */#include<stdio.h>#include<limits.h>#define R 3#define C 3 int min(int x, int y, int z); /* Returns cost of minimum cost path from (0,0) to (m, n) in mat[R][C]*/int minCost(int cost[R][C], int m, int n){ if (n < 0 || m < 0) return INT_MAX; else if (m == 0 && n == 0) return cost[m][n]; else return cost[m][n] + min( minCost(cost, m-1, n-1), minCost(cost, m-1, n), minCost(cost, m, n-1) );} /* A utility function that returns minimum of 3 integers */int min(int x, int y, int z){ if (x < y) return (x < z)? x : z; else return (y < z)? y : z;} /* Driver program to test above functions */int main(){ int cost[R][C] = { {1, 2, 3}, {4, 8, 2}, {1, 5, 3} }; printf(" %d ", minCost(cost, 2, 2)); return 0;} /* A Naive recursive implementation ofMCP(Minimum Cost Path) problem */public class GFG { /* A utility function that returns minimum of 3 integers */ static int min(int x, int y, int z) { if (x < y) return (x < z) ? x : z; else return (y < z) ? y : z; } /* Returns cost of minimum cost path from (0,0) to (m, n) in mat[R][C]*/ static int minCost(int cost[][], int m, int n) { if (n < 0 || m < 0) return Integer.MAX_VALUE; else if (m == 0 && n == 0) return cost[m][n]; else return cost[m][n] + min( minCost(cost, m-1, n-1), minCost(cost, m-1, n), minCost(cost, m, n-1) ); } // Driver code public static void main(String args[]) { int cost[][] = { {1, 2, 3}, {4, 8, 2}, {1, 5, 3} }; System.out.print(minCost(cost, 2, 2)); }} // This code is contributed by Sam007 # A Naive recursive implementation of MCP(Minimum Cost Path) problemR = 3C = 3import sys # Returns cost of minimum cost path from (0,0) to (m, n) in mat[R][C]def minCost(cost, m, n): if (n < 0 or m < 0): return sys.maxsize elif (m == 0 and n == 0): return cost[m][n] else: return cost[m][n] + min( minCost(cost, m-1, n-1), minCost(cost, m-1, n), minCost(cost, m, n-1) ) #A utility function that returns minimum of 3 integers */def min(x, y, z): if (x < y): return x if (x < z) else z else: return y if (y < z) else z # Driver program to test above functionscost= [ [1, 2, 3], [4, 8, 2], [1, 5, 3] ]print(minCost(cost, 2, 2)) # This code is contributed by# Smitha Dinesh Semwal /* A Naive recursive implementation ofMCP(Minimum Cost Path) problem */using System; class GFG{ /* A utility function that returns minimum of 3 integers */ static int min(int x, int y, int z) { if (x < y) return ((x < z) ? x : z); else return ((y < z) ? y : z); } /* Returns cost of minimum cost path from (0,0) to (m, n) in mat[R][C]*/ static int minCost(int [,]cost, int m , int n) { if (n < 0 || m < 0) return int.MaxValue; else if (m == 0 && n == 0) return cost[m, n]; else return cost[m, n] + min(minCost(cost, m - 1, n - 1), minCost(cost, m - 1, n), minCost(cost, m, n - 1) ); } // Driver code public static void Main() { int [,]cost = {{1, 2, 3}, {4, 8, 2}, {1, 5, 3}}; Console.Write(minCost(cost, 2, 2)); }} // This code is contributed// by shiv_bhakt. <?php/* A Naive recursive implementationof MCP(Minimum Cost Path) problem */ $R = 3;$C = 3; /* Returns cost of minimum cost path from (0,0) to(m, n) in mat[R][C]*/function minCost($cost, $m, $n){global $R;global $C;if ($n < 0 || $m < 0) return PHP_INT_MAX;else if ($m == 0 && $n == 0) return $cost[$m][$n];else return $cost[$m][$n] + min1(minCost($cost, $m - 1, $n - 1), minCost($cost, $m - 1, $n), minCost($cost, $m, $n - 1) );} /* A utility function thatreturns minimum of 3 integers */function min1($x, $y, $z){if ($x < $y) return ($x < $z)? $x : $z;else return ($y < $z)? $y : $z;} // Driver Code$cost = array(array(1, 2, 3), array (4, 8, 2), array (1, 5, 3));echo minCost($cost, 2, 2); // This code is contributed by mits.?> <script> // A Naive recursive implementation of// MCP(Minimum Cost Path) problem // A utility function that returns// minimum of 3 integersfunction min(x, y, z){ if (x < y) return (x < z) ? x : z; else return (y < z) ? y : z;} // Returns cost of minimum cost path// from (0,0) to (m, n) in mat[R][C]function minCost(cost, m, n){ if (n < 0 || m < 0) return Number.MAX_VALUE; else if (m == 0 && n == 0) return cost[m][n]; else return cost[m][n] + min(minCost(cost, m - 1, n - 1), minCost(cost, m - 1, n), minCost(cost, m, n - 1));} // Driver codevar cost = [ [ 1, 2, 3 ], [ 4, 8, 2 ], [ 1, 5, 3 ] ]; document.write(minCost(cost, 2, 2)); // This code is contributed by gauravrajput1 </script> 8 Time Complexity: O(m * n) It should be noted that the above function computes the same subproblems again and again. See the following recursion tree, there are many nodes which appear more than once. The time complexity of this naive recursive solution is exponential and it is terribly slow. mC refers to minCost() mC(2, 2) / | \ / | \ mC(1, 1) mC(1, 2) mC(2, 1) / | \ / | \ / | \ / | \ / | \ / | \ mC(0,0) mC(0,1) mC(1,0) mC(0,1) mC(0,2) mC(1,1) mC(1,0) mC(1,1) mC(2,0) So the MCP problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of the same subproblems can be avoided by constructing a temporary array tc[][] in a bottom-up manner. C++ C Java Python C# PHP Javascript /* Dynamic Programming implementation of MCP problem */#include <bits/stdc++.h>#include<limits.h>#define R 3#define C 3using namespace std;int min(int x, int y, int z); int minCost(int cost[R][C], int m, int n){ int i, j; // Instead of following line, we can use int tc[m+1][n+1] or // dynamically allocate memory to save space. The following line is // used to keep the program simple and make it working on all compilers. int tc[R][C]; tc[0][0] = cost[0][0]; /* Initialize first column of total cost(tc) array */ for (i = 1; i <= m; i++) tc[i][0] = tc[i - 1][0] + cost[i][0]; /* Initialize first row of tc array */ for (j = 1; j <= n; j++) tc[0][j] = tc[0][j - 1] + cost[0][j]; /* Construct rest of the tc array */ for (i = 1; i <= m; i++) for (j = 1; j <= n; j++) tc[i][j] = min(tc[i - 1][j - 1], tc[i - 1][j], tc[i][j - 1]) + cost[i][j]; return tc[m][n];} /* A utility function that returns minimum of 3 integers */int min(int x, int y, int z){ if (x < y) return (x < z)? x : z; else return (y < z)? y : z;} /* Driver code*/int main(){ int cost[R][C] = { {1, 2, 3}, {4, 8, 2}, {1, 5, 3} }; cout << " " << minCost(cost, 2, 2); return 0;} // This code is contributed by shivanisinghss2110 /* Dynamic Programming implementation of MCP problem */#include<stdio.h>#include<limits.h>#define R 3#define C 3 int min(int x, int y, int z); int minCost(int cost[R][C], int m, int n){ int i, j; // Instead of following line, we can use int tc[m+1][n+1] or // dynamically allocate memory to save space. The following line is // used to keep the program simple and make it working on all compilers. int tc[R][C]; tc[0][0] = cost[0][0]; /* Initialize first column of total cost(tc) array */ for (i = 1; i <= m; i++) tc[i][0] = tc[i-1][0] + cost[i][0]; /* Initialize first row of tc array */ for (j = 1; j <= n; j++) tc[0][j] = tc[0][j-1] + cost[0][j]; /* Construct rest of the tc array */ for (i = 1; i <= m; i++) for (j = 1; j <= n; j++) tc[i][j] = min(tc[i-1][j-1], tc[i-1][j], tc[i][j-1]) + cost[i][j]; return tc[m][n];} /* A utility function that returns minimum of 3 integers */int min(int x, int y, int z){ if (x < y) return (x < z)? x : z; else return (y < z)? y : z;} /* Driver program to test above functions */int main(){ int cost[R][C] = { {1, 2, 3}, {4, 8, 2}, {1, 5, 3} }; printf(" %d ", minCost(cost, 2, 2)); return 0;} /* Java program for Dynamic Programming implementation of Min Cost Path problem */import java.util.*; class MinimumCostPath{ /* A utility function that returns minimum of 3 integers */ private static int min(int x, int y, int z) { if (x < y) return (x < z)? x : z; else return (y < z)? y : z; } private static int minCost(int cost[][], int m, int n) { int i, j; int tc[][]=new int[m+1][n+1]; tc[0][0] = cost[0][0]; /* Initialize first column of total cost(tc) array */ for (i = 1; i <= m; i++) tc[i][0] = tc[i-1][0] + cost[i][0]; /* Initialize first row of tc array */ for (j = 1; j <= n; j++) tc[0][j] = tc[0][j-1] + cost[0][j]; /* Construct rest of the tc array */ for (i = 1; i <= m; i++) for (j = 1; j <= n; j++) tc[i][j] = min(tc[i-1][j-1], tc[i-1][j], tc[i][j-1]) + cost[i][j]; return tc[m][n]; } /* Driver program to test above functions */ public static void main(String args[]) { int cost[][]= {{1, 2, 3}, {4, 8, 2}, {1, 5, 3}}; System.out.println(minCost(cost,2,2)); }}// This code is contributed by Pankaj Kumar # Dynamic Programming Python implementation of Min Cost Path# problemR = 3C = 3 def minCost(cost, m, n): # Instead of following line, we can use int tc[m+1][n+1] or # dynamically allocate memoery to save space. The following # line is used to keep te program simple and make it working # on all compilers. tc = [[0 for x in range(C)] for x in range(R)] tc[0][0] = cost[0][0] # Initialize first column of total cost(tc) array for i in range(1, m+1): tc[i][0] = tc[i-1][0] + cost[i][0] # Initialize first row of tc array for j in range(1, n+1): tc[0][j] = tc[0][j-1] + cost[0][j] # Construct rest of the tc array for i in range(1, m+1): for j in range(1, n+1): tc[i][j] = min(tc[i-1][j-1], tc[i-1][j], tc[i][j-1]) + cost[i][j] return tc[m][n] # Driver program to test above functionscost = [[1, 2, 3], [4, 8, 2], [1, 5, 3]]print(minCost(cost, 2, 2)) # This code is contributed by Bhavya Jain // C# program for Dynamic Programming implementation// of Min Cost Path problemusing System; class GFG{ // A utility function that // returns minimum of 3 integers private static int min(int x, int y, int z) { if (x < y) return (x < z)? x : z; else return (y < z)? y : z; } private static int minCost(int [,]cost, int m, int n) { int i, j; int [,]tc=new int[m+1,n+1]; tc[0,0] = cost[0,0]; /* Initialize first column of total cost(tc) array */ for (i = 1; i <= m; i++) tc[i, 0] = tc[i - 1, 0] + cost[i, 0]; /* Initialize first row of tc array */ for (j = 1; j <= n; j++) tc[0, j] = tc[0, j - 1] + cost[0, j]; /* Construct rest of the tc array */ for (i = 1; i <= m; i++) for (j = 1; j <= n; j++) tc[i, j] = min(tc[i - 1, j - 1], tc[i - 1, j], tc[i, j - 1]) + cost[i, j]; return tc[m, n]; } // Driver program public static void Main() { int [,]cost= {{1, 2, 3}, {4, 8, 2}, {1, 5, 3}}; Console.Write(minCost(cost,2,2)); }} // This code is contributed by Sam007. <?php// DP implementation// of MCP problem$R = 3;$C = 3; function minCost($cost, $m, $n){ global $R; global $C; // Instead of following line, // we can use int tc[m+1][n+1] // or dynamically allocate // memory to save space. The // following line is used to keep // the program simple and make // it working on all compilers. $tc; for ($i = 0; $i <= $R; $i++) for ($j = 0; $j <= $C; $j++) $tc[$i][$j] = 0; $tc[0][0] = $cost[0][0]; /* Initialize first column of total cost(tc) array */ for ($i = 1; $i <= $m; $i++) $tc[$i][0] = $tc[$i - 1][0] + $cost[$i][0]; /* Initialize first row of tc array */ for ($j = 1; $j <= $n; $j++) $tc[0][$j] = $tc[0][$j - 1] + $cost[0][$j]; /* Construct rest of the tc array */ for ($i = 1; $i <= $m; $i++) for ($j = 1; $j <= $n; $j++) // returns minimum of 3 integers $tc[$i][$j] = min($tc[$i - 1][$j - 1], $tc[$i - 1][$j], $tc[$i][$j - 1]) + $cost[$i][$j]; return $tc[$m][$n];} // Driver Code$cost = array(array(1, 2, 3), array(4, 8, 2), array(1, 5, 3));echo minCost($cost, 2, 2); // This code is contributed by mits?> <script> // Javascript program for Dynamic Programming implementation // of Min Cost Path problem /* A utility function that returns minimum of 3 integers */ function min(x, y, z) { if (x < y) return (x < z)? x : z; else return (y < z)? y : z; } function minCost(cost, m, n) { let i, j; let tc = new Array(m+1); for(let k = 0; k < m + 1; k++) { tc[k] = new Array(n+1); } tc[0][0] = cost[0][0]; /* Initialize first column of total cost(tc) array */ for (i = 1; i <= m; i++) tc[i][0] = tc[i-1][0] + cost[i][0]; /* Initialize first row of tc array */ for (j = 1; j <= n; j++) tc[0][j] = tc[0][j-1] + cost[0][j]; /* Construct rest of the tc array */ for (i = 1; i <= m; i++) for (j = 1; j <= n; j++) tc[i][j] = Math.min(tc[i-1][j-1], tc[i-1][j], tc[i][j-1]) + cost[i][j]; return tc[m][n]; } let cost = [[1, 2, 3], [4, 8, 2], [1, 5, 3]]; document.write(minCost(cost,2,2)); </script> 8 Time Complexity of the DP implementation is O(mn) which is much better than Naive Recursive implementation. Auxiliary Space: O(m * n) Space Optimization: The idea is to use the same given array to store the solutions of subproblems. C++ Java Python3 C# Javascript #include <bits/stdc++.h>#define endl "\n"using namespace std; const int row = 3;const int col = 3; int minCost(int cost[row][col]) { // for 1st column for (int i=1 ; i<row ; i++){ cost[i][0] += cost[i-1][0]; } // for 1st row for (int j=1 ; j<col ; j++){ cost[0][j] += cost[0][j-1]; } // for rest of the 2d matrix for (int i=1 ; i<row ; i++) { for (int j=1 ; j<col ; j++) { cost[i][j] += min(cost[i-1][j-1], min(cost[i-1][j], cost[i][j-1])); } } // returning the value in last cell return cost[row-1][col-1];}int main(int argc, char const *argv[]){ int cost[row][col] = { {1, 2, 3}, {4, 8, 2}, {1, 5, 3} }; cout << minCost(cost) << endl; return 0;} // Contributed by Mansimar-Anand TU_2022 p_e_k_k_a Task @ Codechef/Codeforces // Java program for the// above approachimport java.util.*;class GFG{ static int row = 3;static int col = 3; static int minCost(int cost[][]){ // for 1st column for (int i = 1; i < row; i++) { cost[i][0] += cost[i - 1][0]; } // for 1st row for (int j = 1; j < col; j++) { cost[0][j] += cost[0][j - 1]; } // for rest of the 2d matrix for (int i = 1; i < row; i++) { for (int j = 1; j < col; j++) { cost[i][j] += Math.min(cost[i - 1][j - 1], Math.min(cost[i - 1][j], cost[i][j - 1])); } } // Returning the value in // last cell return cost[row - 1][col - 1];} // Driver code public static void main(String[] args){ int cost[][] = {{1, 2, 3}, {4, 8, 2}, {1, 5, 3} }; System.out.print(minCost(cost) + "\n");}} // This code is contributed by Amit Katiyar # Python3 program for the# above approach def minCost(cost, row, col): # For 1st column for i in range(1, row): cost[i][0] += cost[i - 1][0] # For 1st row for j in range(1, col): cost[0][j] += cost[0][j - 1] # For rest of the 2d matrix for i in range(1, row): for j in range(1, col): cost[i][j] += (min(cost[i - 1][j - 1], min(cost[i - 1][j], cost[i][j - 1]))) # Returning the value in # last cell return cost[row - 1][col - 1] # Driver codeif __name__ == '__main__': row = 3 col = 3 cost = [ [ 1, 2, 3 ], [ 4, 8, 2 ], [ 1, 5, 3 ] ] print(minCost(cost, row, col)); # This code is contributed by Amit Katiyar // C# program for the// above approachusing System;class GFG{ static int row = 3;static int col = 3; static int minCost(int [,]cost){ // for 1st column for (int i = 1; i < row; i++) { cost[i, 0] += cost[i - 1, 0]; } // for 1st row for (int j = 1; j < col; j++) { cost[0, j] += cost[0, j - 1]; } // for rest of the 2d matrix for (int i = 1; i < row; i++) { for (int j = 1; j < col; j++) { cost[i,j] += Math.Min(cost[i - 1, j - 1], Math.Min(cost[i - 1, j], cost[i, j - 1])); } } // Returning the value in // last cell return cost[row - 1, col - 1];} // Driver code public static void Main(String[] args){ int [,]cost = {{1, 2, 3}, {4, 8, 2}, {1, 5, 3} }; Console.Write(minCost(cost) + "\n");}} // This code is contributed by Rajput-Ji <script> // javascript program for the// above approach var row = 3;var col = 3; function minCost(cost){ // for 1st column for (i = 1; i < row; i++) { cost[i][0] += cost[i - 1][0]; } // for 1st row for (j = 1; j < col; j++) { cost[0][j] += cost[0][j - 1]; } // for rest of the 2d matrix for (i = 1; i < row; i++) { for (j = 1; j < col; j++) { cost[i][j] += Math.min(cost[i - 1][j - 1], Math.min(cost[i - 1][j], cost[i][j - 1])); } } // Returning the value in // last cell return cost[row - 1][col - 1];} // Driver code var cost = [[1, 2, 3],[4, 8, 2],[1, 5, 3] ];document.write(minCost(cost) + '<br>'); // This code is contributed by 29AjayKumar </script> 8 Time Complexity: O(row * col) Auxiliary Space: O(1) Alternate Solution We can also use the Dijkstra’s shortest path algorithm. Below is the implementation of the approach: C++ /* Minimum Cost Path using Dijkstra’s shortest path algorithm with Min Heap by dinglizeng */#include <stdio.h>#include <queue>#include <limits.h>using namespace std; /* define the number of rows and the number of columns */#define R 4#define C 5 /* 8 possible moves */int dx[] = {1,-1, 0, 0, 1, 1,-1,-1};int dy[] = {0, 0, 1,-1, 1,-1, 1,-1}; /* The data structure to store the coordinates of \\ the unit square and the cost of path from the top left. */struct Cell{ int x; int y; int cost;}; /* The compare class to be used by a Min Heap. * The greater than condition is used as this is for a Min Heap based on priority_queue. */class mycomparison{public: bool operator() (const Cell &lhs, const Cell &rhs) const { return (lhs.cost > rhs.cost); }}; /* To verify whether a move is within the boundary. */bool isSafe(int x, int y){ return x >= 0 && x < R && y >= 0 && y < C;} /* This solution is based on Dijkstra’s shortest path algorithm * For each unit square being visited, we examine all possible next moves in 8 directions, * calculate the accumulated cost of path for each next move, adjust the cost of path of the adjacent units to the minimum as needed. * then add the valid next moves into a Min Heap. * The Min Heap pops out the next move with the minimum accumulated cost of path. * Once the iteration reaches the last unit at the lower right corner, the minimum cost path will be returned. */int minCost(int cost[R][C], int m, int n) { /* the array to store the accumulated cost of path from top left corner */ int dp[R][C]; /* the array to record whether a unit square has been visited */ bool visited[R][C]; /* Initialize these two arrays, set path cost to maximum integer value, each unit as not visited */ for(int i = 0; i < R; i++) { for(int j = 0; j < C; j++) { dp[i][j] = INT_MAX; visited[i][j] = false; } } /* Define a reverse priority queue. * Priority queue is a heap based implementation. * The default behavior of a priority queue is to have the maximum element at the top. * The compare class is used in the definition of the Min Heap. */ priority_queue<Cell, vector<Cell>, mycomparison> pq; /* initialize the starting top left unit with the cost and add it to the queue as the first move. */ dp[0][0] = cost[0][0]; pq.push({0, 0, cost[0][0]}); while(!pq.empty()) { /* pop a move from the queue, ignore the units already visited */ Cell cell = pq.top(); pq.pop(); int x = cell.x; int y = cell.y; if(visited[x][y]) continue; /* mark the current unit as visited */ visited[x][y] = true; /* examine all non-visited adjacent units in 8 directions * calculate the accumulated cost of path for each next move from this unit, * adjust the cost of path for each next adjacent units to the minimum if possible. */ for(int i = 0; i < 8; i++) { int next_x = x + dx[i]; int next_y = y + dy[i]; if(isSafe(next_x, next_y) && !visited[next_x][next_y]) { dp[next_x][next_y] = min(dp[next_x][next_y], dp[x][y] + cost[next_x][next_y]); pq.push({next_x, next_y, dp[next_x][next_y]}); } } } /* return the minimum cost path at the lower right corner */ return dp[m][n]; } /* Driver program to test above functions */int main(){ int cost[R][C] = { {1, 8, 8, 1, 5}, {4, 1, 1, 8, 1}, {4, 2, 8, 8, 1}, {1, 5, 8, 8, 1} }; printf(" %d ", minCost(cost, 3, 4)); return 0;} 7 Using a reverse priority queue in this solution can reduce the time complexity compared with a full scan looking for the node with minimum path cost. The overall Time Complexity of the DP implementation is O(mn) without consideration of priority queue in use, which is much better than Naive Recursive implementation. ?list=PLqM7alHXFySEQDk2MDfbwEdjd2svVJH9p Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sam007 Mithun Kumar Vishal_Khoda maveriek dinglizeng amit143katiyar Rajput-Ji nikhilchhipa9 shivanisinghss2110 GauravRajput1 decode2207 29AjayKumar subhammahato348 subham348 Amazon MakeMyTrip Samsung Dynamic Programming Mathematical Matrix Amazon Samsung MakeMyTrip Dynamic Programming Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Largest Sum Contiguous Subarray Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Subset Sum Problem | DP-25 Longest Palindromic Substring | Set 1 C++ Data Types Set in C++ Standard Template Library (STL) Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 35839, "s": 35811, "text": "\n21 Oct, 2021" }, { "code": null, "e": 36408, "s": 35839, "text": "Given a cost matrix cost[][] and a position (m, n) in cost[][], write a function that returns cost of minimum cost path to reach (m, n) from (0, 0). Each cell of the matrix represents a cost to traverse through that cell. The total cost of a path to reach (m, n) is the sum of all the costs on that path (including both source and destination). You can only traverse down, right and diagonally lower cells from a given cell, i.e., from a given cell (i, j), cells (i+1, j), (i, j+1), and (i+1, j+1) can be traversed. You may assume that all costs are positive integers." }, { "code": null, "e": 36489, "s": 36408, "text": "For example, in the following figure, what is the minimum cost path to (2, 2)? " }, { "code": null, "e": 36651, "s": 36489, "text": "The path with minimum cost is highlighted in the following figure. The path is (0, 0) –> (0, 1) –> (1, 2) –> (2, 2). The cost of the path is 8 (1 + 2 + 2 + 3). " }, { "code": null, "e": 36660, "s": 36651, "text": "Chapters" }, { "code": null, "e": 36687, "s": 36660, "text": "descriptions off, selected" }, { "code": null, "e": 36737, "s": 36687, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 36760, "s": 36737, "text": "captions off, selected" }, { "code": null, "e": 36768, "s": 36760, "text": "English" }, { "code": null, "e": 36792, "s": 36768, "text": "This is a modal window." }, { "code": null, "e": 36861, "s": 36792, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 36883, "s": 36861, "text": "End of dialog window." }, { "code": null, "e": 37184, "s": 36885, "text": "1) Optimal Substructure The path to reach (m, n) must be through one of the 3 cells: (m-1, n-1) or (m-1, n) or (m, n-1). So minimum cost to reach (m, n) can be written as “minimum of the 3 cells plus cost[m][n]”.minCost(m, n) = min (minCost(m-1, n-1), minCost(m-1, n), minCost(m, n-1)) + cost[m][n]" }, { "code": null, "e": 37375, "s": 37184, "text": "2) Overlapping Subproblems Following is a simple recursive implementation of the MCP (Minimum Cost Path) problem. The implementation simply follows the recursive structure mentioned above. " }, { "code": null, "e": 37379, "s": 37375, "text": "C++" }, { "code": null, "e": 37381, "s": 37379, "text": "C" }, { "code": null, "e": 37386, "s": 37381, "text": "Java" }, { "code": null, "e": 37394, "s": 37386, "text": "Python3" }, { "code": null, "e": 37397, "s": 37394, "text": "C#" }, { "code": null, "e": 37401, "s": 37397, "text": "PHP" }, { "code": null, "e": 37412, "s": 37401, "text": "Javascript" }, { "code": "// A Naive recursive implementation// of MCP(Minimum Cost Path) problem#include <bits/stdc++.h>using namespace std; #define R 3#define C 3 int min(int x, int y, int z); // Returns cost of minimum cost path// from (0,0) to (m, n) in mat[R][C]int minCost(int cost[R][C], int m, int n){ if (n < 0 || m < 0) return INT_MAX; else if (m == 0 && n == 0) return cost[m][n]; else return cost[m][n] + min(minCost(cost, m - 1, n - 1), minCost(cost, m - 1, n), minCost(cost, m, n - 1));} // A utility function that returns// minimum of 3 integersint min(int x, int y, int z){ if (x < y) return (x < z) ? x : z; else return (y < z) ? y : z;} // Driver codeint main(){ int cost[R][C] = { { 1, 2, 3 }, { 4, 8, 2 }, { 1, 5, 3 } }; cout << minCost(cost, 2, 2) << endl; return 0;} // This code is contributed by nikhilchhipa9", "e": 38384, "s": 37412, "text": null }, { "code": "/* A Naive recursive implementation of MCP(Minimum Cost Path) problem */#include<stdio.h>#include<limits.h>#define R 3#define C 3 int min(int x, int y, int z); /* Returns cost of minimum cost path from (0,0) to (m, n) in mat[R][C]*/int minCost(int cost[R][C], int m, int n){ if (n < 0 || m < 0) return INT_MAX; else if (m == 0 && n == 0) return cost[m][n]; else return cost[m][n] + min( minCost(cost, m-1, n-1), minCost(cost, m-1, n), minCost(cost, m, n-1) );} /* A utility function that returns minimum of 3 integers */int min(int x, int y, int z){ if (x < y) return (x < z)? x : z; else return (y < z)? y : z;} /* Driver program to test above functions */int main(){ int cost[R][C] = { {1, 2, 3}, {4, 8, 2}, {1, 5, 3} }; printf(\" %d \", minCost(cost, 2, 2)); return 0;}", "e": 39298, "s": 38384, "text": null }, { "code": "/* A Naive recursive implementation ofMCP(Minimum Cost Path) problem */public class GFG { /* A utility function that returns minimum of 3 integers */ static int min(int x, int y, int z) { if (x < y) return (x < z) ? x : z; else return (y < z) ? y : z; } /* Returns cost of minimum cost path from (0,0) to (m, n) in mat[R][C]*/ static int minCost(int cost[][], int m, int n) { if (n < 0 || m < 0) return Integer.MAX_VALUE; else if (m == 0 && n == 0) return cost[m][n]; else return cost[m][n] + min( minCost(cost, m-1, n-1), minCost(cost, m-1, n), minCost(cost, m, n-1) ); } // Driver code public static void main(String args[]) { int cost[][] = { {1, 2, 3}, {4, 8, 2}, {1, 5, 3} }; System.out.print(minCost(cost, 2, 2)); }} // This code is contributed by Sam007", "e": 40386, "s": 39298, "text": null }, { "code": "# A Naive recursive implementation of MCP(Minimum Cost Path) problemR = 3C = 3import sys # Returns cost of minimum cost path from (0,0) to (m, n) in mat[R][C]def minCost(cost, m, n): if (n < 0 or m < 0): return sys.maxsize elif (m == 0 and n == 0): return cost[m][n] else: return cost[m][n] + min( minCost(cost, m-1, n-1), minCost(cost, m-1, n), minCost(cost, m, n-1) ) #A utility function that returns minimum of 3 integers */def min(x, y, z): if (x < y): return x if (x < z) else z else: return y if (y < z) else z # Driver program to test above functionscost= [ [1, 2, 3], [4, 8, 2], [1, 5, 3] ]print(minCost(cost, 2, 2)) # This code is contributed by# Smitha Dinesh Semwal", "e": 41190, "s": 40386, "text": null }, { "code": "/* A Naive recursive implementation ofMCP(Minimum Cost Path) problem */using System; class GFG{ /* A utility function that returns minimum of 3 integers */ static int min(int x, int y, int z) { if (x < y) return ((x < z) ? x : z); else return ((y < z) ? y : z); } /* Returns cost of minimum cost path from (0,0) to (m, n) in mat[R][C]*/ static int minCost(int [,]cost, int m , int n) { if (n < 0 || m < 0) return int.MaxValue; else if (m == 0 && n == 0) return cost[m, n]; else return cost[m, n] + min(minCost(cost, m - 1, n - 1), minCost(cost, m - 1, n), minCost(cost, m, n - 1) ); } // Driver code public static void Main() { int [,]cost = {{1, 2, 3}, {4, 8, 2}, {1, 5, 3}}; Console.Write(minCost(cost, 2, 2)); }} // This code is contributed// by shiv_bhakt.", "e": 42279, "s": 41190, "text": null }, { "code": "<?php/* A Naive recursive implementationof MCP(Minimum Cost Path) problem */ $R = 3;$C = 3; /* Returns cost of minimum cost path from (0,0) to(m, n) in mat[R][C]*/function minCost($cost, $m, $n){global $R;global $C;if ($n < 0 || $m < 0) return PHP_INT_MAX;else if ($m == 0 && $n == 0) return $cost[$m][$n];else return $cost[$m][$n] + min1(minCost($cost, $m - 1, $n - 1), minCost($cost, $m - 1, $n), minCost($cost, $m, $n - 1) );} /* A utility function thatreturns minimum of 3 integers */function min1($x, $y, $z){if ($x < $y) return ($x < $z)? $x : $z;else return ($y < $z)? $y : $z;} // Driver Code$cost = array(array(1, 2, 3), array (4, 8, 2), array (1, 5, 3));echo minCost($cost, 2, 2); // This code is contributed by mits.?>", "e": 43085, "s": 42279, "text": null }, { "code": "<script> // A Naive recursive implementation of// MCP(Minimum Cost Path) problem // A utility function that returns// minimum of 3 integersfunction min(x, y, z){ if (x < y) return (x < z) ? x : z; else return (y < z) ? y : z;} // Returns cost of minimum cost path// from (0,0) to (m, n) in mat[R][C]function minCost(cost, m, n){ if (n < 0 || m < 0) return Number.MAX_VALUE; else if (m == 0 && n == 0) return cost[m][n]; else return cost[m][n] + min(minCost(cost, m - 1, n - 1), minCost(cost, m - 1, n), minCost(cost, m, n - 1));} // Driver codevar cost = [ [ 1, 2, 3 ], [ 4, 8, 2 ], [ 1, 5, 3 ] ]; document.write(minCost(cost, 2, 2)); // This code is contributed by gauravrajput1 </script>", "e": 43911, "s": 43085, "text": null }, { "code": null, "e": 43914, "s": 43911, "text": " 8" }, { "code": null, "e": 43940, "s": 43914, "text": "Time Complexity: O(m * n)" }, { "code": null, "e": 44208, "s": 43940, "text": "It should be noted that the above function computes the same subproblems again and again. See the following recursion tree, there are many nodes which appear more than once. The time complexity of this naive recursive solution is exponential and it is terribly slow. " }, { "code": null, "e": 44688, "s": 44208, "text": "mC refers to minCost()\n mC(2, 2)\n / | \\\n / | \\ \n mC(1, 1) mC(1, 2) mC(2, 1)\n / | \\ / | \\ / | \\ \n / | \\ / | \\ / | \\\n mC(0,0) mC(0,1) mC(1,0) mC(0,1) mC(0,2) mC(1,1) mC(1,0) mC(1,1) mC(2,0)" }, { "code": null, "e": 44952, "s": 44688, "text": "So the MCP problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of the same subproblems can be avoided by constructing a temporary array tc[][] in a bottom-up manner." }, { "code": null, "e": 44956, "s": 44952, "text": "C++" }, { "code": null, "e": 44958, "s": 44956, "text": "C" }, { "code": null, "e": 44963, "s": 44958, "text": "Java" }, { "code": null, "e": 44970, "s": 44963, "text": "Python" }, { "code": null, "e": 44973, "s": 44970, "text": "C#" }, { "code": null, "e": 44977, "s": 44973, "text": "PHP" }, { "code": null, "e": 44988, "s": 44977, "text": "Javascript" }, { "code": "/* Dynamic Programming implementation of MCP problem */#include <bits/stdc++.h>#include<limits.h>#define R 3#define C 3using namespace std;int min(int x, int y, int z); int minCost(int cost[R][C], int m, int n){ int i, j; // Instead of following line, we can use int tc[m+1][n+1] or // dynamically allocate memory to save space. The following line is // used to keep the program simple and make it working on all compilers. int tc[R][C]; tc[0][0] = cost[0][0]; /* Initialize first column of total cost(tc) array */ for (i = 1; i <= m; i++) tc[i][0] = tc[i - 1][0] + cost[i][0]; /* Initialize first row of tc array */ for (j = 1; j <= n; j++) tc[0][j] = tc[0][j - 1] + cost[0][j]; /* Construct rest of the tc array */ for (i = 1; i <= m; i++) for (j = 1; j <= n; j++) tc[i][j] = min(tc[i - 1][j - 1], tc[i - 1][j], tc[i][j - 1]) + cost[i][j]; return tc[m][n];} /* A utility function that returns minimum of 3 integers */int min(int x, int y, int z){ if (x < y) return (x < z)? x : z; else return (y < z)? y : z;} /* Driver code*/int main(){ int cost[R][C] = { {1, 2, 3}, {4, 8, 2}, {1, 5, 3} }; cout << \" \" << minCost(cost, 2, 2); return 0;} // This code is contributed by shivanisinghss2110", "e": 46385, "s": 44988, "text": null }, { "code": "/* Dynamic Programming implementation of MCP problem */#include<stdio.h>#include<limits.h>#define R 3#define C 3 int min(int x, int y, int z); int minCost(int cost[R][C], int m, int n){ int i, j; // Instead of following line, we can use int tc[m+1][n+1] or // dynamically allocate memory to save space. The following line is // used to keep the program simple and make it working on all compilers. int tc[R][C]; tc[0][0] = cost[0][0]; /* Initialize first column of total cost(tc) array */ for (i = 1; i <= m; i++) tc[i][0] = tc[i-1][0] + cost[i][0]; /* Initialize first row of tc array */ for (j = 1; j <= n; j++) tc[0][j] = tc[0][j-1] + cost[0][j]; /* Construct rest of the tc array */ for (i = 1; i <= m; i++) for (j = 1; j <= n; j++) tc[i][j] = min(tc[i-1][j-1], tc[i-1][j], tc[i][j-1]) + cost[i][j]; return tc[m][n];} /* A utility function that returns minimum of 3 integers */int min(int x, int y, int z){ if (x < y) return (x < z)? x : z; else return (y < z)? y : z;} /* Driver program to test above functions */int main(){ int cost[R][C] = { {1, 2, 3}, {4, 8, 2}, {1, 5, 3} }; printf(\" %d \", minCost(cost, 2, 2)); return 0;}", "e": 47722, "s": 46385, "text": null }, { "code": "/* Java program for Dynamic Programming implementation of Min Cost Path problem */import java.util.*; class MinimumCostPath{ /* A utility function that returns minimum of 3 integers */ private static int min(int x, int y, int z) { if (x < y) return (x < z)? x : z; else return (y < z)? y : z; } private static int minCost(int cost[][], int m, int n) { int i, j; int tc[][]=new int[m+1][n+1]; tc[0][0] = cost[0][0]; /* Initialize first column of total cost(tc) array */ for (i = 1; i <= m; i++) tc[i][0] = tc[i-1][0] + cost[i][0]; /* Initialize first row of tc array */ for (j = 1; j <= n; j++) tc[0][j] = tc[0][j-1] + cost[0][j]; /* Construct rest of the tc array */ for (i = 1; i <= m; i++) for (j = 1; j <= n; j++) tc[i][j] = min(tc[i-1][j-1], tc[i-1][j], tc[i][j-1]) + cost[i][j]; return tc[m][n]; } /* Driver program to test above functions */ public static void main(String args[]) { int cost[][]= {{1, 2, 3}, {4, 8, 2}, {1, 5, 3}}; System.out.println(minCost(cost,2,2)); }}// This code is contributed by Pankaj Kumar", "e": 49059, "s": 47722, "text": null }, { "code": "# Dynamic Programming Python implementation of Min Cost Path# problemR = 3C = 3 def minCost(cost, m, n): # Instead of following line, we can use int tc[m+1][n+1] or # dynamically allocate memoery to save space. The following # line is used to keep te program simple and make it working # on all compilers. tc = [[0 for x in range(C)] for x in range(R)] tc[0][0] = cost[0][0] # Initialize first column of total cost(tc) array for i in range(1, m+1): tc[i][0] = tc[i-1][0] + cost[i][0] # Initialize first row of tc array for j in range(1, n+1): tc[0][j] = tc[0][j-1] + cost[0][j] # Construct rest of the tc array for i in range(1, m+1): for j in range(1, n+1): tc[i][j] = min(tc[i-1][j-1], tc[i-1][j], tc[i][j-1]) + cost[i][j] return tc[m][n] # Driver program to test above functionscost = [[1, 2, 3], [4, 8, 2], [1, 5, 3]]print(minCost(cost, 2, 2)) # This code is contributed by Bhavya Jain", "e": 50040, "s": 49059, "text": null }, { "code": "// C# program for Dynamic Programming implementation// of Min Cost Path problemusing System; class GFG{ // A utility function that // returns minimum of 3 integers private static int min(int x, int y, int z) { if (x < y) return (x < z)? x : z; else return (y < z)? y : z; } private static int minCost(int [,]cost, int m, int n) { int i, j; int [,]tc=new int[m+1,n+1]; tc[0,0] = cost[0,0]; /* Initialize first column of total cost(tc) array */ for (i = 1; i <= m; i++) tc[i, 0] = tc[i - 1, 0] + cost[i, 0]; /* Initialize first row of tc array */ for (j = 1; j <= n; j++) tc[0, j] = tc[0, j - 1] + cost[0, j]; /* Construct rest of the tc array */ for (i = 1; i <= m; i++) for (j = 1; j <= n; j++) tc[i, j] = min(tc[i - 1, j - 1], tc[i - 1, j], tc[i, j - 1]) + cost[i, j]; return tc[m, n]; } // Driver program public static void Main() { int [,]cost= {{1, 2, 3}, {4, 8, 2}, {1, 5, 3}}; Console.Write(minCost(cost,2,2)); }} // This code is contributed by Sam007.", "e": 51302, "s": 50040, "text": null }, { "code": "<?php// DP implementation// of MCP problem$R = 3;$C = 3; function minCost($cost, $m, $n){ global $R; global $C; // Instead of following line, // we can use int tc[m+1][n+1] // or dynamically allocate // memory to save space. The // following line is used to keep // the program simple and make // it working on all compilers. $tc; for ($i = 0; $i <= $R; $i++) for ($j = 0; $j <= $C; $j++) $tc[$i][$j] = 0; $tc[0][0] = $cost[0][0]; /* Initialize first column of total cost(tc) array */ for ($i = 1; $i <= $m; $i++) $tc[$i][0] = $tc[$i - 1][0] + $cost[$i][0]; /* Initialize first row of tc array */ for ($j = 1; $j <= $n; $j++) $tc[0][$j] = $tc[0][$j - 1] + $cost[0][$j]; /* Construct rest of the tc array */ for ($i = 1; $i <= $m; $i++) for ($j = 1; $j <= $n; $j++) // returns minimum of 3 integers $tc[$i][$j] = min($tc[$i - 1][$j - 1], $tc[$i - 1][$j], $tc[$i][$j - 1]) + $cost[$i][$j]; return $tc[$m][$n];} // Driver Code$cost = array(array(1, 2, 3), array(4, 8, 2), array(1, 5, 3));echo minCost($cost, 2, 2); // This code is contributed by mits?>", "e": 52644, "s": 51302, "text": null }, { "code": "<script> // Javascript program for Dynamic Programming implementation // of Min Cost Path problem /* A utility function that returns minimum of 3 integers */ function min(x, y, z) { if (x < y) return (x < z)? x : z; else return (y < z)? y : z; } function minCost(cost, m, n) { let i, j; let tc = new Array(m+1); for(let k = 0; k < m + 1; k++) { tc[k] = new Array(n+1); } tc[0][0] = cost[0][0]; /* Initialize first column of total cost(tc) array */ for (i = 1; i <= m; i++) tc[i][0] = tc[i-1][0] + cost[i][0]; /* Initialize first row of tc array */ for (j = 1; j <= n; j++) tc[0][j] = tc[0][j-1] + cost[0][j]; /* Construct rest of the tc array */ for (i = 1; i <= m; i++) for (j = 1; j <= n; j++) tc[i][j] = Math.min(tc[i-1][j-1], tc[i-1][j], tc[i][j-1]) + cost[i][j]; return tc[m][n]; } let cost = [[1, 2, 3], [4, 8, 2], [1, 5, 3]]; document.write(minCost(cost,2,2)); </script>", "e": 53873, "s": 52644, "text": null }, { "code": null, "e": 53876, "s": 53873, "text": " 8" }, { "code": null, "e": 53984, "s": 53876, "text": "Time Complexity of the DP implementation is O(mn) which is much better than Naive Recursive implementation." }, { "code": null, "e": 54010, "s": 53984, "text": "Auxiliary Space: O(m * n)" }, { "code": null, "e": 54110, "s": 54010, "text": "Space Optimization: The idea is to use the same given array to store the solutions of subproblems. " }, { "code": null, "e": 54114, "s": 54110, "text": "C++" }, { "code": null, "e": 54119, "s": 54114, "text": "Java" }, { "code": null, "e": 54127, "s": 54119, "text": "Python3" }, { "code": null, "e": 54130, "s": 54127, "text": "C#" }, { "code": null, "e": 54141, "s": 54130, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>#define endl \"\\n\"using namespace std; const int row = 3;const int col = 3; int minCost(int cost[row][col]) { // for 1st column for (int i=1 ; i<row ; i++){ cost[i][0] += cost[i-1][0]; } // for 1st row for (int j=1 ; j<col ; j++){ cost[0][j] += cost[0][j-1]; } // for rest of the 2d matrix for (int i=1 ; i<row ; i++) { for (int j=1 ; j<col ; j++) { cost[i][j] += min(cost[i-1][j-1], min(cost[i-1][j], cost[i][j-1])); } } // returning the value in last cell return cost[row-1][col-1];}int main(int argc, char const *argv[]){ int cost[row][col] = { {1, 2, 3}, {4, 8, 2}, {1, 5, 3} }; cout << minCost(cost) << endl; return 0;} // Contributed by Mansimar-Anand TU_2022 p_e_k_k_a Task @ Codechef/Codeforces", "e": 55015, "s": 54141, "text": null }, { "code": "// Java program for the// above approachimport java.util.*;class GFG{ static int row = 3;static int col = 3; static int minCost(int cost[][]){ // for 1st column for (int i = 1; i < row; i++) { cost[i][0] += cost[i - 1][0]; } // for 1st row for (int j = 1; j < col; j++) { cost[0][j] += cost[0][j - 1]; } // for rest of the 2d matrix for (int i = 1; i < row; i++) { for (int j = 1; j < col; j++) { cost[i][j] += Math.min(cost[i - 1][j - 1], Math.min(cost[i - 1][j], cost[i][j - 1])); } } // Returning the value in // last cell return cost[row - 1][col - 1];} // Driver code public static void main(String[] args){ int cost[][] = {{1, 2, 3}, {4, 8, 2}, {1, 5, 3} }; System.out.print(minCost(cost) + \"\\n\");}} // This code is contributed by Amit Katiyar", "e": 55893, "s": 55015, "text": null }, { "code": "# Python3 program for the# above approach def minCost(cost, row, col): # For 1st column for i in range(1, row): cost[i][0] += cost[i - 1][0] # For 1st row for j in range(1, col): cost[0][j] += cost[0][j - 1] # For rest of the 2d matrix for i in range(1, row): for j in range(1, col): cost[i][j] += (min(cost[i - 1][j - 1], min(cost[i - 1][j], cost[i][j - 1]))) # Returning the value in # last cell return cost[row - 1][col - 1] # Driver codeif __name__ == '__main__': row = 3 col = 3 cost = [ [ 1, 2, 3 ], [ 4, 8, 2 ], [ 1, 5, 3 ] ] print(minCost(cost, row, col)); # This code is contributed by Amit Katiyar", "e": 56684, "s": 55893, "text": null }, { "code": "// C# program for the// above approachusing System;class GFG{ static int row = 3;static int col = 3; static int minCost(int [,]cost){ // for 1st column for (int i = 1; i < row; i++) { cost[i, 0] += cost[i - 1, 0]; } // for 1st row for (int j = 1; j < col; j++) { cost[0, j] += cost[0, j - 1]; } // for rest of the 2d matrix for (int i = 1; i < row; i++) { for (int j = 1; j < col; j++) { cost[i,j] += Math.Min(cost[i - 1, j - 1], Math.Min(cost[i - 1, j], cost[i, j - 1])); } } // Returning the value in // last cell return cost[row - 1, col - 1];} // Driver code public static void Main(String[] args){ int [,]cost = {{1, 2, 3}, {4, 8, 2}, {1, 5, 3} }; Console.Write(minCost(cost) + \"\\n\");}} // This code is contributed by Rajput-Ji", "e": 57573, "s": 56684, "text": null }, { "code": "<script> // javascript program for the// above approach var row = 3;var col = 3; function minCost(cost){ // for 1st column for (i = 1; i < row; i++) { cost[i][0] += cost[i - 1][0]; } // for 1st row for (j = 1; j < col; j++) { cost[0][j] += cost[0][j - 1]; } // for rest of the 2d matrix for (i = 1; i < row; i++) { for (j = 1; j < col; j++) { cost[i][j] += Math.min(cost[i - 1][j - 1], Math.min(cost[i - 1][j], cost[i][j - 1])); } } // Returning the value in // last cell return cost[row - 1][col - 1];} // Driver code var cost = [[1, 2, 3],[4, 8, 2],[1, 5, 3] ];document.write(minCost(cost) + '<br>'); // This code is contributed by 29AjayKumar </script>", "e": 58316, "s": 57573, "text": null }, { "code": null, "e": 58318, "s": 58316, "text": "8" }, { "code": null, "e": 58348, "s": 58318, "text": "Time Complexity: O(row * col)" }, { "code": null, "e": 58370, "s": 58348, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 58491, "s": 58370, "text": "Alternate Solution We can also use the Dijkstra’s shortest path algorithm. Below is the implementation of the approach: " }, { "code": null, "e": 58495, "s": 58491, "text": "C++" }, { "code": "/* Minimum Cost Path using Dijkstra’s shortest path algorithm with Min Heap by dinglizeng */#include <stdio.h>#include <queue>#include <limits.h>using namespace std; /* define the number of rows and the number of columns */#define R 4#define C 5 /* 8 possible moves */int dx[] = {1,-1, 0, 0, 1, 1,-1,-1};int dy[] = {0, 0, 1,-1, 1,-1, 1,-1}; /* The data structure to store the coordinates of \\\\ the unit square and the cost of path from the top left. */struct Cell{ int x; int y; int cost;}; /* The compare class to be used by a Min Heap. * The greater than condition is used as this is for a Min Heap based on priority_queue. */class mycomparison{public: bool operator() (const Cell &lhs, const Cell &rhs) const { return (lhs.cost > rhs.cost); }}; /* To verify whether a move is within the boundary. */bool isSafe(int x, int y){ return x >= 0 && x < R && y >= 0 && y < C;} /* This solution is based on Dijkstra’s shortest path algorithm * For each unit square being visited, we examine all possible next moves in 8 directions, * calculate the accumulated cost of path for each next move, adjust the cost of path of the adjacent units to the minimum as needed. * then add the valid next moves into a Min Heap. * The Min Heap pops out the next move with the minimum accumulated cost of path. * Once the iteration reaches the last unit at the lower right corner, the minimum cost path will be returned. */int minCost(int cost[R][C], int m, int n) { /* the array to store the accumulated cost of path from top left corner */ int dp[R][C]; /* the array to record whether a unit square has been visited */ bool visited[R][C]; /* Initialize these two arrays, set path cost to maximum integer value, each unit as not visited */ for(int i = 0; i < R; i++) { for(int j = 0; j < C; j++) { dp[i][j] = INT_MAX; visited[i][j] = false; } } /* Define a reverse priority queue. * Priority queue is a heap based implementation. * The default behavior of a priority queue is to have the maximum element at the top. * The compare class is used in the definition of the Min Heap. */ priority_queue<Cell, vector<Cell>, mycomparison> pq; /* initialize the starting top left unit with the cost and add it to the queue as the first move. */ dp[0][0] = cost[0][0]; pq.push({0, 0, cost[0][0]}); while(!pq.empty()) { /* pop a move from the queue, ignore the units already visited */ Cell cell = pq.top(); pq.pop(); int x = cell.x; int y = cell.y; if(visited[x][y]) continue; /* mark the current unit as visited */ visited[x][y] = true; /* examine all non-visited adjacent units in 8 directions * calculate the accumulated cost of path for each next move from this unit, * adjust the cost of path for each next adjacent units to the minimum if possible. */ for(int i = 0; i < 8; i++) { int next_x = x + dx[i]; int next_y = y + dy[i]; if(isSafe(next_x, next_y) && !visited[next_x][next_y]) { dp[next_x][next_y] = min(dp[next_x][next_y], dp[x][y] + cost[next_x][next_y]); pq.push({next_x, next_y, dp[next_x][next_y]}); } } } /* return the minimum cost path at the lower right corner */ return dp[m][n]; } /* Driver program to test above functions */int main(){ int cost[R][C] = { {1, 8, 8, 1, 5}, {4, 1, 1, 8, 1}, {4, 2, 8, 8, 1}, {1, 5, 8, 8, 1} }; printf(\" %d \", minCost(cost, 3, 4)); return 0;}", "e": 62265, "s": 58495, "text": null }, { "code": null, "e": 62268, "s": 62265, "text": " 7" }, { "code": null, "e": 62587, "s": 62268, "text": "Using a reverse priority queue in this solution can reduce the time complexity compared with a full scan looking for the node with minimum path cost. The overall Time Complexity of the DP implementation is O(mn) without consideration of priority queue in use, which is much better than Naive Recursive implementation. " }, { "code": null, "e": 62630, "s": 62587, "text": "?list=PLqM7alHXFySEQDk2MDfbwEdjd2svVJH9p " }, { "code": null, "e": 62757, "s": 62632, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 62766, "s": 62759, "text": "Sam007" }, { "code": null, "e": 62779, "s": 62766, "text": "Mithun Kumar" }, { "code": null, "e": 62792, "s": 62779, "text": "Vishal_Khoda" }, { "code": null, "e": 62801, "s": 62792, "text": "maveriek" }, { "code": null, "e": 62812, "s": 62801, "text": "dinglizeng" }, { "code": null, "e": 62827, "s": 62812, "text": "amit143katiyar" }, { "code": null, "e": 62837, "s": 62827, "text": "Rajput-Ji" }, { "code": null, "e": 62851, "s": 62837, "text": "nikhilchhipa9" }, { "code": null, "e": 62870, "s": 62851, "text": "shivanisinghss2110" }, { "code": null, "e": 62884, "s": 62870, "text": "GauravRajput1" }, { "code": null, "e": 62895, "s": 62884, "text": "decode2207" }, { "code": null, "e": 62907, "s": 62895, "text": "29AjayKumar" }, { "code": null, "e": 62923, "s": 62907, "text": "subhammahato348" }, { "code": null, "e": 62933, "s": 62923, "text": "subham348" }, { "code": null, "e": 62940, "s": 62933, "text": "Amazon" }, { "code": null, "e": 62951, "s": 62940, "text": "MakeMyTrip" }, { "code": null, "e": 62959, "s": 62951, "text": "Samsung" }, { "code": null, "e": 62979, "s": 62959, "text": "Dynamic Programming" }, { "code": null, "e": 62992, "s": 62979, "text": "Mathematical" }, { "code": null, "e": 62999, "s": 62992, "text": "Matrix" }, { "code": null, "e": 63006, "s": 62999, "text": "Amazon" }, { "code": null, "e": 63014, "s": 63006, "text": "Samsung" }, { "code": null, "e": 63025, "s": 63014, "text": "MakeMyTrip" }, { "code": null, "e": 63045, "s": 63025, "text": "Dynamic Programming" }, { "code": null, "e": 63058, "s": 63045, "text": "Mathematical" }, { "code": null, "e": 63065, "s": 63058, "text": "Matrix" }, { "code": null, "e": 63163, "s": 63065, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 63195, "s": 63163, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 63226, "s": 63195, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 63259, "s": 63226, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 63286, "s": 63259, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 63324, "s": 63286, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 63339, "s": 63324, "text": "C++ Data Types" }, { "code": null, "e": 63382, "s": 63339, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 63406, "s": 63382, "text": "Merge two sorted arrays" } ]
Python Program to Filter Rows with a specific Pair Sum - GeeksforGeeks
12 Nov, 2020 Given Matrix, the following program shows how to extract all rows which have a pair such that their sum is equal to a specific number, here denoted as K. Input : test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]], k = 8 Output : [[1, 5, 3, 6], [6, 9, 3, 2]] Explanation : 5 + 3 = 8 and 6 + 2 = 8. Input : test_list = [[1, 5, 4, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 7]], k = 8 Output : [] Explanation : No list with 8 as pair summation. Method 1 : Using loop and list comprehension In this we perform the task of getting all the pair whose sum is equal to a given value using external function and filtering of lists is done using list comprehension. Python3 # get pair sumdef pair_sum(x, k): # checking pair sum for idx in range(len(x)): for ix in range(idx + 1, len(x)): if x[idx] + x[ix] == k: return True return False # initializing listtest_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]] # printing original listprint("The original list is : " + str(test_list)) # initializing Kk = 8 # checking for pair sumres = [ele for ele in test_list if pair_sum(ele, k)] # printing resultprint("Filtered Rows : " + str(res)) Output: The original list is : [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]] Filtered Rows : [[1, 5, 3, 6], [6, 9, 3, 2]] Method 2 : Using filter() and lambda In this, we perform task of filtering using filter() and lambda function. Python3 # get pair sumdef pair_sum(x, k): # checking pair sum for idx in range(len(x)): for ix in range(idx + 1, len(x)): if x[idx] + x[ix] == k: return True return False # initializing listtest_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]] # printing original listprint("The original list is : " + str(test_list)) # initializing Kk = 8 # checking for pair sum# filtering using filter() and lambdares = list(filter(lambda ele: pair_sum(ele, k), test_list)) # printing resultprint("Filtered Rows : " + str(res)) Output: The original list is : [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]] Filtered Rows : [[1, 5, 3, 6], [6, 9, 3, 2]] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n12 Nov, 2020" }, { "code": null, "e": 25691, "s": 25537, "text": "Given Matrix, the following program shows how to extract all rows which have a pair such that their sum is equal to a specific number, here denoted as K." }, { "code": null, "e": 25997, "s": 25691, "text": "Input : test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]], k = 8 Output : [[1, 5, 3, 6], [6, 9, 3, 2]] Explanation : 5 + 3 = 8 and 6 + 2 = 8. Input : test_list = [[1, 5, 4, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 7]], k = 8 Output : [] Explanation : No list with 8 as pair summation. " }, { "code": null, "e": 26042, "s": 25997, "text": "Method 1 : Using loop and list comprehension" }, { "code": null, "e": 26211, "s": 26042, "text": "In this we perform the task of getting all the pair whose sum is equal to a given value using external function and filtering of lists is done using list comprehension." }, { "code": null, "e": 26219, "s": 26211, "text": "Python3" }, { "code": "# get pair sumdef pair_sum(x, k): # checking pair sum for idx in range(len(x)): for ix in range(idx + 1, len(x)): if x[idx] + x[ix] == k: return True return False # initializing listtest_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing Kk = 8 # checking for pair sumres = [ele for ele in test_list if pair_sum(ele, k)] # printing resultprint(\"Filtered Rows : \" + str(res))", "e": 26747, "s": 26219, "text": null }, { "code": null, "e": 26755, "s": 26747, "text": "Output:" }, { "code": null, "e": 26835, "s": 26755, "text": "The original list is : [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]" }, { "code": null, "e": 26880, "s": 26835, "text": "Filtered Rows : [[1, 5, 3, 6], [6, 9, 3, 2]]" }, { "code": null, "e": 26917, "s": 26880, "text": "Method 2 : Using filter() and lambda" }, { "code": null, "e": 26992, "s": 26917, "text": "In this, we perform task of filtering using filter() and lambda function. " }, { "code": null, "e": 27000, "s": 26992, "text": "Python3" }, { "code": "# get pair sumdef pair_sum(x, k): # checking pair sum for idx in range(len(x)): for ix in range(idx + 1, len(x)): if x[idx] + x[ix] == k: return True return False # initializing listtest_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing Kk = 8 # checking for pair sum# filtering using filter() and lambdares = list(filter(lambda ele: pair_sum(ele, k), test_list)) # printing resultprint(\"Filtered Rows : \" + str(res))", "e": 27572, "s": 27000, "text": null }, { "code": null, "e": 27580, "s": 27572, "text": "Output:" }, { "code": null, "e": 27660, "s": 27580, "text": "The original list is : [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]" }, { "code": null, "e": 27705, "s": 27660, "text": "Filtered Rows : [[1, 5, 3, 6], [6, 9, 3, 2]]" }, { "code": null, "e": 27726, "s": 27705, "text": "Python list-programs" }, { "code": null, "e": 27733, "s": 27726, "text": "Python" }, { "code": null, "e": 27749, "s": 27733, "text": "Python Programs" }, { "code": null, "e": 27847, "s": 27749, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27879, "s": 27847, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27921, "s": 27879, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27963, "s": 27921, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27990, "s": 27963, "text": "Python Classes and Objects" }, { "code": null, "e": 28046, "s": 27990, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28068, "s": 28046, "text": "Defaultdict in Python" }, { "code": null, "e": 28107, "s": 28068, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28153, "s": 28107, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28191, "s": 28153, "text": "Python | Convert a list to dictionary" } ]
How to show legend in heatmap in R? - GeeksforGeeks
23 Feb, 2021 A heat map is a graphical representation of data where each data value is represented in terms of color value. Heatmap is created using heatmap() function in R. Legend associated with histogram makes it easy to understand what the color values mean. Legend is shown with histogram using legend() function in R. heatmap() function in R Language is used to plot a heatmap. Heatmap is defined as a graphical representation of data using colors to visualize the value of the matrix. Syntax: heatmap(data) Parameters:data: It represent matrix data, such as values of rows and columns Return: This function draws a heatmap legend() function in R Language is used to add legends to an existing Plot. A legend is defined as an area of the graph plot describing each of the parts of the plot. The legend plot is used to show statistical data in graphical form. Syntax:legend(x, y, legend, fill, col, bg, lty, cex, title, text.font, bg) Parameters:x and y: These are co-ordinates to be used to position the legendlegend: Text of the legendfill: Colors to use for filling the boxes with legend textcol: Colors of linesbg: It defines background color for the legend box.title: Legend title (optional)text.font: An integer specifying the font style of the legend (optional) Returns: Legend plot Create data matrix Plot heatmap using heatmap() method Provide appropriate attributes with respective values Associate legend with heatmap using legend() method Run code to display plot Example 1: R # Create data matrixA <- matrix(rnorm(25, 0, 5), nrow = 5, ncol = 5) print(A) # Plot a heatmap heatmap(A,Rowv=NA,Colv=NA,col=heat.colors(3)) # Plot a corresponding legendlegend(x="right", legend=c("min", "med", "max"),fill=heat.colors(3)) Output: Example 2: R # Import library for colorlibrary(RColorBrewer) # Create data matrixA = matrix( c(1,2,0,3,4,0,2,1,3,3,0,0,4, 4,1,4,3,1,4,3,0,2,1,1,4), nrow = 5, ncol = 5) # Plot a heatmapheatmap(A, Rowv = NA, Colv = NA, col = colorRampPalette(brewer.pal(8,"Blues"))(3)) # Plot a legend in bottom right part of heatmaplegend(x = "bottomright", legend = c("low", "medium", "high"), cex = 0.8, fill = colorRampPalette(brewer.pal(8, "Blues"))(3)) Output: Picked R-Charts R-Graphs R-plots R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to import an Excel File into R ? How to filter R DataFrame by values in a column? Time Series Analysis in R Logistic Regression in R Programming R - if statement
[ { "code": null, "e": 26487, "s": 26459, "text": "\n23 Feb, 2021" }, { "code": null, "e": 26798, "s": 26487, "text": "A heat map is a graphical representation of data where each data value is represented in terms of color value. Heatmap is created using heatmap() function in R. Legend associated with histogram makes it easy to understand what the color values mean. Legend is shown with histogram using legend() function in R." }, { "code": null, "e": 26966, "s": 26798, "text": "heatmap() function in R Language is used to plot a heatmap. Heatmap is defined as a graphical representation of data using colors to visualize the value of the matrix." }, { "code": null, "e": 26988, "s": 26966, "text": "Syntax: heatmap(data)" }, { "code": null, "e": 27066, "s": 26988, "text": "Parameters:data: It represent matrix data, such as values of rows and columns" }, { "code": null, "e": 27104, "s": 27066, "text": "Return: This function draws a heatmap" }, { "code": null, "e": 27339, "s": 27104, "text": "legend() function in R Language is used to add legends to an existing Plot. A legend is defined as an area of the graph plot describing each of the parts of the plot. The legend plot is used to show statistical data in graphical form." }, { "code": null, "e": 27414, "s": 27339, "text": "Syntax:legend(x, y, legend, fill, col, bg, lty, cex, title, text.font, bg)" }, { "code": null, "e": 27748, "s": 27414, "text": "Parameters:x and y: These are co-ordinates to be used to position the legendlegend: Text of the legendfill: Colors to use for filling the boxes with legend textcol: Colors of linesbg: It defines background color for the legend box.title: Legend title (optional)text.font: An integer specifying the font style of the legend (optional)" }, { "code": null, "e": 27769, "s": 27748, "text": "Returns: Legend plot" }, { "code": null, "e": 27788, "s": 27769, "text": "Create data matrix" }, { "code": null, "e": 27824, "s": 27788, "text": "Plot heatmap using heatmap() method" }, { "code": null, "e": 27878, "s": 27824, "text": "Provide appropriate attributes with respective values" }, { "code": null, "e": 27930, "s": 27878, "text": "Associate legend with heatmap using legend() method" }, { "code": null, "e": 27955, "s": 27930, "text": "Run code to display plot" }, { "code": null, "e": 27966, "s": 27955, "text": "Example 1:" }, { "code": null, "e": 27968, "s": 27966, "text": "R" }, { "code": "# Create data matrixA <- matrix(rnorm(25, 0, 5), nrow = 5, ncol = 5) print(A) # Plot a heatmap heatmap(A,Rowv=NA,Colv=NA,col=heat.colors(3)) # Plot a corresponding legendlegend(x=\"right\", legend=c(\"min\", \"med\", \"max\"),fill=heat.colors(3))", "e": 28210, "s": 27968, "text": null }, { "code": null, "e": 28218, "s": 28210, "text": "Output:" }, { "code": null, "e": 28229, "s": 28218, "text": "Example 2:" }, { "code": null, "e": 28231, "s": 28229, "text": "R" }, { "code": "# Import library for colorlibrary(RColorBrewer) # Create data matrixA = matrix( c(1,2,0,3,4,0,2,1,3,3,0,0,4, 4,1,4,3,1,4,3,0,2,1,1,4), nrow = 5, ncol = 5) # Plot a heatmapheatmap(A, Rowv = NA, Colv = NA, col = colorRampPalette(brewer.pal(8,\"Blues\"))(3)) # Plot a legend in bottom right part of heatmaplegend(x = \"bottomright\", legend = c(\"low\", \"medium\", \"high\"), cex = 0.8, fill = colorRampPalette(brewer.pal(8, \"Blues\"))(3))", "e": 28688, "s": 28231, "text": null }, { "code": null, "e": 28696, "s": 28688, "text": "Output:" }, { "code": null, "e": 28703, "s": 28696, "text": "Picked" }, { "code": null, "e": 28712, "s": 28703, "text": "R-Charts" }, { "code": null, "e": 28721, "s": 28712, "text": "R-Graphs" }, { "code": null, "e": 28729, "s": 28721, "text": "R-plots" }, { "code": null, "e": 28740, "s": 28729, "text": "R Language" }, { "code": null, "e": 28838, "s": 28740, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28890, "s": 28838, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28925, "s": 28890, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28963, "s": 28925, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29021, "s": 28963, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29064, "s": 29021, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29101, "s": 29064, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 29150, "s": 29101, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29176, "s": 29150, "text": "Time Series Analysis in R" }, { "code": null, "e": 29213, "s": 29176, "text": "Logistic Regression in R Programming" } ]
Python | Sort list of numbers by sum of their digits - GeeksforGeeks
11 May, 2020 Given a list of non-negative numbers, the task is to sort these integers according to the sum of their digits. Examples: Input : [12, 10, 106, 31, 15] Output : [10, 12, 31, 15, 106] Input : [1111, 19, 29, 11, 12, 9] Output : [11, 12, 1111, 9, 19, 29] Let’s discuss few Pythonic ways to do this task. Approach #1 : List comprehension Using for loop to convert each element of list to a different list with its digits as elements. Now, use the sorted function with the above-mentioned function as key. # Python3 Program to Sort list of# integers according to sum of digits def sortList(lst): digits = [int(digit) for digit in str(lst) ] return sum(digits) # Driver Codelst = [12, 10, 106, 31, 15]print(sorted(lst, key = sortList)) [10, 12, 31, 15, 106] Approach #2 : Using map() This approach is similar to the above approach with a slight difference that instead of for loop, we use map() to convert each element of list to a different list with its digit as elements and then follow the similar approach as above. # Python3 Program to Sort list of# integers according to sum of digits def sortList(num): return sum(map(int, str(num))) # Driver Codelst = [12, 10, 106, 31, 15]result = sorted(lst, key = sortList)print(result) [10, 12, 31, 15, 106] There is also a one-liner alternative to the above mentioned approach. def sortList(lst): return sorted(lst, key = lambda x:(sum(map(int, str(x))))) Python list-programs python-list Python-sort Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n11 May, 2020" }, { "code": null, "e": 25648, "s": 25537, "text": "Given a list of non-negative numbers, the task is to sort these integers according to the sum of their digits." }, { "code": null, "e": 25658, "s": 25648, "text": "Examples:" }, { "code": null, "e": 25790, "s": 25658, "text": "Input : [12, 10, 106, 31, 15]\nOutput : [10, 12, 31, 15, 106]\n\nInput : [1111, 19, 29, 11, 12, 9]\nOutput : [11, 12, 1111, 9, 19, 29]\n" }, { "code": null, "e": 25839, "s": 25790, "text": "Let’s discuss few Pythonic ways to do this task." }, { "code": null, "e": 25872, "s": 25839, "text": "Approach #1 : List comprehension" }, { "code": null, "e": 26039, "s": 25872, "text": "Using for loop to convert each element of list to a different list with its digits as elements. Now, use the sorted function with the above-mentioned function as key." }, { "code": "# Python3 Program to Sort list of# integers according to sum of digits def sortList(lst): digits = [int(digit) for digit in str(lst) ] return sum(digits) # Driver Codelst = [12, 10, 106, 31, 15]print(sorted(lst, key = sortList))", "e": 26280, "s": 26039, "text": null }, { "code": null, "e": 26303, "s": 26280, "text": "[10, 12, 31, 15, 106]\n" }, { "code": null, "e": 26329, "s": 26303, "text": "Approach #2 : Using map()" }, { "code": null, "e": 26566, "s": 26329, "text": "This approach is similar to the above approach with a slight difference that instead of for loop, we use map() to convert each element of list to a different list with its digit as elements and then follow the similar approach as above." }, { "code": "# Python3 Program to Sort list of# integers according to sum of digits def sortList(num): return sum(map(int, str(num))) # Driver Codelst = [12, 10, 106, 31, 15]result = sorted(lst, key = sortList)print(result)", "e": 26786, "s": 26566, "text": null }, { "code": null, "e": 26809, "s": 26786, "text": "[10, 12, 31, 15, 106]\n" }, { "code": null, "e": 26880, "s": 26809, "text": "There is also a one-liner alternative to the above mentioned approach." }, { "code": "def sortList(lst): return sorted(lst, key = lambda x:(sum(map(int, str(x)))))", "e": 26961, "s": 26880, "text": null }, { "code": null, "e": 26982, "s": 26961, "text": "Python list-programs" }, { "code": null, "e": 26994, "s": 26982, "text": "python-list" }, { "code": null, "e": 27006, "s": 26994, "text": "Python-sort" }, { "code": null, "e": 27013, "s": 27006, "text": "Python" }, { "code": null, "e": 27029, "s": 27013, "text": "Python Programs" }, { "code": null, "e": 27041, "s": 27029, "text": "python-list" }, { "code": null, "e": 27139, "s": 27041, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27171, "s": 27139, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27213, "s": 27171, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27255, "s": 27213, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27282, "s": 27255, "text": "Python Classes and Objects" }, { "code": null, "e": 27338, "s": 27282, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27360, "s": 27338, "text": "Defaultdict in Python" }, { "code": null, "e": 27399, "s": 27360, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27445, "s": 27399, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27483, "s": 27445, "text": "Python | Convert a list to dictionary" } ]
Python | sympy.sec() method - GeeksforGeeks
02 Aug, 2019 With the help of sympy.sec() method, we are able to find the value of sec theta using sympy.sec() function. Syntax : sympy.sec()Return : Return value of sec theta. Example #1 :In this example we can see that by using sympy.sec() method, we can find the value of sec theta. # import sympyfrom sympy import * # Use sympy.sec() methodgfg = simplify(sec(pi / 6)) print(gfg) Output : 2*sqrt(3)/3 Example #2 : # import sympyfrom sympy import * # Use sympy.sec() methodgfg = simplify(sec(pi / 3)) print(gfg) Output : 2 SymPy 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 | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n02 Aug, 2019" }, { "code": null, "e": 25645, "s": 25537, "text": "With the help of sympy.sec() method, we are able to find the value of sec theta using sympy.sec() function." }, { "code": null, "e": 25701, "s": 25645, "text": "Syntax : sympy.sec()Return : Return value of sec theta." }, { "code": null, "e": 25810, "s": 25701, "text": "Example #1 :In this example we can see that by using sympy.sec() method, we can find the value of sec theta." }, { "code": "# import sympyfrom sympy import * # Use sympy.sec() methodgfg = simplify(sec(pi / 6)) print(gfg)", "e": 25911, "s": 25810, "text": null }, { "code": null, "e": 25920, "s": 25911, "text": "Output :" }, { "code": null, "e": 25932, "s": 25920, "text": "2*sqrt(3)/3" }, { "code": null, "e": 25945, "s": 25932, "text": "Example #2 :" }, { "code": "# import sympyfrom sympy import * # Use sympy.sec() methodgfg = simplify(sec(pi / 3)) print(gfg)", "e": 26046, "s": 25945, "text": null }, { "code": null, "e": 26055, "s": 26046, "text": "Output :" }, { "code": null, "e": 26057, "s": 26055, "text": "2" }, { "code": null, "e": 26063, "s": 26057, "text": "SymPy" }, { "code": null, "e": 26070, "s": 26063, "text": "Python" }, { "code": null, "e": 26168, "s": 26070, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26200, "s": 26168, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26242, "s": 26200, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26284, "s": 26242, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26340, "s": 26284, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26367, "s": 26340, "text": "Python Classes and Objects" }, { "code": null, "e": 26406, "s": 26367, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26437, "s": 26406, "text": "Python | os.path.join() method" }, { "code": null, "e": 26459, "s": 26437, "text": "Defaultdict in Python" }, { "code": null, "e": 26488, "s": 26459, "text": "Create a directory in Python" } ]
How to Use Select Case Statement in Excel VBA? - GeeksforGeeks
19 Jul, 2021 VBA in Excel stands for Visual Basic for Applications which is Microsoft’s programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. Some helpful links to get more insights about Macros, VBA in Excel : Record Macros in Excel.How to Create a Macro in Excel? Record Macros in Excel. How to Create a Macro in Excel? In this article, we are going to discuss how to use Select Case Statement in Excel VBA. In the Microsoft Excel tabs, select the Developer Tab. Initially, the Developer Tab may not be available. The Developer Tab can be enabled easily by a two-step process : Right-click on any of the existing tabs at the top of the Excel window. Now select Customize the Ribbon from the pop-down menu. In the Excel Options Box, check the box Developer to enable it and click on OK. Now, the Developer Tab is visible. Now click on the Visual Basic option in the Developer tab and make a new module to write the program using the Select Case statement. Developer -> Visual Basic -> Tools -> Macros Now create a Macro and give any suitable name. This will open the Editor window where can write the code. The select case statement is similar to SWITCH-CASE statement in programming languages like C,C++, JAVA, etc. The structure of Select Case in Excel is : Select Case Expression/Condition Case Val_1 Block of statements when Expression matches Val_1 Case Val_2 Block of statements when Expression matches Val_2 Case Val_3 Block of statements when Expression matches Val_3 . . . Case Else Block of code when none of the above conditions match End Select Val_1, Val_2,... are the values. Some important keywords used in Select Case in Excel are as follows : Case Is: It is basically used with numbers. For example Case IS < 70 // Means all numbers less than 70. Case Else: If none of the values of Cases matches with the Expression. It is similar to the default in the SWITCH statement in C/C++. InputBox: To take input from the user. MsgBox: To display output to the user. Example 1 : We want to display the grades of students as per the marks obtained by them in an exam. Consider the data set shown below : Code : Sub Select_Case_Grade() 'Declaring variables to fetch marks and store the grade Dim marks As Integer, Grade As String 'Fetching marks from the Excel cell marks = Range("A2").Value Select Case marks Case Is >= 90 Grade = "S" Case Is >= 80 Grade = "A" Case Is >= 70 Grade = "B" Case Is >= 60 Grade = "C" Case Is >= 50 Grade = "D" Case Is >= 40 result = "E" Case Else Grade = "F" End Select 'Displaying the grade in the Excel cell Range("B2").Value = Grade End Sub Now, change the marks the Grade displayed will be “S”. You can also write the previous code using range of numbers instead of Case Is. Sub Select_Case_Grade() 'Declaring variables to fetch marks and store the grade Dim marks As Integer, Grade As String 'Fetching marks from the Excel cell marks = Range("A2").Value Select Case marks Case 91 To 100 Grade = "S" Case 81 To 90 Grade = "A" Case 71 To 80 Grade = "B" Case 61 To 70 Grade = "C" Case 51 To 60 Grade = "D" Case 40 To 50 result = "E" Case Else Grade = "F" End Select 'Displaying the grade in the Excel cell Range("B2").Value = Grade End Sub Example 2: Consider in a company, employees have to work on a project on the basis of shifts. The company wants to allocate shifts based on odd-even rules and keep age as the deciding criteria. If the age of the employee is odd then he/she has to work in the night shift and if it is even then in the morning shift. Select Case where the user can input the data in a box. Sub Select_Case_Allocate() 'Declaring variables to fetch marks and store the grade Dim Age As Integer 'Asking the user to enter the age Age = InputBox("Enter Your Age:") Select Case (Age Mod 2) = 0 Case True MsgBox "You will work in the morning shift" Case False MsgBox "You will work in the night shift" End Select End Sub Example 3: Let’s create a small calculator which takes two numbers as input and performs addition and multiplication of these numbers. Code : Sub Select_Case_Calculator() 'Declaring variables to fetch marks and store the grade Dim num1 As Integer, mum2 As Integer, operator As String, res As Integer 'Asking the user to enter the numbers and operator to calculate num1 = InputBox("Enter The First Number:") num2 = InputBox("Enter The Second Number:") operator = InputBox("Enter The Operator Name(Sum,Mul):") Select Case operator Case "Sum" res = num1 + num2 MsgBox ("The result is :" & res) Case "Mul" res = num1 * num2 MsgBox ("The result is :" & res) Case Else MsgBox "Please Enter a Valid Operator" End Select End Sub We can modify the above code and use multiple conditions in the case. For example, the user can input the string Sum as “SUM” or “sum” as the Excel dialog box is case-sensitive. Sub Select_Case_Calculator() 'Declaring variables to fetch marks and store the grade Dim num1 As Integer, mum2 As Integer, operator As String, res As Integer 'Asking the user to enter the numbers num1 = InputBox("Enter The First Number:") num2 = InputBox("Enter The Second Number:") operator = InputBox("Enter The Operator Name(Sum,Mul):") Select Case operator Case "Sum", "SUM", "sum", "SUm", "SuM", "suM", "sUm" res = num1 + num2 MsgBox ("The result is :" & res) Case "Mul", "mul", "MUL", "MuL", "muL", "mUl", "MUl" res = num1 * num2 MsgBox ("The result is :" & res) Case Else MsgBox "Please Enter a Valid Operator" End Select End Sub Example 4: Let’s see an example using a nested Select Case. Consider a company that has a policy department-wise regarding the total number of leaves an employee can take in a single year. Now, there are multiple departments and there are female as well as male employees and everyone has different policies for applying for leave. So, a nested Select Case is used to build the problem statement where users can enter the details of department and gender to check the maximum number of days they can take leave in a year. Sub Select_Case_Empleave() 'Declaring variables to fetch Department and gender of employee Dim Department As String, sex As String 'Asking the user to enter the details Department = InputBox("Enter Your Department:") sex = InputBox("Enter Your Gender (Male,Female):") Select Case Department Case "HR" Select Case sex Case "Male" MsgBox ("You can take maximum 10 days leave in an year") Case "Female" MsgBox ("You can take maximum 20 days leave in an year") Case Else MsgBox ("Invalid Gender") End Select Case "IT" Select Case sex Case "Male" MsgBox ("You can take maximum 15 days leave in an year") Case "Female" MsgBox ("You can take maximum 25 days leave in an year") Case Else MsgBox ("Invalid Gender") End Select Case Else 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? Using CHOOSE Function along with VLOOKUP in Excel Macros in Excel Introduction to Excel Spreadsheet How to Extract the Last Word From a Cell in Excel? How to Show Percentages in Stacked Column Chart in Excel? How to Remove Duplicates From Array Using VBA in Excel? How to Sum Values Based on Criteria in Another Column in Excel?
[ { "code": null, "e": 26289, "s": 26261, "text": "\n19 Jul, 2021" }, { "code": null, "e": 26500, "s": 26289, "text": "VBA in Excel stands for Visual Basic for Applications which is Microsoft’s programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. " }, { "code": null, "e": 26569, "s": 26500, "text": "Some helpful links to get more insights about Macros, VBA in Excel :" }, { "code": null, "e": 26624, "s": 26569, "text": "Record Macros in Excel.How to Create a Macro in Excel?" }, { "code": null, "e": 26648, "s": 26624, "text": "Record Macros in Excel." }, { "code": null, "e": 26680, "s": 26648, "text": "How to Create a Macro in Excel?" }, { "code": null, "e": 26768, "s": 26680, "text": "In this article, we are going to discuss how to use Select Case Statement in Excel VBA." }, { "code": null, "e": 26875, "s": 26768, "text": "In the Microsoft Excel tabs, select the Developer Tab. Initially, the Developer Tab may not be available. " }, { "code": null, "e": 26939, "s": 26875, "text": "The Developer Tab can be enabled easily by a two-step process :" }, { "code": null, "e": 27011, "s": 26939, "text": "Right-click on any of the existing tabs at the top of the Excel window." }, { "code": null, "e": 27067, "s": 27011, "text": "Now select Customize the Ribbon from the pop-down menu." }, { "code": null, "e": 27147, "s": 27067, "text": "In the Excel Options Box, check the box Developer to enable it and click on OK." }, { "code": null, "e": 27182, "s": 27147, "text": "Now, the Developer Tab is visible." }, { "code": null, "e": 27316, "s": 27182, "text": "Now click on the Visual Basic option in the Developer tab and make a new module to write the program using the Select Case statement." }, { "code": null, "e": 27362, "s": 27316, "text": "Developer -> Visual Basic -> Tools -> Macros" }, { "code": null, "e": 27409, "s": 27362, "text": "Now create a Macro and give any suitable name." }, { "code": null, "e": 27468, "s": 27409, "text": "This will open the Editor window where can write the code." }, { "code": null, "e": 27621, "s": 27468, "text": "The select case statement is similar to SWITCH-CASE statement in programming languages like C,C++, JAVA, etc. The structure of Select Case in Excel is :" }, { "code": null, "e": 27996, "s": 27621, "text": "Select Case Expression/Condition\n Case Val_1\n Block of statements when Expression matches Val_1\n Case Val_2\n Block of statements when Expression matches Val_2\n Case Val_3\n Block of statements when Expression matches Val_3\n .\n .\n .\n Case Else\n Block of code when none of the above conditions match\nEnd Select\n\nVal_1, Val_2,... are the values." }, { "code": null, "e": 28066, "s": 27996, "text": "Some important keywords used in Select Case in Excel are as follows :" }, { "code": null, "e": 28110, "s": 28066, "text": "Case Is: It is basically used with numbers." }, { "code": null, "e": 28170, "s": 28110, "text": "For example Case IS < 70 // Means all numbers less than 70." }, { "code": null, "e": 28304, "s": 28170, "text": "Case Else: If none of the values of Cases matches with the Expression. It is similar to the default in the SWITCH statement in C/C++." }, { "code": null, "e": 28345, "s": 28304, "text": " InputBox: To take input from the user. " }, { "code": null, "e": 28385, "s": 28345, "text": " MsgBox: To display output to the user." }, { "code": null, "e": 28397, "s": 28385, "text": "Example 1 :" }, { "code": null, "e": 28521, "s": 28397, "text": "We want to display the grades of students as per the marks obtained by them in an exam. Consider the data set shown below :" }, { "code": null, "e": 28528, "s": 28521, "text": "Code :" }, { "code": null, "e": 29074, "s": 28528, "text": "Sub Select_Case_Grade()\n'Declaring variables to fetch marks and store the grade\nDim marks As Integer, Grade As String\n'Fetching marks from the Excel cell\nmarks = Range(\"A2\").Value\nSelect Case marks\n Case Is >= 90\n Grade = \"S\"\n Case Is >= 80\n Grade = \"A\"\n Case Is >= 70\n Grade = \"B\"\n Case Is >= 60\n Grade = \"C\"\n Case Is >= 50\n Grade = \"D\"\n Case Is >= 40\n result = \"E\"\n Case Else\n Grade = \"F\"\nEnd Select\n'Displaying the grade in the Excel cell\nRange(\"B2\").Value = Grade\nEnd Sub" }, { "code": null, "e": 29129, "s": 29074, "text": "Now, change the marks the Grade displayed will be “S”." }, { "code": null, "e": 29210, "s": 29129, "text": "You can also write the previous code using range of numbers instead of Case Is. " }, { "code": null, "e": 29757, "s": 29210, "text": "Sub Select_Case_Grade()\n'Declaring variables to fetch marks and store the grade\nDim marks As Integer, Grade As String\n'Fetching marks from the Excel cell\nmarks = Range(\"A2\").Value\nSelect Case marks\n Case 91 To 100\n Grade = \"S\"\n Case 81 To 90\n Grade = \"A\"\n Case 71 To 80\n Grade = \"B\"\n Case 61 To 70\n Grade = \"C\"\n Case 51 To 60\n Grade = \"D\"\n Case 40 To 50\n result = \"E\"\n Case Else\n Grade = \"F\"\nEnd Select\n'Displaying the grade in the Excel cell\nRange(\"B2\").Value = Grade\nEnd Sub" }, { "code": null, "e": 30073, "s": 29757, "text": "Example 2: Consider in a company, employees have to work on a project on the basis of shifts. The company wants to allocate shifts based on odd-even rules and keep age as the deciding criteria. If the age of the employee is odd then he/she has to work in the night shift and if it is even then in the morning shift." }, { "code": null, "e": 30129, "s": 30073, "text": "Select Case where the user can input the data in a box." }, { "code": null, "e": 30469, "s": 30129, "text": "Sub Select_Case_Allocate()\n'Declaring variables to fetch marks and store the grade\nDim Age As Integer\n'Asking the user to enter the age\nAge = InputBox(\"Enter Your Age:\")\nSelect Case (Age Mod 2) = 0\n Case True\n MsgBox \"You will work in the morning shift\"\n Case False\n MsgBox \"You will work in the night shift\"\nEnd Select\nEnd Sub" }, { "code": null, "e": 30604, "s": 30469, "text": "Example 3: Let’s create a small calculator which takes two numbers as input and performs addition and multiplication of these numbers." }, { "code": null, "e": 30611, "s": 30604, "text": "Code :" }, { "code": null, "e": 31222, "s": 30611, "text": "Sub Select_Case_Calculator()\n'Declaring variables to fetch marks and store the grade\nDim num1 As Integer, mum2 As Integer, operator As String, res As Integer\n'Asking the user to enter the numbers and operator to calculate\nnum1 = InputBox(\"Enter The First Number:\")\nnum2 = InputBox(\"Enter The Second Number:\")\noperator = InputBox(\"Enter The Operator Name(Sum,Mul):\")\nSelect Case operator\n Case \"Sum\"\n res = num1 + num2\n MsgBox (\"The result is :\" & res)\n Case \"Mul\"\n res = num1 * num2\n MsgBox (\"The result is :\" & res)\n Case Else\n MsgBox \"Please Enter a Valid Operator\"\nEnd Select\nEnd Sub" }, { "code": null, "e": 31400, "s": 31222, "text": "We can modify the above code and use multiple conditions in the case. For example, the user can input the string Sum as “SUM” or “sum” as the Excel dialog box is case-sensitive." }, { "code": null, "e": 32069, "s": 31400, "text": "Sub Select_Case_Calculator()\n'Declaring variables to fetch marks and store the grade\nDim num1 As Integer, mum2 As Integer, operator As String, res As Integer\n'Asking the user to enter the numbers\nnum1 = InputBox(\"Enter The First Number:\")\nnum2 = InputBox(\"Enter The Second Number:\")\noperator = InputBox(\"Enter The Operator Name(Sum,Mul):\")\nSelect Case operator\n Case \"Sum\", \"SUM\", \"sum\", \"SUm\", \"SuM\", \"suM\", \"sUm\"\n res = num1 + num2\n MsgBox (\"The result is :\" & res)\n Case \"Mul\", \"mul\", \"MUL\", \"MuL\", \"muL\", \"mUl\", \"MUl\"\n res = num1 * num2\n MsgBox (\"The result is :\" & res)\n Case Else\n MsgBox \"Please Enter a Valid Operator\"\nEnd Select\nEnd Sub" }, { "code": null, "e": 32129, "s": 32069, "text": "Example 4: Let’s see an example using a nested Select Case." }, { "code": null, "e": 32591, "s": 32129, "text": "Consider a company that has a policy department-wise regarding the total number of leaves an employee can take in a single year. Now, there are multiple departments and there are female as well as male employees and everyone has different policies for applying for leave. So, a nested Select Case is used to build the problem statement where users can enter the details of department and gender to check the maximum number of days they can take leave in a year." }, { "code": null, "e": 33438, "s": 32591, "text": "Sub Select_Case_Empleave()\n'Declaring variables to fetch Department and gender of employee\nDim Department As String, sex As String\n'Asking the user to enter the details\nDepartment = InputBox(\"Enter Your Department:\")\nsex = InputBox(\"Enter Your Gender (Male,Female):\")\nSelect Case Department\n Case \"HR\"\n Select Case sex\n Case \"Male\"\n MsgBox (\"You can take maximum 10 days leave in an year\")\n Case \"Female\"\n MsgBox (\"You can take maximum 20 days leave in an year\")\n Case Else\n MsgBox (\"Invalid Gender\")\n End Select\n Case \"IT\"\n Select Case sex\n Case \"Male\"\n MsgBox (\"You can take maximum 15 days leave in an year\")\n Case \"Female\"\n MsgBox (\"You can take maximum 25 days leave in an year\")\n Case Else\n MsgBox (\"Invalid Gender\")\n End Select\nCase Else" }, { "code": null, "e": 33445, "s": 33438, "text": "Picked" }, { "code": null, "e": 33451, "s": 33445, "text": "Excel" }, { "code": null, "e": 33549, "s": 33451, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33577, "s": 33549, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 33632, "s": 33577, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 33673, "s": 33632, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 33723, "s": 33673, "text": "Using CHOOSE Function along with VLOOKUP in Excel" }, { "code": null, "e": 33739, "s": 33723, "text": "Macros in Excel" }, { "code": null, "e": 33773, "s": 33739, "text": "Introduction to Excel Spreadsheet" }, { "code": null, "e": 33824, "s": 33773, "text": "How to Extract the Last Word From a Cell in Excel?" }, { "code": null, "e": 33882, "s": 33824, "text": "How to Show Percentages in Stacked Column Chart in Excel?" }, { "code": null, "e": 33938, "s": 33882, "text": "How to Remove Duplicates From Array Using VBA in Excel?" } ]
Product of Array except itself - GeeksforGeeks
22 Feb, 2022 Given an array arr[] of n integers, construct a Product Array prod[] (of same size) such that prod[i] is equal to the product of all the elements of arr[] except arr[i]. Solve it without division operator in O(n) time. Example : Input: arr[] = {10, 3, 5, 6, 2} Output: prod[] = {180, 600, 360, 300, 900} 3 * 5 * 6 * 2 product of other array elements except 10 is 180 10 * 5 * 6 * 2 product of other array elements except 3 is 600 10 * 3 * 6 * 2 product of other array elements except 5 is 360 10 * 3 * 5 * 2 product of other array elements except 6 is 300 10 * 3 * 6 * 5 product of other array elements except 2 is 900 Input: arr[] = {1, 2, 3, 4, 5} Output: prod[] = {120, 60, 40, 30, 24 } 2 * 3 * 4 * 5 product of other array elements except 1 is 120 1 * 3 * 4 * 5 product of other array elements except 2 is 60 1 * 2 * 4 * 5 product of other array elements except 3 is 40 1 * 2 * 3 * 5 product of other array elements except 4 is 30 1 * 2 * 3 * 4 product of other array elements except 5 is 24 Naive Solution:Approach: Create two extra space, i.e. two extra arrays to store the product of all the array elements from start, up to that index and another array to store the product of all the array elements from the end of the array to that index. To get the product excluding that index, multiply the prefix product up to index i-1 with the suffix product up to index i+1. Algorithm: Create two array prefix and suffix of length n, i.e length of the original array, initialize prefix[0] = 1 and suffix[n-1] = 1 and also another array to store the product.Traverse the array from second index to end.For every index i update prefix[i] as prefix[i] = prefix[i-1] * array[i-1], i.e store the product upto i-1 index from the start of array.Traverse the array from second last index to start.For every index i update suffix[i] as suffix[i] = suffix[i+1] * array[i+1], i.e store the product upto i+1 index from the end of arrayTraverse the array from start to end.For every index i the output will be prefix[i] * suffix[i], the product of the array element except that element. Create two array prefix and suffix of length n, i.e length of the original array, initialize prefix[0] = 1 and suffix[n-1] = 1 and also another array to store the product. Traverse the array from second index to end. For every index i update prefix[i] as prefix[i] = prefix[i-1] * array[i-1], i.e store the product upto i-1 index from the start of array. Traverse the array from second last index to start. For every index i update suffix[i] as suffix[i] = suffix[i+1] * array[i+1], i.e store the product upto i+1 index from the end of array Traverse the array from start to end. For every index i the output will be prefix[i] * suffix[i], the product of the array element except that element. C++ C Java Python3 C# PHP Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; /* Function to print product arrayfor a given array arr[] of size n */void productArray(int arr[], int n){ // Base case if (n == 1) { cout << 0; return; } /* Allocate memory for temporaryarrays left[] and right[] */ int* left = new int[sizeof(int) * n]; int* right = new int[sizeof(int) * n]; /* Allocate memory for the product array */ int* prod = new int[sizeof(int) * n]; int i, j; /* Left most element of leftarray is always 1 */ left[0] = 1; /* Right most element of rightarray is always 1 */ right[n - 1] = 1; /* Construct the left array */ for (i = 1; i < n; i++) left[i] = arr[i - 1] * left[i - 1]; /* Construct the right array */ for (j = n - 2; j >= 0; j--) right[j] = arr[j + 1] * right[j + 1]; /* Construct the product array using left[] and right[] */ for (i = 0; i < n; i++) prod[i] = left[i] * right[i]; /* print the constructed prod array */ for (i = 0; i < n; i++) cout << prod[i] << " "; return;} /* Driver code*/int main(){ int arr[] = { 10, 3, 5, 6, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "The product array is: \n"; productArray(arr, n);} // This is code is contributed by rathbhupendra #include <stdio.h>#include <stdlib.h> /* Function to print product arrayfor a given array arr[] of size n */void productArray(int arr[], int n){ // Base case if (n == 1) { printf("0"); return; } /* Allocate memory for temporaryarrays left[] and right[] */ int* left = (int*)malloc( sizeof(int) * n); int* right = (int*)malloc( sizeof(int) * n); /* Allocate memory for the product array */ int* prod = (int*)malloc( sizeof(int) * n); int i, j; /* Left most element of left arrayis always 1 */ left[0] = 1; /* Right most element of rightarray is always 1 */ right[n - 1] = 1; /* Construct the left array */ for (i = 1; i < n; i++) left[i] = arr[i - 1] * left[i - 1]; /* Construct the right array */ for (j = n - 2; j >= 0; j--) right[j] = arr[j + 1] * right[j + 1]; /* Construct the product array using left[] and right[] */ for (i = 0; i < n; i++) prod[i] = left[i] * right[i]; /* print the constructed prod array */ for (i = 0; i < n; i++) printf("%d ", prod[i]); return;} /* Driver program to test above functions */int main(){ int arr[] = { 10, 3, 5, 6, 2 }; int n = sizeof(arr) / sizeof(arr[0]); printf("The product array is: \n"); productArray(arr, n); getchar();} class ProductArray { /* Function to print product array for a given array arr[] of size n */ void productArray(int arr[], int n) { // Base case if (n == 1) { System.out.print(0); return; } // Initialize memory to all arrays int left[] = new int[n]; int right[] = new int[n]; int prod[] = new int[n]; int i, j; /* Left most element of left arrayis always 1 */ left[0] = 1; /* Right most element of rightarray is always 1 */ right[n - 1] = 1; /* Construct the left array */ for (i = 1; i < n; i++) left[i] = arr[i - 1] * left[i - 1]; /* Construct the right array */ for (j = n - 2; j >= 0; j--) right[j] = arr[j + 1] * right[j + 1]; /* Construct the product array using left[] and right[] */ for (i = 0; i < n; i++) prod[i] = left[i] * right[i]; /* print the constructed prod array */ for (i = 0; i < n; i++) System.out.print(prod[i] + " "); return; } /* Driver program to test the above function */ public static void main(String[] args) { ProductArray pa = new ProductArray(); int arr[] = { 10, 3, 5, 6, 2 }; int n = arr.length; System.out.println("The product array is : "); pa.productArray(arr, n); }} // This code has been contributed by Mayank Jaiswal # Python implementation of the above approach # Function to print product array for a given array# arr[] of size n def productArray(arr, n): # Base case if(n == 1): print(0) return # Allocate memory for temporary arrays left[] and right[] left = [0]*n right = [0]*n # Allocate memory for the product array prod = [0]*n # Left most element of left array is always 1 left[0] = 1 # Right most element of right array is always 1 right[n - 1] = 1 # Construct the left array for i in range(1, n): left[i] = arr[i - 1] * left[i - 1] # Construct the right array for j in range(n-2, -1, -1): right[j] = arr[j + 1] * right[j + 1] # Construct the product array using # left[] and right[] for i in range(n): prod[i] = left[i] * right[i] # print the constructed prod array for i in range(n): print(prod[i], end =' ') # Driver codearr = [10, 3, 5, 6, 2]n = len(arr)print("The product array is:")productArray(arr, n) # This code is contributed by ankush_953 using System; class GFG { /* Function to print product array for a given array arr[] of size n */ static void productArray(int[] arr, int n) { // Base case if (n == 1) { Console.Write(0); return; } // Initialize memory to all arrays int[] left = new int[n]; int[] right = new int[n]; int[] prod = new int[n]; int i, j; /* Left most element of left array is always 1 */ left[0] = 1; /* Right most element of right array is always 1 */ right[n - 1] = 1; /* Construct the left array */ for (i = 1; i < n; i++) left[i] = arr[i - 1] * left[i - 1]; /* Construct the right array */ for (j = n - 2; j >= 0; j--) right[j] = arr[j + 1] * right[j + 1]; /* Construct the product array using left[] and right[] */ for (i = 0; i < n; i++) prod[i] = left[i] * right[i]; /* print the constructed prod array */ for (i = 0; i < n; i++) Console.Write(prod[i] + " "); return; } /* Driver program to test the above function */ public static void Main() { int[] arr = { 10, 3, 5, 6, 2 }; int n = arr.Length; Console.Write("The product array is :\n"); productArray(arr, n); }} // This code is contributed by nitin mittal. <?php// Function to print product// array for a given array// arr[] of size nfunction productArray($arr, $n){ // Base case if($n == 1) { echo "0"; return; } // Initialize memory // to all arrays $left = array(); $right = array(); $prod = array(); $i; $j; // Left most element of // left array is always 1 $left[0] = 1; // Right most element of // right array is always 1 $right[$n - 1] = 1; // Construct the left array for ($i = 1; $i < $n; $i++) $left[$i] = $arr[$i - 1] * $left[$i - 1]; // Construct the right array for ($j = $n - 2; $j >= 0; $j--) $right[$j] = $arr[$j + 1] * $right[$j + 1]; // Construct the product array // using left[] and right[] for ($i = 0; $i < $n; $i++) $prod[$i] = $left[$i] * $right[$i]; // print the constructed prod array for ($i = 0; $i < $n; $i++) echo $prod[$i], " "; return;} // Driver Code$arr = array(10, 3, 5, 6, 2);$n = count($arr);echo "The product array is : \n";productArray($arr, $n); // This code has been contributed by anuj_67.?> <script> /* Function to print product array for a given array arr[] of size n */ function productArray(arr, n) { // Base case if (n == 1) { document.write(0); return; } // Initialize memory to all arrays let left = new Array(n); let right = new Array(n); let prod = new Array(n); let i, j; /* Left most element of left array is always 1 */ left[0] = 1; /* Right most element of right array is always 1 */ right[n - 1] = 1; /* Construct the left array */ for (i = 1; i < n; i++) left[i] = arr[i - 1] * left[i - 1]; /* Construct the right array */ for (j = n - 2; j >= 0; j--) right[j] = arr[j + 1] * right[j + 1]; /* Construct the product array using left[] and right[] */ for (i = 0; i < n; i++) prod[i] = left[i] * right[i]; /* print the constructed prod array */ for (i = 0; i < n; i++) document.write(prod[i] + " "); return; } // Driver code let arr = [ 10, 3, 5, 6, 2 ]; let n = arr.length; document.write("The product array is :" + "</br>"); productArray(arr, n); // This code is contributed by mukesh07.</script> The product array is: 180 600 360 300 900 C++ C Java Python3 C# PHP Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; /* Function to print product arrayfor a given array arr[] of size n */void productArray(int arr[], int n){ // Base case if (n == 1) { cout << 0; return; } /* Allocate memory for temporaryarrays left[] and right[] */ int* left = new int[sizeof(int) * n]; int* right = new int[sizeof(int) * n]; /* Allocate memory for the product array */ int* prod = new int[sizeof(int) * n]; int i, j; /* Left most element of leftarray is always 1 */ left[0] = 1; /* Right most element of rightarray is always 1 */ right[n - 1] = 1; /* Construct the left array */ for (i = 1; i < n; i++) left[i] = arr[i - 1] * left[i - 1]; /* Construct the right array */ for (j = n - 2; j >= 0; j--) right[j] = arr[j + 1] * right[j + 1]; /* Construct the product array using left[] and right[] */ for (i = 0; i < n; i++) prod[i] = left[i] * right[i]; /* print the constructed prod array */ for (i = 0; i < n; i++) cout << prod[i] << " "; return;} /* Driver code*/int main(){ int arr[] = { 10, 3, 5, 6, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "The product array is: \n"; productArray(arr, n);} // This is code is contributed by rathbhupendra #include <stdio.h>#include <stdlib.h> /* Function to print product arrayfor a given array arr[] of size n */void productArray(int arr[], int n){ // Base case if (n == 1) { printf("0"); return; } /* Allocate memory for temporaryarrays left[] and right[] */ int* left = (int*)malloc( sizeof(int) * n); int* right = (int*)malloc( sizeof(int) * n); /* Allocate memory for the product array */ int* prod = (int*)malloc( sizeof(int) * n); int i, j; /* Left most element of left arrayis always 1 */ left[0] = 1; /* Right most element of rightarray is always 1 */ right[n - 1] = 1; /* Construct the left array */ for (i = 1; i < n; i++) left[i] = arr[i - 1] * left[i - 1]; /* Construct the right array */ for (j = n - 2; j >= 0; j--) right[j] = arr[j + 1] * right[j + 1]; /* Construct the product array using left[] and right[] */ for (i = 0; i < n; i++) prod[i] = left[i] * right[i]; /* print the constructed prod array */ for (i = 0; i < n; i++) printf("%d ", prod[i]); return;} /* Driver program to test above functions */int main(){ int arr[] = { 10, 3, 5, 6, 2 }; int n = sizeof(arr) / sizeof(arr[0]); printf("The product array is: \n"); productArray(arr, n); getchar();} class ProductArray { /* Function to print product array for a given array arr[] of size n */ void productArray(int arr[], int n) { // Base case if (n == 1) { System.out.print(0); return; } // Initialize memory to all arrays int left[] = new int[n]; int right[] = new int[n]; int prod[] = new int[n]; int i, j; /* Left most element of left arrayis always 1 */ left[0] = 1; /* Right most element of rightarray is always 1 */ right[n - 1] = 1; /* Construct the left array */ for (i = 1; i < n; i++) left[i] = arr[i - 1] * left[i - 1]; /* Construct the right array */ for (j = n - 2; j >= 0; j--) right[j] = arr[j + 1] * right[j + 1]; /* Construct the product array using left[] and right[] */ for (i = 0; i < n; i++) prod[i] = left[i] * right[i]; /* print the constructed prod array */ for (i = 0; i < n; i++) System.out.print(prod[i] + " "); return; } /* Driver program to test the above function */ public static void main(String[] args) { ProductArray pa = new ProductArray(); int arr[] = { 10, 3, 5, 6, 2 }; int n = arr.length; System.out.println("The product array is : "); pa.productArray(arr, n); }} // This code has been contributed by Mayank Jaiswal # Python implementation of the above approach # Function to print product array for a given array# arr[] of size n def productArray(arr, n): # Base case if(n == 1): print(0) return # Allocate memory for temporary arrays left[] and right[] left = [0]*n right = [0]*n # Allocate memory for the product array prod = [0]*n # Left most element of left array is always 1 left[0] = 1 # Right most element of right array is always 1 right[n - 1] = 1 # Construct the left array for i in range(1, n): left[i] = arr[i - 1] * left[i - 1] # Construct the right array for j in range(n-2, -1, -1): right[j] = arr[j + 1] * right[j + 1] # Construct the product array using # left[] and right[] for i in range(n): prod[i] = left[i] * right[i] # print the constructed prod array for i in range(n): print(prod[i], end =' ') # Driver codearr = [10, 3, 5, 6, 2]n = len(arr)print("The product array is:")productArray(arr, n) # This code is contributed by ankush_953 using System; class GFG { /* Function to print product array for a given array arr[] of size n */ static void productArray(int[] arr, int n) { // Base case if (n == 1) { Console.Write(0); return; } // Initialize memory to all arrays int[] left = new int[n]; int[] right = new int[n]; int[] prod = new int[n]; int i, j; /* Left most element of left array is always 1 */ left[0] = 1; /* Right most element of right array is always 1 */ right[n - 1] = 1; /* Construct the left array */ for (i = 1; i < n; i++) left[i] = arr[i - 1] * left[i - 1]; /* Construct the right array */ for (j = n - 2; j >= 0; j--) right[j] = arr[j + 1] * right[j + 1]; /* Construct the product array using left[] and right[] */ for (i = 0; i < n; i++) prod[i] = left[i] * right[i]; /* print the constructed prod array */ for (i = 0; i < n; i++) Console.Write(prod[i] + " "); return; } /* Driver program to test the above function */ public static void Main() { int[] arr = { 10, 3, 5, 6, 2 }; int n = arr.Length; Console.Write("The product array is :\n"); productArray(arr, n); }} // This code is contributed by nitin mittal. <?php// Function to print product// array for a given array// arr[] of size nfunction productArray($arr, $n){ // Base case if($n == 1) { echo "0"; return; } // Initialize memory // to all arrays $left = array(); $right = array(); $prod = array(); $i; $j; // Left most element of // left array is always 1 $left[0] = 1; // Right most element of // right array is always 1 $right[$n - 1] = 1; // Construct the left array for ($i = 1; $i < $n; $i++) $left[$i] = $arr[$i - 1] * $left[$i - 1]; // Construct the right array for ($j = $n - 2; $j >= 0; $j--) $right[$j] = $arr[$j + 1] * $right[$j + 1]; // Construct the product array // using left[] and right[] for ($i = 0; $i < $n; $i++) $prod[$i] = $left[$i] * $right[$i]; // print the constructed prod array for ($i = 0; $i < $n; $i++) echo $prod[$i], " "; return;} // Driver Code$arr = array(10, 3, 5, 6, 2);$n = count($arr);echo "The product array is : \n";productArray($arr, $n); // This code has been contributed by anuj_67.?> <script> /* Function to print product array for a given array arr[] of size n */ function productArray(arr, n) { // Base case if (n == 1) { document.write(0); return; } // Initialize memory to all arrays let left = new Array(n); let right = new Array(n); let prod = new Array(n); let i, j; /* Left most element of left array is always 1 */ left[0] = 1; /* Right most element of right array is always 1 */ right[n - 1] = 1; /* Construct the left array */ for (i = 1; i < n; i++) left[i] = arr[i - 1] * left[i - 1]; /* Construct the right array */ for (j = n - 2; j >= 0; j--) right[j] = arr[j + 1] * right[j + 1]; /* Construct the product array using left[] and right[] */ for (i = 0; i < n; i++) prod[i] = left[i] * right[i]; /* print the constructed prod array */ for (i = 0; i < n; i++) document.write(prod[i] + " "); return; } // Driver code let arr = [ 10, 3, 5, 6, 2 ]; let n = arr.length; document.write("The product array is :" + "</br>"); productArray(arr, n); // This code is contributed by mukesh07.</script> Complexity Analysis: Time Complexity: O(n). The array needs to be traversed three times, so the time complexity is O(n). Space Complexity: O(n). Two extra arrays and one array to store the output is needed so the space complexity is O(n) Note: The above method can be optimized to work in space complexity O(1). Thanks to Dileep for suggesting the below solution. Efficient solution:Approach: In the previous solution, two extra arrays were created to store the prefix and suffix, in this solution store the prefix and suffix product in the output array (or product array) itself. Thus reducing the space required. Algorithm: Create an array product and initialize its value to 1 and a variable temp = 1.Traverse the array from start to end.For every index i update product[i] as product[i] = temp and temp = temp * array[i], i.e store the product upto i-1 index from the start of array.initialize temp = 1 and traverse the array from last index to start.For every index i update product[i] as product[i] = product[i] * temp and temp = temp * array[i], i.e multiply with the product upto i+1 index from the end of array.Print the product array. Create an array product and initialize its value to 1 and a variable temp = 1. Traverse the array from start to end. For every index i update product[i] as product[i] = temp and temp = temp * array[i], i.e store the product upto i-1 index from the start of array. initialize temp = 1 and traverse the array from last index to start. For every index i update product[i] as product[i] = product[i] * temp and temp = temp * array[i], i.e multiply with the product upto i+1 index from the end of array. Print the product array. C++ Java Python3 C# PHP Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; /* Function to print product arrayfor a given array arr[] of size n */void productArray(int arr[], int n){ // Base case if (n == 1) { cout << 0; return; } int i, temp = 1; /* Allocate memory for the product array */ int* prod = new int[(sizeof(int) * n)]; /* Initialize the product array as 1 */ memset(prod, 1, n); /* In this loop, temp variable contains product of elements on left side excluding arr[i] */ for (i = 0; i < n; i++) { prod[i] = temp; temp *= arr[i]; } /* Initialize temp to 1 for product on right side */ temp = 1; /* In this loop, temp variable contains product of elements on right side excluding arr[i] */ for (i = n - 1; i >= 0; i--) { prod[i] *= temp; temp *= arr[i]; } /* print the constructed prod array */ for (i = 0; i < n; i++) cout << prod[i] << " "; return;} // Driver Codeint main(){ int arr[] = { 10, 3, 5, 6, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "The product array is: \n"; productArray(arr, n);} // This code is contributed by rathbhupendra class ProductArray { void productArray(int arr[], int n) { // Base case if (n == 1) { System.out.print("0"); return; } int i, temp = 1; /* Allocate memory for the product array */ int prod[] = new int[n]; /* Initialize the product array as 1 */ for (int j = 0; j < n; j++) prod[j] = 1; /* In this loop, temp variable contains product of elements on left side excluding arr[i] */ for (i = 0; i < n; i++) { prod[i] = temp; temp *= arr[i]; } /* Initialize temp to 1 for product on right side */ temp = 1; /* In this loop, temp variable contains product of elements on right side excluding arr[i] */ for (i = n - 1; i >= 0; i--) { prod[i] *= temp; temp *= arr[i]; } /* print the constructed prod array */ for (i = 0; i < n; i++) System.out.print(prod[i] + " "); return; } /* Driver program to test above functions */ public static void main(String[] args) { ProductArray pa = new ProductArray(); int arr[] = { 10, 3, 5, 6, 2 }; int n = arr.length; System.out.println("The product array is : "); pa.productArray(arr, n); }} // This code has been contributed by Mayank Jaiswal # Python3 program for A Product Array Puzzledef productArray(arr, n): # Base case if n == 1: print(0) return i, temp = 1, 1 # Allocate memory for the product array prod = [1 for i in range(n)] # Initialize the product array as 1 # In this loop, temp variable contains product of # elements on left side excluding arr[i] for i in range(n): prod[i] = temp temp *= arr[i] # Initialize temp to 1 for product on right side temp = 1 # In this loop, temp variable contains product of # elements on right side excluding arr[i] for i in range(n - 1, -1, -1): prod[i] *= temp temp *= arr[i] # Print the constructed prod array for i in range(n): print(prod[i], end = " ") return # Driver Codearr = [10, 3, 5, 6, 2]n = len(arr)print("The product array is: n")productArray(arr, n) # This code is contributed by mohit kumar using System; class GFG { static void productArray(int[] arr, int n) { // Base case if (n == 1) { Console.Write(0); return; } int i, temp = 1; /* Allocate memory for the product array */ int[] prod = new int[n]; /* Initialize the product array as 1 */ for (int j = 0; j < n; j++) prod[j] = 1; /* In this loop, temp variable contains product of elements on left side excluding arr[i] */ for (i = 0; i < n; i++) { prod[i] = temp; temp *= arr[i]; } /* Initialize temp to 1 for product on right side */ temp = 1; /* In this loop, temp variable contains product of elements on right side excluding arr[i] */ for (i = n - 1; i >= 0; i--) { prod[i] *= temp; temp *= arr[i]; } /* print the constructed prod array */ for (i = 0; i < n; i++) Console.Write(prod[i] + " "); return; } /* Driver program to test above functions */ public static void Main() { int[] arr = { 10, 3, 5, 6, 2 }; int n = arr.Length; Console.WriteLine("The product array is : "); productArray(arr, n); }} // This code is contributed by nitin mittal. <?php// PHP program for// A Product Array Puzzle function productArray($arr, $n) { // Base case if ($n == 1) { echo "0"; return; } $i; $temp = 1; /* Allocate memory for the productarray */ $prod = array(); /* Initialize the product array as 1 */ for( $j = 0; $j < $n; $j++) $prod[$j] = 1; /* In this loop, temp variable contains product of elements on left side excluding arr[i] */ for ($i = 0; $i < $n; $i++) { $prod[$i] = $temp; $temp *= $arr[$i]; } /* Initialize temp to 1 for product on right side */ $temp = 1; /* In this loop, temp variable contains product of elements on right side excluding arr[i] */ for ($i = $n - 1; $i >= 0; $i--) { $prod[$i] *= $temp; $temp *= $arr[$i]; } /* print the constructed prod array */ for ($i = 0; $i < $n; $i++) echo $prod[$i], " "; return; } // Driver Code $arr = array(10, 3, 5, 6, 2); $n = count($arr); echo "The product array is : \n"; productArray($arr, $n); // This code is contributed by anuj_67.?> <script> function productArray(arr , n) { // Base case if (n == 1) { document.write("0"); return; } var i, temp = 1; /* Allocate memory for the product array */ var prod = Array(n).fill(0); /* Initialize the product array as 1 */ for (j = 0; j < n; j++) prod[j] = 1; /* In this loop, temp variable contains product of elements on left side excluding arr[i] */ for (i = 0; i < n; i++) { prod[i] = temp; temp *= arr[i]; } /* Initialize temp to 1 for product on right side */ temp = 1; /* In this loop, temp variable contains product of elements on right side excluding arr[i] */ for (i = n - 1; i >= 0; i--) { prod[i] *= temp; temp *= arr[i]; } /* print the constructed prod array */ for (i = 0; i < n; i++) document.write(prod[i] + " "); return; } /* Driver program to test above functions */ var arr = [ 10, 3, 5, 6, 2 ]; var n = arr.length; document.write("The product array is : "); productArray(arr, n); // This code contributed by Rajput-Ji </script> The product array is: 180 600 360 300 900 Complexity Analysis: Time Complexity: O(n). The original array needs to be traversed only once, so the time complexity is constant. Space Complexity: O(n). Even though the extra arrays are removed, the space complexity remains O(n), as the product array is still needed. Another Approach: Store the product of all the elements is a variable and then iterate the array and add product/current_index_value in a new array. and then return this new array. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <iostream>using namespace std; long* productExceptSelf(int a[], int n){ long prod = 1; long flag = 0; // product of all elements for (int i = 0; i < n; i++) { // counting number of elements // which have value // 0 if (a[i] == 0) flag++; else prod *= a[i]; } // creating a new array of size n long* arr = new long[n]; for (int i = 0; i < n; i++) { // if number of elements in // array with value 0 // is more than 1 than each // value in new array // will be equal to 0 if (flag > 1) { arr[i] = 0; } // if no element having value // 0 than we will // insert product/a[i] in new array else if (flag == 0) arr[i] = (prod / a[i]); // if 1 element of array having // value 0 than all // the elements except that index // value , will be // equal to 0 else if (flag == 1 && a[i] != 0) { arr[i] = 0; } // if(flag == 1 && a[i] == 0) else arr[i] = prod; } return arr;} // Driver Codeint main(){ int n = 5; int array[] = { 10, 3, 5, 6, 2 }; long* ans; ans = productExceptSelf(array, n); for (int i = 0; i < n; i++) { cout << ans[i] << " "; } // cout<<"GFG!"; return 0;} // This code is contributed by RohitOberoi. // Java program for the above approachimport java.io.*;import java.util.*; class Solution { public static long[] productExceptSelf(int a[], int n) { long prod = 1; long flag = 0; // product of all elements for (int i = 0; i < n; i++) { // counting number of elements // which have value // 0 if (a[i] == 0) flag++; else prod *= a[i]; } // creating a new array of size n long arr[] = new long[n]; for (int i = 0; i < n; i++) { // if number of elements in // array with value 0 // is more than 1 than each // value in new array // will be equal to 0 if (flag > 1) { arr[i] = 0; } // if no element having value // 0 than we will // insert product/a[i] in new array else if (flag == 0) arr[i] = (prod / a[i]); // if 1 element of array having // value 0 than all // the elements except that index // value , will be // equal to 0 else if (flag == 1 && a[i] != 0) { arr[i] = 0; } // if(flag == 1 && a[i] == 0) else arr[i] = prod; } return arr; } // Driver Code public static void main(String args[]) throws IOException { int n = 5; int[] array = { 10, 3, 5, 6, 2 }; Solution ob = new Solution(); long[] ans = new long[n]; ans = ob.productExceptSelf(array, n); for (int i = 0; i < n; i++) { System.out.print(ans[i] + " "); } }} // This code is contributed by Kapil Kumar (kapilkumar2001) # Python3 program for the above approachdef productExceptSelf(a, n): prod = 1 flag = 0 for i in range(n): # Counting number of elements # which have value # 0 if (a[i] == 0): flag += 1 else: prod *= a[i] # Creating a new array of size n arr = [0 for i in range(n)] for i in range(n): # If number of elements in # array with value 0 # is more than 1 than each # value in new array # will be equal to 0 if (flag > 1): arr[i] = 0 # If no element having value # 0 than we will # insert product/a[i] in new array elif (flag == 0): arr[i] = (prod // a[i]) # If 1 element of array having # value 0 than all # the elements except that index # value , will be # equal to 0 elif (flag == 1 and a[i] != 0): arr[i] = 0 # If(flag == 1 && a[i] == 0) else: arr[i] = prod return arr # Driver Coden = 5array = [ 10, 3, 5, 6, 2 ]ans = productExceptSelf(array, n) print(*ans) # This code is contributed by rag2127 using System; public class GFG{ public static long[] productExceptSelf(int[] a, int n) { long prod = 1; long flag = 0; // product of all elements for (int i = 0; i < n; i++) { // counting number of elements // which have value // 0 if (a[i] == 0) flag++; else prod *= a[i]; } // creating a new array of size n long[] arr = new long[n]; for (int i = 0; i < n; i++) { // if number of elements in // array with value 0 // is more than 1 than each // value in new array // will be equal to 0 if (flag > 1) { arr[i] = 0; } // if no element having value // 0 than we will // insert product/a[i] in new array else if (flag == 0) arr[i] = (prod / a[i]); // if 1 element of array having // value 0 than all // the elements except that index // value , will be // equal to 0 else if (flag == 1 && a[i] != 0) { arr[i] = 0; } // if(flag == 1 && a[i] == 0) else arr[i] = prod; } return arr; } // Driver Code static public void Main (){ int n = 5; int[] array = { 10, 3, 5, 6, 2 }; long[] ans = new long[n]; ans = productExceptSelf(array, n); for (int i = 0; i < n; i++) { Console.Write(ans[i] + " "); } }} // This code is contributed by avanitrachhadiya2155 <script> // Javascript program for the above approachfunction productExceptSelf(a, n){ let prod = 1; let flag = 0; // Product of all elements for(let i = 0; i < n; i++) { // Counting number of elements // which have value // 0 if (a[i] == 0) flag++; else prod *= a[i]; } // Creating a new array of size n let arr = Array(n).fill(0); for(let i = 0; i < n; i++) { // If number of elements in // array with value 0 // is more than 1 than each // value in new array // will be equal to 0 if (flag > 1) { arr[i] = 0; } // If no element having value // 0 than we will // insert product/a[i] in new array else if (flag == 0) arr[i] = (prod / a[i]); // If 1 element of array having // value 0 than all // the elements except that index // value , will be // equal to 0 else if (flag == 1 && a[i] != 0) { arr[i] = 0; } // If(flag == 1 && a[i] == 0) else arr[i] = prod; } return arr;} // Driver codelet n = 5;let array = [ 10, 3, 5, 6, 2 ];let ans = Array(n).fill(0);ans = productExceptSelf(array, n); for(let i = 0; i < n; i++){ document.write(ans[i] + " ");} // This code is contributed by avijitmondal1998 </script> 180 600 360 300 900 Time Complexity: O(n) Space Complexity: O(1) The original array needs to be traversed only once, so the space complexity is constant. YouTubeGeeksforGeeks508K subscribersA Product Array Puzzle | 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 / 2:37•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=R745JLPox_A" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> ?list=PLqM7alHXFySEQDk2MDfbwEdjd2svVJH9p A product array puzzle | Set 2 (O(1) Space)Related Problem: Construct an Array from XOR of all elements of array except element at same indexPlease write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem. nitin mittal vt_m mohit kumar 29 rathbhupendra ankush_953 aashutoshrathi gp6 andrew1234 byte bx kapilkumar2001 RohitOberoi mukesh07 sweetyty arorakashish0911 Rajput-Ji avijitmondal1998 anikakapoor avanitrachhadiya2155 rag2127 sonu719723 sud31 simmytarika5 Accolite Amazon D-E-Shaw Morgan Stanley Opera Arrays Mathematical Morgan Stanley Accolite Amazon D-E-Shaw Opera Arrays Mathematical 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 Largest Sum Contiguous Subarray Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 42521, "s": 42493, "text": "\n22 Feb, 2022" }, { "code": null, "e": 42740, "s": 42521, "text": "Given an array arr[] of n integers, construct a Product Array prod[] (of same size) such that prod[i] is equal to the product of all the elements of arr[] except arr[i]. Solve it without division operator in O(n) time." }, { "code": null, "e": 42751, "s": 42740, "text": "Example : " }, { "code": null, "e": 43539, "s": 42751, "text": "Input: arr[] = {10, 3, 5, 6, 2}\nOutput: prod[] = {180, 600, 360, 300, 900}\n3 * 5 * 6 * 2 product of other array \nelements except 10 is 180\n10 * 5 * 6 * 2 product of other array \nelements except 3 is 600\n10 * 3 * 6 * 2 product of other array \nelements except 5 is 360\n10 * 3 * 5 * 2 product of other array \nelements except 6 is 300\n10 * 3 * 6 * 5 product of other array \nelements except 2 is 900\n\n\nInput: arr[] = {1, 2, 3, 4, 5}\nOutput: prod[] = {120, 60, 40, 30, 24 }\n2 * 3 * 4 * 5 product of other array \nelements except 1 is 120\n1 * 3 * 4 * 5 product of other array \nelements except 2 is 60\n1 * 2 * 4 * 5 product of other array \nelements except 3 is 40\n1 * 2 * 3 * 5 product of other array \nelements except 4 is 30\n1 * 2 * 3 * 4 product of other array \nelements except 5 is 24" }, { "code": null, "e": 43918, "s": 43539, "text": "Naive Solution:Approach: Create two extra space, i.e. two extra arrays to store the product of all the array elements from start, up to that index and another array to store the product of all the array elements from the end of the array to that index. To get the product excluding that index, multiply the prefix product up to index i-1 with the suffix product up to index i+1." }, { "code": null, "e": 43930, "s": 43918, "text": "Algorithm: " }, { "code": null, "e": 44618, "s": 43930, "text": "Create two array prefix and suffix of length n, i.e length of the original array, initialize prefix[0] = 1 and suffix[n-1] = 1 and also another array to store the product.Traverse the array from second index to end.For every index i update prefix[i] as prefix[i] = prefix[i-1] * array[i-1], i.e store the product upto i-1 index from the start of array.Traverse the array from second last index to start.For every index i update suffix[i] as suffix[i] = suffix[i+1] * array[i+1], i.e store the product upto i+1 index from the end of arrayTraverse the array from start to end.For every index i the output will be prefix[i] * suffix[i], the product of the array element except that element." }, { "code": null, "e": 44790, "s": 44618, "text": "Create two array prefix and suffix of length n, i.e length of the original array, initialize prefix[0] = 1 and suffix[n-1] = 1 and also another array to store the product." }, { "code": null, "e": 44835, "s": 44790, "text": "Traverse the array from second index to end." }, { "code": null, "e": 44973, "s": 44835, "text": "For every index i update prefix[i] as prefix[i] = prefix[i-1] * array[i-1], i.e store the product upto i-1 index from the start of array." }, { "code": null, "e": 45025, "s": 44973, "text": "Traverse the array from second last index to start." }, { "code": null, "e": 45160, "s": 45025, "text": "For every index i update suffix[i] as suffix[i] = suffix[i+1] * array[i+1], i.e store the product upto i+1 index from the end of array" }, { "code": null, "e": 45198, "s": 45160, "text": "Traverse the array from start to end." }, { "code": null, "e": 45312, "s": 45198, "text": "For every index i the output will be prefix[i] * suffix[i], the product of the array element except that element." }, { "code": null, "e": 45316, "s": 45312, "text": "C++" }, { "code": null, "e": 45318, "s": 45316, "text": "C" }, { "code": null, "e": 45323, "s": 45318, "text": "Java" }, { "code": null, "e": 45331, "s": 45323, "text": "Python3" }, { "code": null, "e": 45334, "s": 45331, "text": "C#" }, { "code": null, "e": 45338, "s": 45334, "text": "PHP" }, { "code": null, "e": 45349, "s": 45338, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; /* Function to print product arrayfor a given array arr[] of size n */void productArray(int arr[], int n){ // Base case if (n == 1) { cout << 0; return; } /* Allocate memory for temporaryarrays left[] and right[] */ int* left = new int[sizeof(int) * n]; int* right = new int[sizeof(int) * n]; /* Allocate memory for the product array */ int* prod = new int[sizeof(int) * n]; int i, j; /* Left most element of leftarray is always 1 */ left[0] = 1; /* Right most element of rightarray is always 1 */ right[n - 1] = 1; /* Construct the left array */ for (i = 1; i < n; i++) left[i] = arr[i - 1] * left[i - 1]; /* Construct the right array */ for (j = n - 2; j >= 0; j--) right[j] = arr[j + 1] * right[j + 1]; /* Construct the product array using left[] and right[] */ for (i = 0; i < n; i++) prod[i] = left[i] * right[i]; /* print the constructed prod array */ for (i = 0; i < n; i++) cout << prod[i] << \" \"; return;} /* Driver code*/int main(){ int arr[] = { 10, 3, 5, 6, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"The product array is: \\n\"; productArray(arr, n);} // This is code is contributed by rathbhupendra", "e": 46690, "s": 45349, "text": null }, { "code": "#include <stdio.h>#include <stdlib.h> /* Function to print product arrayfor a given array arr[] of size n */void productArray(int arr[], int n){ // Base case if (n == 1) { printf(\"0\"); return; } /* Allocate memory for temporaryarrays left[] and right[] */ int* left = (int*)malloc( sizeof(int) * n); int* right = (int*)malloc( sizeof(int) * n); /* Allocate memory for the product array */ int* prod = (int*)malloc( sizeof(int) * n); int i, j; /* Left most element of left arrayis always 1 */ left[0] = 1; /* Right most element of rightarray is always 1 */ right[n - 1] = 1; /* Construct the left array */ for (i = 1; i < n; i++) left[i] = arr[i - 1] * left[i - 1]; /* Construct the right array */ for (j = n - 2; j >= 0; j--) right[j] = arr[j + 1] * right[j + 1]; /* Construct the product array using left[] and right[] */ for (i = 0; i < n; i++) prod[i] = left[i] * right[i]; /* print the constructed prod array */ for (i = 0; i < n; i++) printf(\"%d \", prod[i]); return;} /* Driver program to test above functions */int main(){ int arr[] = { 10, 3, 5, 6, 2 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"The product array is: \\n\"); productArray(arr, n); getchar();}", "e": 48017, "s": 46690, "text": null }, { "code": "class ProductArray { /* Function to print product array for a given array arr[] of size n */ void productArray(int arr[], int n) { // Base case if (n == 1) { System.out.print(0); return; } // Initialize memory to all arrays int left[] = new int[n]; int right[] = new int[n]; int prod[] = new int[n]; int i, j; /* Left most element of left arrayis always 1 */ left[0] = 1; /* Right most element of rightarray is always 1 */ right[n - 1] = 1; /* Construct the left array */ for (i = 1; i < n; i++) left[i] = arr[i - 1] * left[i - 1]; /* Construct the right array */ for (j = n - 2; j >= 0; j--) right[j] = arr[j + 1] * right[j + 1]; /* Construct the product array using left[] and right[] */ for (i = 0; i < n; i++) prod[i] = left[i] * right[i]; /* print the constructed prod array */ for (i = 0; i < n; i++) System.out.print(prod[i] + \" \"); return; } /* Driver program to test the above function */ public static void main(String[] args) { ProductArray pa = new ProductArray(); int arr[] = { 10, 3, 5, 6, 2 }; int n = arr.length; System.out.println(\"The product array is : \"); pa.productArray(arr, n); }} // This code has been contributed by Mayank Jaiswal", "e": 49465, "s": 48017, "text": null }, { "code": "# Python implementation of the above approach # Function to print product array for a given array# arr[] of size n def productArray(arr, n): # Base case if(n == 1): print(0) return # Allocate memory for temporary arrays left[] and right[] left = [0]*n right = [0]*n # Allocate memory for the product array prod = [0]*n # Left most element of left array is always 1 left[0] = 1 # Right most element of right array is always 1 right[n - 1] = 1 # Construct the left array for i in range(1, n): left[i] = arr[i - 1] * left[i - 1] # Construct the right array for j in range(n-2, -1, -1): right[j] = arr[j + 1] * right[j + 1] # Construct the product array using # left[] and right[] for i in range(n): prod[i] = left[i] * right[i] # print the constructed prod array for i in range(n): print(prod[i], end =' ') # Driver codearr = [10, 3, 5, 6, 2]n = len(arr)print(\"The product array is:\")productArray(arr, n) # This code is contributed by ankush_953", "e": 50529, "s": 49465, "text": null }, { "code": "using System; class GFG { /* Function to print product array for a given array arr[] of size n */ static void productArray(int[] arr, int n) { // Base case if (n == 1) { Console.Write(0); return; } // Initialize memory to all arrays int[] left = new int[n]; int[] right = new int[n]; int[] prod = new int[n]; int i, j; /* Left most element of left array is always 1 */ left[0] = 1; /* Right most element of right array is always 1 */ right[n - 1] = 1; /* Construct the left array */ for (i = 1; i < n; i++) left[i] = arr[i - 1] * left[i - 1]; /* Construct the right array */ for (j = n - 2; j >= 0; j--) right[j] = arr[j + 1] * right[j + 1]; /* Construct the product array using left[] and right[] */ for (i = 0; i < n; i++) prod[i] = left[i] * right[i]; /* print the constructed prod array */ for (i = 0; i < n; i++) Console.Write(prod[i] + \" \"); return; } /* Driver program to test the above function */ public static void Main() { int[] arr = { 10, 3, 5, 6, 2 }; int n = arr.Length; Console.Write(\"The product array is :\\n\"); productArray(arr, n); }} // This code is contributed by nitin mittal.", "e": 51929, "s": 50529, "text": null }, { "code": "<?php// Function to print product// array for a given array// arr[] of size nfunction productArray($arr, $n){ // Base case if($n == 1) { echo \"0\"; return; } // Initialize memory // to all arrays $left = array(); $right = array(); $prod = array(); $i; $j; // Left most element of // left array is always 1 $left[0] = 1; // Right most element of // right array is always 1 $right[$n - 1] = 1; // Construct the left array for ($i = 1; $i < $n; $i++) $left[$i] = $arr[$i - 1] * $left[$i - 1]; // Construct the right array for ($j = $n - 2; $j >= 0; $j--) $right[$j] = $arr[$j + 1] * $right[$j + 1]; // Construct the product array // using left[] and right[] for ($i = 0; $i < $n; $i++) $prod[$i] = $left[$i] * $right[$i]; // print the constructed prod array for ($i = 0; $i < $n; $i++) echo $prod[$i], \" \"; return;} // Driver Code$arr = array(10, 3, 5, 6, 2);$n = count($arr);echo \"The product array is : \\n\";productArray($arr, $n); // This code has been contributed by anuj_67.?>", "e": 53089, "s": 51929, "text": null }, { "code": "<script> /* Function to print product array for a given array arr[] of size n */ function productArray(arr, n) { // Base case if (n == 1) { document.write(0); return; } // Initialize memory to all arrays let left = new Array(n); let right = new Array(n); let prod = new Array(n); let i, j; /* Left most element of left array is always 1 */ left[0] = 1; /* Right most element of right array is always 1 */ right[n - 1] = 1; /* Construct the left array */ for (i = 1; i < n; i++) left[i] = arr[i - 1] * left[i - 1]; /* Construct the right array */ for (j = n - 2; j >= 0; j--) right[j] = arr[j + 1] * right[j + 1]; /* Construct the product array using left[] and right[] */ for (i = 0; i < n; i++) prod[i] = left[i] * right[i]; /* print the constructed prod array */ for (i = 0; i < n; i++) document.write(prod[i] + \" \"); return; } // Driver code let arr = [ 10, 3, 5, 6, 2 ]; let n = arr.length; document.write(\"The product array is :\" + \"</br>\"); productArray(arr, n); // This code is contributed by mukesh07.</script>", "e": 54405, "s": 53089, "text": null }, { "code": null, "e": 54452, "s": 54408, "text": "The product array is: \n180 600 360 300 900 " }, { "code": null, "e": 54458, "s": 54454, "text": "C++" }, { "code": null, "e": 54460, "s": 54458, "text": "C" }, { "code": null, "e": 54465, "s": 54460, "text": "Java" }, { "code": null, "e": 54473, "s": 54465, "text": "Python3" }, { "code": null, "e": 54476, "s": 54473, "text": "C#" }, { "code": null, "e": 54480, "s": 54476, "text": "PHP" }, { "code": null, "e": 54491, "s": 54480, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; /* Function to print product arrayfor a given array arr[] of size n */void productArray(int arr[], int n){ // Base case if (n == 1) { cout << 0; return; } /* Allocate memory for temporaryarrays left[] and right[] */ int* left = new int[sizeof(int) * n]; int* right = new int[sizeof(int) * n]; /* Allocate memory for the product array */ int* prod = new int[sizeof(int) * n]; int i, j; /* Left most element of leftarray is always 1 */ left[0] = 1; /* Right most element of rightarray is always 1 */ right[n - 1] = 1; /* Construct the left array */ for (i = 1; i < n; i++) left[i] = arr[i - 1] * left[i - 1]; /* Construct the right array */ for (j = n - 2; j >= 0; j--) right[j] = arr[j + 1] * right[j + 1]; /* Construct the product array using left[] and right[] */ for (i = 0; i < n; i++) prod[i] = left[i] * right[i]; /* print the constructed prod array */ for (i = 0; i < n; i++) cout << prod[i] << \" \"; return;} /* Driver code*/int main(){ int arr[] = { 10, 3, 5, 6, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"The product array is: \\n\"; productArray(arr, n);} // This is code is contributed by rathbhupendra", "e": 55832, "s": 54491, "text": null }, { "code": "#include <stdio.h>#include <stdlib.h> /* Function to print product arrayfor a given array arr[] of size n */void productArray(int arr[], int n){ // Base case if (n == 1) { printf(\"0\"); return; } /* Allocate memory for temporaryarrays left[] and right[] */ int* left = (int*)malloc( sizeof(int) * n); int* right = (int*)malloc( sizeof(int) * n); /* Allocate memory for the product array */ int* prod = (int*)malloc( sizeof(int) * n); int i, j; /* Left most element of left arrayis always 1 */ left[0] = 1; /* Right most element of rightarray is always 1 */ right[n - 1] = 1; /* Construct the left array */ for (i = 1; i < n; i++) left[i] = arr[i - 1] * left[i - 1]; /* Construct the right array */ for (j = n - 2; j >= 0; j--) right[j] = arr[j + 1] * right[j + 1]; /* Construct the product array using left[] and right[] */ for (i = 0; i < n; i++) prod[i] = left[i] * right[i]; /* print the constructed prod array */ for (i = 0; i < n; i++) printf(\"%d \", prod[i]); return;} /* Driver program to test above functions */int main(){ int arr[] = { 10, 3, 5, 6, 2 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"The product array is: \\n\"); productArray(arr, n); getchar();}", "e": 57159, "s": 55832, "text": null }, { "code": "class ProductArray { /* Function to print product array for a given array arr[] of size n */ void productArray(int arr[], int n) { // Base case if (n == 1) { System.out.print(0); return; } // Initialize memory to all arrays int left[] = new int[n]; int right[] = new int[n]; int prod[] = new int[n]; int i, j; /* Left most element of left arrayis always 1 */ left[0] = 1; /* Right most element of rightarray is always 1 */ right[n - 1] = 1; /* Construct the left array */ for (i = 1; i < n; i++) left[i] = arr[i - 1] * left[i - 1]; /* Construct the right array */ for (j = n - 2; j >= 0; j--) right[j] = arr[j + 1] * right[j + 1]; /* Construct the product array using left[] and right[] */ for (i = 0; i < n; i++) prod[i] = left[i] * right[i]; /* print the constructed prod array */ for (i = 0; i < n; i++) System.out.print(prod[i] + \" \"); return; } /* Driver program to test the above function */ public static void main(String[] args) { ProductArray pa = new ProductArray(); int arr[] = { 10, 3, 5, 6, 2 }; int n = arr.length; System.out.println(\"The product array is : \"); pa.productArray(arr, n); }} // This code has been contributed by Mayank Jaiswal", "e": 58607, "s": 57159, "text": null }, { "code": "# Python implementation of the above approach # Function to print product array for a given array# arr[] of size n def productArray(arr, n): # Base case if(n == 1): print(0) return # Allocate memory for temporary arrays left[] and right[] left = [0]*n right = [0]*n # Allocate memory for the product array prod = [0]*n # Left most element of left array is always 1 left[0] = 1 # Right most element of right array is always 1 right[n - 1] = 1 # Construct the left array for i in range(1, n): left[i] = arr[i - 1] * left[i - 1] # Construct the right array for j in range(n-2, -1, -1): right[j] = arr[j + 1] * right[j + 1] # Construct the product array using # left[] and right[] for i in range(n): prod[i] = left[i] * right[i] # print the constructed prod array for i in range(n): print(prod[i], end =' ') # Driver codearr = [10, 3, 5, 6, 2]n = len(arr)print(\"The product array is:\")productArray(arr, n) # This code is contributed by ankush_953", "e": 59671, "s": 58607, "text": null }, { "code": "using System; class GFG { /* Function to print product array for a given array arr[] of size n */ static void productArray(int[] arr, int n) { // Base case if (n == 1) { Console.Write(0); return; } // Initialize memory to all arrays int[] left = new int[n]; int[] right = new int[n]; int[] prod = new int[n]; int i, j; /* Left most element of left array is always 1 */ left[0] = 1; /* Right most element of right array is always 1 */ right[n - 1] = 1; /* Construct the left array */ for (i = 1; i < n; i++) left[i] = arr[i - 1] * left[i - 1]; /* Construct the right array */ for (j = n - 2; j >= 0; j--) right[j] = arr[j + 1] * right[j + 1]; /* Construct the product array using left[] and right[] */ for (i = 0; i < n; i++) prod[i] = left[i] * right[i]; /* print the constructed prod array */ for (i = 0; i < n; i++) Console.Write(prod[i] + \" \"); return; } /* Driver program to test the above function */ public static void Main() { int[] arr = { 10, 3, 5, 6, 2 }; int n = arr.Length; Console.Write(\"The product array is :\\n\"); productArray(arr, n); }} // This code is contributed by nitin mittal.", "e": 61071, "s": 59671, "text": null }, { "code": "<?php// Function to print product// array for a given array// arr[] of size nfunction productArray($arr, $n){ // Base case if($n == 1) { echo \"0\"; return; } // Initialize memory // to all arrays $left = array(); $right = array(); $prod = array(); $i; $j; // Left most element of // left array is always 1 $left[0] = 1; // Right most element of // right array is always 1 $right[$n - 1] = 1; // Construct the left array for ($i = 1; $i < $n; $i++) $left[$i] = $arr[$i - 1] * $left[$i - 1]; // Construct the right array for ($j = $n - 2; $j >= 0; $j--) $right[$j] = $arr[$j + 1] * $right[$j + 1]; // Construct the product array // using left[] and right[] for ($i = 0; $i < $n; $i++) $prod[$i] = $left[$i] * $right[$i]; // print the constructed prod array for ($i = 0; $i < $n; $i++) echo $prod[$i], \" \"; return;} // Driver Code$arr = array(10, 3, 5, 6, 2);$n = count($arr);echo \"The product array is : \\n\";productArray($arr, $n); // This code has been contributed by anuj_67.?>", "e": 62231, "s": 61071, "text": null }, { "code": "<script> /* Function to print product array for a given array arr[] of size n */ function productArray(arr, n) { // Base case if (n == 1) { document.write(0); return; } // Initialize memory to all arrays let left = new Array(n); let right = new Array(n); let prod = new Array(n); let i, j; /* Left most element of left array is always 1 */ left[0] = 1; /* Right most element of right array is always 1 */ right[n - 1] = 1; /* Construct the left array */ for (i = 1; i < n; i++) left[i] = arr[i - 1] * left[i - 1]; /* Construct the right array */ for (j = n - 2; j >= 0; j--) right[j] = arr[j + 1] * right[j + 1]; /* Construct the product array using left[] and right[] */ for (i = 0; i < n; i++) prod[i] = left[i] * right[i]; /* print the constructed prod array */ for (i = 0; i < n; i++) document.write(prod[i] + \" \"); return; } // Driver code let arr = [ 10, 3, 5, 6, 2 ]; let n = arr.length; document.write(\"The product array is :\" + \"</br>\"); productArray(arr, n); // This code is contributed by mukesh07.</script>", "e": 63547, "s": 62231, "text": null }, { "code": null, "e": 63569, "s": 63547, "text": "Complexity Analysis: " }, { "code": null, "e": 63669, "s": 63569, "text": "Time Complexity: O(n). The array needs to be traversed three times, so the time complexity is O(n)." }, { "code": null, "e": 63786, "s": 63669, "text": "Space Complexity: O(n). Two extra arrays and one array to store the output is needed so the space complexity is O(n)" }, { "code": null, "e": 63912, "s": 63786, "text": "Note: The above method can be optimized to work in space complexity O(1). Thanks to Dileep for suggesting the below solution." }, { "code": null, "e": 64163, "s": 63912, "text": "Efficient solution:Approach: In the previous solution, two extra arrays were created to store the prefix and suffix, in this solution store the prefix and suffix product in the output array (or product array) itself. Thus reducing the space required." }, { "code": null, "e": 64175, "s": 64163, "text": "Algorithm: " }, { "code": null, "e": 64694, "s": 64175, "text": "Create an array product and initialize its value to 1 and a variable temp = 1.Traverse the array from start to end.For every index i update product[i] as product[i] = temp and temp = temp * array[i], i.e store the product upto i-1 index from the start of array.initialize temp = 1 and traverse the array from last index to start.For every index i update product[i] as product[i] = product[i] * temp and temp = temp * array[i], i.e multiply with the product upto i+1 index from the end of array.Print the product array." }, { "code": null, "e": 64773, "s": 64694, "text": "Create an array product and initialize its value to 1 and a variable temp = 1." }, { "code": null, "e": 64811, "s": 64773, "text": "Traverse the array from start to end." }, { "code": null, "e": 64958, "s": 64811, "text": "For every index i update product[i] as product[i] = temp and temp = temp * array[i], i.e store the product upto i-1 index from the start of array." }, { "code": null, "e": 65027, "s": 64958, "text": "initialize temp = 1 and traverse the array from last index to start." }, { "code": null, "e": 65193, "s": 65027, "text": "For every index i update product[i] as product[i] = product[i] * temp and temp = temp * array[i], i.e multiply with the product upto i+1 index from the end of array." }, { "code": null, "e": 65218, "s": 65193, "text": "Print the product array." }, { "code": null, "e": 65222, "s": 65218, "text": "C++" }, { "code": null, "e": 65227, "s": 65222, "text": "Java" }, { "code": null, "e": 65235, "s": 65227, "text": "Python3" }, { "code": null, "e": 65238, "s": 65235, "text": "C#" }, { "code": null, "e": 65242, "s": 65238, "text": "PHP" }, { "code": null, "e": 65253, "s": 65242, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; /* Function to print product arrayfor a given array arr[] of size n */void productArray(int arr[], int n){ // Base case if (n == 1) { cout << 0; return; } int i, temp = 1; /* Allocate memory for the product array */ int* prod = new int[(sizeof(int) * n)]; /* Initialize the product array as 1 */ memset(prod, 1, n); /* In this loop, temp variable contains product of elements on left side excluding arr[i] */ for (i = 0; i < n; i++) { prod[i] = temp; temp *= arr[i]; } /* Initialize temp to 1 for product on right side */ temp = 1; /* In this loop, temp variable contains product of elements on right side excluding arr[i] */ for (i = n - 1; i >= 0; i--) { prod[i] *= temp; temp *= arr[i]; } /* print the constructed prod array */ for (i = 0; i < n; i++) cout << prod[i] << \" \"; return;} // Driver Codeint main(){ int arr[] = { 10, 3, 5, 6, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"The product array is: \\n\"; productArray(arr, n);} // This code is contributed by rathbhupendra", "e": 66467, "s": 65253, "text": null }, { "code": "class ProductArray { void productArray(int arr[], int n) { // Base case if (n == 1) { System.out.print(\"0\"); return; } int i, temp = 1; /* Allocate memory for the product array */ int prod[] = new int[n]; /* Initialize the product array as 1 */ for (int j = 0; j < n; j++) prod[j] = 1; /* In this loop, temp variable contains product of elements on left side excluding arr[i] */ for (i = 0; i < n; i++) { prod[i] = temp; temp *= arr[i]; } /* Initialize temp to 1 for product on right side */ temp = 1; /* In this loop, temp variable contains product of elements on right side excluding arr[i] */ for (i = n - 1; i >= 0; i--) { prod[i] *= temp; temp *= arr[i]; } /* print the constructed prod array */ for (i = 0; i < n; i++) System.out.print(prod[i] + \" \"); return; } /* Driver program to test above functions */ public static void main(String[] args) { ProductArray pa = new ProductArray(); int arr[] = { 10, 3, 5, 6, 2 }; int n = arr.length; System.out.println(\"The product array is : \"); pa.productArray(arr, n); }} // This code has been contributed by Mayank Jaiswal", "e": 67845, "s": 66467, "text": null }, { "code": "# Python3 program for A Product Array Puzzledef productArray(arr, n): # Base case if n == 1: print(0) return i, temp = 1, 1 # Allocate memory for the product array prod = [1 for i in range(n)] # Initialize the product array as 1 # In this loop, temp variable contains product of # elements on left side excluding arr[i] for i in range(n): prod[i] = temp temp *= arr[i] # Initialize temp to 1 for product on right side temp = 1 # In this loop, temp variable contains product of # elements on right side excluding arr[i] for i in range(n - 1, -1, -1): prod[i] *= temp temp *= arr[i] # Print the constructed prod array for i in range(n): print(prod[i], end = \" \") return # Driver Codearr = [10, 3, 5, 6, 2]n = len(arr)print(\"The product array is: n\")productArray(arr, n) # This code is contributed by mohit kumar", "e": 68764, "s": 67845, "text": null }, { "code": "using System; class GFG { static void productArray(int[] arr, int n) { // Base case if (n == 1) { Console.Write(0); return; } int i, temp = 1; /* Allocate memory for the product array */ int[] prod = new int[n]; /* Initialize the product array as 1 */ for (int j = 0; j < n; j++) prod[j] = 1; /* In this loop, temp variable contains product of elements on left side excluding arr[i] */ for (i = 0; i < n; i++) { prod[i] = temp; temp *= arr[i]; } /* Initialize temp to 1 for product on right side */ temp = 1; /* In this loop, temp variable contains product of elements on right side excluding arr[i] */ for (i = n - 1; i >= 0; i--) { prod[i] *= temp; temp *= arr[i]; } /* print the constructed prod array */ for (i = 0; i < n; i++) Console.Write(prod[i] + \" \"); return; } /* Driver program to test above functions */ public static void Main() { int[] arr = { 10, 3, 5, 6, 2 }; int n = arr.Length; Console.WriteLine(\"The product array is : \"); productArray(arr, n); }} // This code is contributed by nitin mittal.", "e": 70100, "s": 68764, "text": null }, { "code": "<?php// PHP program for// A Product Array Puzzle function productArray($arr, $n) { // Base case if ($n == 1) { echo \"0\"; return; } $i; $temp = 1; /* Allocate memory for the productarray */ $prod = array(); /* Initialize the product array as 1 */ for( $j = 0; $j < $n; $j++) $prod[$j] = 1; /* In this loop, temp variable contains product of elements on left side excluding arr[i] */ for ($i = 0; $i < $n; $i++) { $prod[$i] = $temp; $temp *= $arr[$i]; } /* Initialize temp to 1 for product on right side */ $temp = 1; /* In this loop, temp variable contains product of elements on right side excluding arr[i] */ for ($i = $n - 1; $i >= 0; $i--) { $prod[$i] *= $temp; $temp *= $arr[$i]; } /* print the constructed prod array */ for ($i = 0; $i < $n; $i++) echo $prod[$i], \" \"; return; } // Driver Code $arr = array(10, 3, 5, 6, 2); $n = count($arr); echo \"The product array is : \\n\"; productArray($arr, $n); // This code is contributed by anuj_67.?>", "e": 71481, "s": 70100, "text": null }, { "code": "<script> function productArray(arr , n) { // Base case if (n == 1) { document.write(\"0\"); return; } var i, temp = 1; /* Allocate memory for the product array */ var prod = Array(n).fill(0); /* Initialize the product array as 1 */ for (j = 0; j < n; j++) prod[j] = 1; /* In this loop, temp variable contains product of elements on left side excluding arr[i] */ for (i = 0; i < n; i++) { prod[i] = temp; temp *= arr[i]; } /* Initialize temp to 1 for product on right side */ temp = 1; /* In this loop, temp variable contains product of elements on right side excluding arr[i] */ for (i = n - 1; i >= 0; i--) { prod[i] *= temp; temp *= arr[i]; } /* print the constructed prod array */ for (i = 0; i < n; i++) document.write(prod[i] + \" \"); return; } /* Driver program to test above functions */ var arr = [ 10, 3, 5, 6, 2 ]; var n = arr.length; document.write(\"The product array is : \"); productArray(arr, n); // This code contributed by Rajput-Ji </script>", "e": 72793, "s": 71481, "text": null }, { "code": null, "e": 72837, "s": 72793, "text": "The product array is: \n180 600 360 300 900 " }, { "code": null, "e": 72859, "s": 72837, "text": "Complexity Analysis: " }, { "code": null, "e": 72970, "s": 72859, "text": "Time Complexity: O(n). The original array needs to be traversed only once, so the time complexity is constant." }, { "code": null, "e": 73109, "s": 72970, "text": "Space Complexity: O(n). Even though the extra arrays are removed, the space complexity remains O(n), as the product array is still needed." }, { "code": null, "e": 73127, "s": 73109, "text": "Another Approach:" }, { "code": null, "e": 73290, "s": 73127, "text": "Store the product of all the elements is a variable and then iterate the array and add product/current_index_value in a new array. and then return this new array." }, { "code": null, "e": 73341, "s": 73290, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 73345, "s": 73341, "text": "C++" }, { "code": null, "e": 73350, "s": 73345, "text": "Java" }, { "code": null, "e": 73358, "s": 73350, "text": "Python3" }, { "code": null, "e": 73361, "s": 73358, "text": "C#" }, { "code": null, "e": 73372, "s": 73361, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <iostream>using namespace std; long* productExceptSelf(int a[], int n){ long prod = 1; long flag = 0; // product of all elements for (int i = 0; i < n; i++) { // counting number of elements // which have value // 0 if (a[i] == 0) flag++; else prod *= a[i]; } // creating a new array of size n long* arr = new long[n]; for (int i = 0; i < n; i++) { // if number of elements in // array with value 0 // is more than 1 than each // value in new array // will be equal to 0 if (flag > 1) { arr[i] = 0; } // if no element having value // 0 than we will // insert product/a[i] in new array else if (flag == 0) arr[i] = (prod / a[i]); // if 1 element of array having // value 0 than all // the elements except that index // value , will be // equal to 0 else if (flag == 1 && a[i] != 0) { arr[i] = 0; } // if(flag == 1 && a[i] == 0) else arr[i] = prod; } return arr;} // Driver Codeint main(){ int n = 5; int array[] = { 10, 3, 5, 6, 2 }; long* ans; ans = productExceptSelf(array, n); for (int i = 0; i < n; i++) { cout << ans[i] << \" \"; } // cout<<\"GFG!\"; return 0;} // This code is contributed by RohitOberoi.", "e": 74835, "s": 73372, "text": null }, { "code": "// Java program for the above approachimport java.io.*;import java.util.*; class Solution { public static long[] productExceptSelf(int a[], int n) { long prod = 1; long flag = 0; // product of all elements for (int i = 0; i < n; i++) { // counting number of elements // which have value // 0 if (a[i] == 0) flag++; else prod *= a[i]; } // creating a new array of size n long arr[] = new long[n]; for (int i = 0; i < n; i++) { // if number of elements in // array with value 0 // is more than 1 than each // value in new array // will be equal to 0 if (flag > 1) { arr[i] = 0; } // if no element having value // 0 than we will // insert product/a[i] in new array else if (flag == 0) arr[i] = (prod / a[i]); // if 1 element of array having // value 0 than all // the elements except that index // value , will be // equal to 0 else if (flag == 1 && a[i] != 0) { arr[i] = 0; } // if(flag == 1 && a[i] == 0) else arr[i] = prod; } return arr; } // Driver Code public static void main(String args[]) throws IOException { int n = 5; int[] array = { 10, 3, 5, 6, 2 }; Solution ob = new Solution(); long[] ans = new long[n]; ans = ob.productExceptSelf(array, n); for (int i = 0; i < n; i++) { System.out.print(ans[i] + \" \"); } }} // This code is contributed by Kapil Kumar (kapilkumar2001)", "e": 76650, "s": 74835, "text": null }, { "code": "# Python3 program for the above approachdef productExceptSelf(a, n): prod = 1 flag = 0 for i in range(n): # Counting number of elements # which have value # 0 if (a[i] == 0): flag += 1 else: prod *= a[i] # Creating a new array of size n arr = [0 for i in range(n)] for i in range(n): # If number of elements in # array with value 0 # is more than 1 than each # value in new array # will be equal to 0 if (flag > 1): arr[i] = 0 # If no element having value # 0 than we will # insert product/a[i] in new array elif (flag == 0): arr[i] = (prod // a[i]) # If 1 element of array having # value 0 than all # the elements except that index # value , will be # equal to 0 elif (flag == 1 and a[i] != 0): arr[i] = 0 # If(flag == 1 && a[i] == 0) else: arr[i] = prod return arr # Driver Coden = 5array = [ 10, 3, 5, 6, 2 ]ans = productExceptSelf(array, n) print(*ans) # This code is contributed by rag2127", "e": 77872, "s": 76650, "text": null }, { "code": "using System; public class GFG{ public static long[] productExceptSelf(int[] a, int n) { long prod = 1; long flag = 0; // product of all elements for (int i = 0; i < n; i++) { // counting number of elements // which have value // 0 if (a[i] == 0) flag++; else prod *= a[i]; } // creating a new array of size n long[] arr = new long[n]; for (int i = 0; i < n; i++) { // if number of elements in // array with value 0 // is more than 1 than each // value in new array // will be equal to 0 if (flag > 1) { arr[i] = 0; } // if no element having value // 0 than we will // insert product/a[i] in new array else if (flag == 0) arr[i] = (prod / a[i]); // if 1 element of array having // value 0 than all // the elements except that index // value , will be // equal to 0 else if (flag == 1 && a[i] != 0) { arr[i] = 0; } // if(flag == 1 && a[i] == 0) else arr[i] = prod; } return arr; } // Driver Code static public void Main (){ int n = 5; int[] array = { 10, 3, 5, 6, 2 }; long[] ans = new long[n]; ans = productExceptSelf(array, n); for (int i = 0; i < n; i++) { Console.Write(ans[i] + \" \"); } }} // This code is contributed by avanitrachhadiya2155", "e": 79580, "s": 77872, "text": null }, { "code": "<script> // Javascript program for the above approachfunction productExceptSelf(a, n){ let prod = 1; let flag = 0; // Product of all elements for(let i = 0; i < n; i++) { // Counting number of elements // which have value // 0 if (a[i] == 0) flag++; else prod *= a[i]; } // Creating a new array of size n let arr = Array(n).fill(0); for(let i = 0; i < n; i++) { // If number of elements in // array with value 0 // is more than 1 than each // value in new array // will be equal to 0 if (flag > 1) { arr[i] = 0; } // If no element having value // 0 than we will // insert product/a[i] in new array else if (flag == 0) arr[i] = (prod / a[i]); // If 1 element of array having // value 0 than all // the elements except that index // value , will be // equal to 0 else if (flag == 1 && a[i] != 0) { arr[i] = 0; } // If(flag == 1 && a[i] == 0) else arr[i] = prod; } return arr;} // Driver codelet n = 5;let array = [ 10, 3, 5, 6, 2 ];let ans = Array(n).fill(0);ans = productExceptSelf(array, n); for(let i = 0; i < n; i++){ document.write(ans[i] + \" \");} // This code is contributed by avijitmondal1998 </script>", "e": 81019, "s": 79580, "text": null }, { "code": null, "e": 81040, "s": 81019, "text": "180 600 360 300 900 " }, { "code": null, "e": 81062, "s": 81040, "text": "Time Complexity: O(n)" }, { "code": null, "e": 81085, "s": 81062, "text": "Space Complexity: O(1)" }, { "code": null, "e": 81174, "s": 81085, "text": "The original array needs to be traversed only once, so the space complexity is constant." }, { "code": null, "e": 81995, "s": 81174, "text": "YouTubeGeeksforGeeks508K subscribersA Product Array Puzzle | 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 / 2:37•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=R745JLPox_A\" 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": 82295, "s": 81995, "text": "?list=PLqM7alHXFySEQDk2MDfbwEdjd2svVJH9p A product array puzzle | Set 2 (O(1) Space)Related Problem: Construct an Array from XOR of all elements of array except element at same indexPlease write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem." }, { "code": null, "e": 82308, "s": 82295, "text": "nitin mittal" }, { "code": null, "e": 82313, "s": 82308, "text": "vt_m" }, { "code": null, "e": 82328, "s": 82313, "text": "mohit kumar 29" }, { "code": null, "e": 82342, "s": 82328, "text": "rathbhupendra" }, { "code": null, "e": 82353, "s": 82342, "text": "ankush_953" }, { "code": null, "e": 82368, "s": 82353, "text": "aashutoshrathi" }, { "code": null, "e": 82372, "s": 82368, "text": "gp6" }, { "code": null, "e": 82383, "s": 82372, "text": "andrew1234" }, { "code": null, "e": 82391, "s": 82383, "text": "byte bx" }, { "code": null, "e": 82406, "s": 82391, "text": "kapilkumar2001" }, { "code": null, "e": 82418, "s": 82406, "text": "RohitOberoi" }, { "code": null, "e": 82427, "s": 82418, "text": "mukesh07" }, { "code": null, "e": 82436, "s": 82427, "text": "sweetyty" }, { "code": null, "e": 82453, "s": 82436, "text": "arorakashish0911" }, { "code": null, "e": 82463, "s": 82453, "text": "Rajput-Ji" }, { "code": null, "e": 82480, "s": 82463, "text": "avijitmondal1998" }, { "code": null, "e": 82492, "s": 82480, "text": "anikakapoor" }, { "code": null, "e": 82513, "s": 82492, "text": "avanitrachhadiya2155" }, { "code": null, "e": 82521, "s": 82513, "text": "rag2127" }, { "code": null, "e": 82532, "s": 82521, "text": "sonu719723" }, { "code": null, "e": 82538, "s": 82532, "text": "sud31" }, { "code": null, "e": 82551, "s": 82538, "text": "simmytarika5" }, { "code": null, "e": 82560, "s": 82551, "text": "Accolite" }, { "code": null, "e": 82567, "s": 82560, "text": "Amazon" }, { "code": null, "e": 82576, "s": 82567, "text": "D-E-Shaw" }, { "code": null, "e": 82591, "s": 82576, "text": "Morgan Stanley" }, { "code": null, "e": 82597, "s": 82591, "text": "Opera" }, { "code": null, "e": 82604, "s": 82597, "text": "Arrays" }, { "code": null, "e": 82617, "s": 82604, "text": "Mathematical" }, { "code": null, "e": 82632, "s": 82617, "text": "Morgan Stanley" }, { "code": null, "e": 82641, "s": 82632, "text": "Accolite" }, { "code": null, "e": 82648, "s": 82641, "text": "Amazon" }, { "code": null, "e": 82657, "s": 82648, "text": "D-E-Shaw" }, { "code": null, "e": 82663, "s": 82657, "text": "Opera" }, { "code": null, "e": 82670, "s": 82663, "text": "Arrays" }, { "code": null, "e": 82683, "s": 82670, "text": "Mathematical" }, { "code": null, "e": 82781, "s": 82683, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 82796, "s": 82781, "text": "Arrays in Java" }, { "code": null, "e": 82812, "s": 82796, "text": "Arrays in C/C++" }, { "code": null, "e": 82858, "s": 82812, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 82885, "s": 82858, "text": "Program for array rotation" }, { "code": null, "e": 82917, "s": 82885, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 82947, "s": 82917, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 83007, "s": 82947, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 83022, "s": 83007, "text": "C++ Data Types" }, { "code": null, "e": 83065, "s": 83022, "text": "Set in C++ Standard Template Library (STL)" } ]
Array of Linked Lists in C/C++ - GeeksforGeeks
11 Oct, 2021 An array in C/C++ or be it in any programming language is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in C/C++ can store derived data types such as structures, pointers, etc. Given below is the picture representation of an array. A linked list is a linear data structure consisting of nodes where each node contains a reference to the next node. To create a link list we need a pointer that points to the first node of the list. Approach: To create an array of linked lists below are the main requirements: An array of pointers. For keeping the track of the above-created array of pointers then another pointer is needed that points to the first pointer of the array. This pointer is called pointer to pointer. Below is the pictorial representation of the array of linked lists: Below is the C++ program to implement the array of linked list: C++ // C++ program to illustrate the array// of Linked Lists#include <iostream>using namespace std; // Structure of Linked Listsstruct info { int data; info* next;}; // Driver Codeint main(){ int size = 10; // Pointer To Pointer Array info** head; // Array of pointers to info struct // of size head = new info*[size]; // Initialize pointer array to NULL for (int i = 0; i < size; ++i) { *(head + i) = NULL; } // Traverse the pointer array for (int i = 0; i < size; ++i) { // To track last node of the list info* prev = NULL; // Randomly taking 4 nodes in each // linked list int s = 4; while (s--) { // Create a new node info* n = new info; // Input the random data n->data = i * s; n->next = NULL; // If the node is first if (*(head + i) == NULL) { *(head + i) = n; } else { prev->next = n; } prev = n; } } // Print the array of linked list for (int i = 0; i < size; ++i) { info* temp = *(head + i); // Linked list number cout << i << "-->\t"; // Print the Linked List while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } cout << '\n'; } return 0;} 0--> 0 0 0 0 1--> 3 2 1 0 2--> 6 4 2 0 3--> 9 6 3 0 4--> 12 8 4 0 5--> 15 10 5 0 6--> 18 12 6 0 7--> 21 14 7 0 8--> 24 16 8 0 9--> 27 18 9 0 Linked Lists Arrays C Programs C++ Programs Linked List Linked List Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Count pairs with given sum Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Strings in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File Header files in C/C++ and its uses Basics of File Handling in C
[ { "code": null, "e": 26065, "s": 26037, "text": "\n11 Oct, 2021" }, { "code": null, "e": 26540, "s": 26065, "text": "An array in C/C++ or be it in any programming language is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in C/C++ can store derived data types such as structures, pointers, etc. Given below is the picture representation of an array." }, { "code": null, "e": 26739, "s": 26540, "text": "A linked list is a linear data structure consisting of nodes where each node contains a reference to the next node. To create a link list we need a pointer that points to the first node of the list." }, { "code": null, "e": 26817, "s": 26739, "text": "Approach: To create an array of linked lists below are the main requirements:" }, { "code": null, "e": 26839, "s": 26817, "text": "An array of pointers." }, { "code": null, "e": 27021, "s": 26839, "text": "For keeping the track of the above-created array of pointers then another pointer is needed that points to the first pointer of the array. This pointer is called pointer to pointer." }, { "code": null, "e": 27089, "s": 27021, "text": "Below is the pictorial representation of the array of linked lists:" }, { "code": null, "e": 27153, "s": 27089, "text": "Below is the C++ program to implement the array of linked list:" }, { "code": null, "e": 27157, "s": 27153, "text": "C++" }, { "code": "// C++ program to illustrate the array// of Linked Lists#include <iostream>using namespace std; // Structure of Linked Listsstruct info { int data; info* next;}; // Driver Codeint main(){ int size = 10; // Pointer To Pointer Array info** head; // Array of pointers to info struct // of size head = new info*[size]; // Initialize pointer array to NULL for (int i = 0; i < size; ++i) { *(head + i) = NULL; } // Traverse the pointer array for (int i = 0; i < size; ++i) { // To track last node of the list info* prev = NULL; // Randomly taking 4 nodes in each // linked list int s = 4; while (s--) { // Create a new node info* n = new info; // Input the random data n->data = i * s; n->next = NULL; // If the node is first if (*(head + i) == NULL) { *(head + i) = n; } else { prev->next = n; } prev = n; } } // Print the array of linked list for (int i = 0; i < size; ++i) { info* temp = *(head + i); // Linked list number cout << i << \"-->\\t\"; // Print the Linked List while (temp != NULL) { cout << temp->data << \" \"; temp = temp->next; } cout << '\\n'; } return 0;}", "e": 28586, "s": 27157, "text": null }, { "code": null, "e": 28767, "s": 28586, "text": "0--> 0 0 0 0 \n1--> 3 2 1 0 \n2--> 6 4 2 0 \n3--> 9 6 3 0 \n4--> 12 8 4 0 \n5--> 15 10 5 0 \n6--> 18 12 6 0 \n7--> 21 14 7 0 \n8--> 24 16 8 0 \n9--> 27 18 9 0\n" }, { "code": null, "e": 28780, "s": 28767, "text": "Linked Lists" }, { "code": null, "e": 28787, "s": 28780, "text": "Arrays" }, { "code": null, "e": 28798, "s": 28787, "text": "C Programs" }, { "code": null, "e": 28811, "s": 28798, "text": "C++ Programs" }, { "code": null, "e": 28823, "s": 28811, "text": "Linked List" }, { "code": null, "e": 28835, "s": 28823, "text": "Linked List" }, { "code": null, "e": 28842, "s": 28835, "text": "Arrays" }, { "code": null, "e": 28940, "s": 28842, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28971, "s": 28940, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 28998, "s": 28971, "text": "Count pairs with given sum" }, { "code": null, "e": 29023, "s": 28998, "text": "Window Sliding Technique" }, { "code": null, "e": 29061, "s": 29023, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 29082, "s": 29061, "text": "Next Greater Element" }, { "code": null, "e": 29095, "s": 29082, "text": "Strings in C" }, { "code": null, "e": 29136, "s": 29095, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 29177, "s": 29136, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 29212, "s": 29177, "text": "Header files in C/C++ and its uses" } ]
Bitmap Indexing in DBMS - GeeksforGeeks
11 Apr, 2022 Bitmap Indexing is a special type of database indexing that uses bitmaps. This technique is used for huge databases, when column is of low cardinality and these columns are most frequently used in the query. Need of Bitmap Indexing – The need of Bitmap Indexing will be clear through the below given example : For example, Let us say that a company holds an employee table with entries like EmpNo, EmpName, Job, New_Emp and salary. Let us assume that the employees are hired once in the year, therefore the table will be updated very less and will remain static most of the time. But the columns will be frequently used in queries to retrieve data like : No. of female employees in the company etc. In this case we need a file organization method which should be fast enough to give quick results. But any of the traditional file organization method is not that fast, therefore we switch to a better method of storing and retrieving data known as Bitmap Indexing. How Bitmap Indexing is done – In the above example of table employee, we can see that the column New_Emp has only two values Yes and No based upon the fact that the employee is new to the company or not. Similarly let us assume that the Job of the Employees is divided into 4 categories only i.e Manager, Analyst, Clerk and Salesman. Such columns are called columns with low cardinality. Even though these columns have less unique values, they can be queried very often. Bit: Bit is a basic unit of information used in computing that can have only one of two values either 0 or 1 . The two values of a binary digit can also be interpreted as logical values true/false or yes/no. In Bitmap Indexing these bits are used to represent the unique values in those low cardinality columns. This technique of storing the low cardinality rows in form of bits are called bitmap indices. Continuing the Employee example, Given below is the Employee table : If New_Emp is the data to be indexed, the content of the bitmap index is shown as four( As we have four rows in the above table) columns under the heading Bitmap Indices. Here Bitmap Index “Yes” has value 1001 because row 1 and row four has value “Yes” in column New_Emp. In this case there are two such bitmaps, one for “New_Emp” Yes and one for “New_Emp” NO. It is easy to see that each bit in bitmap indices shows that whether a particular row refer to a person who is New to the company or not. The above scenario is the simplest form of Bitmap Indexing. Most columns will have more distinct values. For example the column Job here will have only 4 unique values (As mentioned earlier). Variations on the bitmap index can effectively index this data as well. For Job column the bitmap Indexing is shown below: Now Suppose, If we want to find out the details for the Employee who is not new in the company and is a sales person then we will run the query: SELECT * FROM Employee WHERE New_Emp = "No" and Job = "Salesperson"; For this query the DBMS will search the bitmap index of both the columns and perform logical AND operation on those bits and find out the actual result: Here the result 0100 represents that the second column has to be retrieved as a result. Bitmap Indexing in SQL – The syntax for creating bitmap index in sql is given below: CREATE BITMAP INDEX Index_Name ON Table_Name (Column_Name); For the above example of employee table, the bitmap index on column New_Emp will be created as follows: CREATE BITMAP INDEX index_New_Emp ON Employee (New_Emp); Advantages – Efficiency in terms of insertion deletion and updation. Faster retrieval of records Disadvantages – Only suitable for large tables Bitmap Indexing is time consuming TapanMeena ruhelaa48 Sukeesh DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions CTE in SQL Data Preprocessing in Data Mining Difference between SQL and NoSQL Difference between DDL and DML in DBMS SQL | Views SQL | GROUP BY Difference between DELETE, DROP and TRUNCATE Indexing in Databases | Set 1 Third Normal Form (3NF)
[ { "code": null, "e": 25659, "s": 25631, "text": "\n11 Apr, 2022" }, { "code": null, "e": 25868, "s": 25659, "text": "Bitmap Indexing is a special type of database indexing that uses bitmaps. This technique is used for huge databases, when column is of low cardinality and these columns are most frequently used in the query. " }, { "code": null, "e": 26625, "s": 25868, "text": "Need of Bitmap Indexing – The need of Bitmap Indexing will be clear through the below given example : For example, Let us say that a company holds an employee table with entries like EmpNo, EmpName, Job, New_Emp and salary. Let us assume that the employees are hired once in the year, therefore the table will be updated very less and will remain static most of the time. But the columns will be frequently used in queries to retrieve data like : No. of female employees in the company etc. In this case we need a file organization method which should be fast enough to give quick results. But any of the traditional file organization method is not that fast, therefore we switch to a better method of storing and retrieving data known as Bitmap Indexing. " }, { "code": null, "e": 27097, "s": 26625, "text": "How Bitmap Indexing is done – In the above example of table employee, we can see that the column New_Emp has only two values Yes and No based upon the fact that the employee is new to the company or not. Similarly let us assume that the Job of the Employees is divided into 4 categories only i.e Manager, Analyst, Clerk and Salesman. Such columns are called columns with low cardinality. Even though these columns have less unique values, they can be queried very often. " }, { "code": null, "e": 27306, "s": 27097, "text": "Bit: Bit is a basic unit of information used in computing that can have only one of two values either 0 or 1 . The two values of a binary digit can also be interpreted as logical values true/false or yes/no. " }, { "code": null, "e": 27575, "s": 27306, "text": "In Bitmap Indexing these bits are used to represent the unique values in those low cardinality columns. This technique of storing the low cardinality rows in form of bits are called bitmap indices. Continuing the Employee example, Given below is the Employee table : " }, { "code": null, "e": 27848, "s": 27575, "text": "If New_Emp is the data to be indexed, the content of the bitmap index is shown as four( As we have four rows in the above table) columns under the heading Bitmap Indices. Here Bitmap Index “Yes” has value 1001 because row 1 and row four has value “Yes” in column New_Emp. " }, { "code": null, "e": 28076, "s": 27848, "text": "In this case there are two such bitmaps, one for “New_Emp” Yes and one for “New_Emp” NO. It is easy to see that each bit in bitmap indices shows that whether a particular row refer to a person who is New to the company or not. " }, { "code": null, "e": 28393, "s": 28076, "text": "The above scenario is the simplest form of Bitmap Indexing. Most columns will have more distinct values. For example the column Job here will have only 4 unique values (As mentioned earlier). Variations on the bitmap index can effectively index this data as well. For Job column the bitmap Indexing is shown below: " }, { "code": null, "e": 28540, "s": 28393, "text": "Now Suppose, If we want to find out the details for the Employee who is not new in the company and is a sales person then we will run the query: " }, { "code": null, "e": 28632, "s": 28540, "text": " SELECT * \n FROM Employee \n WHERE New_Emp = \"No\" and Job = \"Salesperson\";" }, { "code": null, "e": 28786, "s": 28632, "text": "For this query the DBMS will search the bitmap index of both the columns and perform logical AND operation on those bits and find out the actual result: " }, { "code": null, "e": 28875, "s": 28786, "text": "Here the result 0100 represents that the second column has to be retrieved as a result. " }, { "code": null, "e": 28961, "s": 28875, "text": "Bitmap Indexing in SQL – The syntax for creating bitmap index in sql is given below: " }, { "code": null, "e": 29030, "s": 28961, "text": "CREATE BITMAP INDEX Index_Name\n ON Table_Name (Column_Name);" }, { "code": null, "e": 29136, "s": 29030, "text": "For the above example of employee table, the bitmap index on column New_Emp will be created as follows: " }, { "code": null, "e": 29201, "s": 29136, "text": "CREATE BITMAP INDEX index_New_Emp\n ON Employee (New_Emp);" }, { "code": null, "e": 29216, "s": 29201, "text": "Advantages – " }, { "code": null, "e": 29272, "s": 29216, "text": "Efficiency in terms of insertion deletion and updation." }, { "code": null, "e": 29300, "s": 29272, "text": "Faster retrieval of records" }, { "code": null, "e": 29317, "s": 29300, "text": "Disadvantages – " }, { "code": null, "e": 29348, "s": 29317, "text": "Only suitable for large tables" }, { "code": null, "e": 29382, "s": 29348, "text": "Bitmap Indexing is time consuming" }, { "code": null, "e": 29395, "s": 29384, "text": "TapanMeena" }, { "code": null, "e": 29405, "s": 29395, "text": "ruhelaa48" }, { "code": null, "e": 29413, "s": 29405, "text": "Sukeesh" }, { "code": null, "e": 29418, "s": 29413, "text": "DBMS" }, { "code": null, "e": 29423, "s": 29418, "text": "DBMS" }, { "code": null, "e": 29521, "s": 29423, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29545, "s": 29521, "text": "SQL Interview Questions" }, { "code": null, "e": 29556, "s": 29545, "text": "CTE in SQL" }, { "code": null, "e": 29590, "s": 29556, "text": "Data Preprocessing in Data Mining" }, { "code": null, "e": 29623, "s": 29590, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 29662, "s": 29623, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 29674, "s": 29662, "text": "SQL | Views" }, { "code": null, "e": 29689, "s": 29674, "text": "SQL | GROUP BY" }, { "code": null, "e": 29734, "s": 29689, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 29764, "s": 29734, "text": "Indexing in Databases | Set 1" } ]
SVG font-size Attribute - GeeksforGeeks
31 Mar, 2022 The font-size attribute refers to the size of the font from baseline when multiple lines of text are set solid in a multiline layout environment. Syntax: font-size="size" Attribute Values: length: Length at which we want to set the size. percentage: Percentage at which we want to set the size. We will use the font size attribute for setting the size of font. Example 1 <!DOCTYPE html><html> <body> <svg viewBox="0 0 600 100" xmlns="http://www.w3.org/2000/svg"> <text x="10" y="50" font-size="smaller"> smaller </text> <text x="10" y="30" font-size="2em"> larger </text> </svg></body> </html> Output: Example 2: <!DOCTYPE html><html> <body> <svg viewBox="0 0 600 100" xmlns="http://www.w3.org/2000/svg"> <text x="10" y="50" font-size="60%"> smaller </text> <text x="10" y="30" font-size="240%"> larger </text> </svg></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-SVG SVG-Attribute HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property 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 ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 29899, "s": 29871, "text": "\n31 Mar, 2022" }, { "code": null, "e": 30045, "s": 29899, "text": "The font-size attribute refers to the size of the font from baseline when multiple lines of text are set solid in a multiline layout environment." }, { "code": null, "e": 30053, "s": 30045, "text": "Syntax:" }, { "code": null, "e": 30070, "s": 30053, "text": "font-size=\"size\"" }, { "code": null, "e": 30088, "s": 30070, "text": "Attribute Values:" }, { "code": null, "e": 30137, "s": 30088, "text": "length: Length at which we want to set the size." }, { "code": null, "e": 30194, "s": 30137, "text": "percentage: Percentage at which we want to set the size." }, { "code": null, "e": 30260, "s": 30194, "text": "We will use the font size attribute for setting the size of font." }, { "code": null, "e": 30271, "s": 30260, "text": "Example 1 " }, { "code": "<!DOCTYPE html><html> <body> <svg viewBox=\"0 0 600 100\" xmlns=\"http://www.w3.org/2000/svg\"> <text x=\"10\" y=\"50\" font-size=\"smaller\"> smaller </text> <text x=\"10\" y=\"30\" font-size=\"2em\"> larger </text> </svg></body> </html>", "e": 30604, "s": 30271, "text": null }, { "code": null, "e": 30612, "s": 30604, "text": "Output:" }, { "code": null, "e": 30624, "s": 30612, "text": "Example 2: " }, { "code": "<!DOCTYPE html><html> <body> <svg viewBox=\"0 0 600 100\" xmlns=\"http://www.w3.org/2000/svg\"> <text x=\"10\" y=\"50\" font-size=\"60%\"> smaller </text> <text x=\"10\" y=\"30\" font-size=\"240%\"> larger </text> </svg></body> </html>", "e": 30954, "s": 30624, "text": null }, { "code": null, "e": 30962, "s": 30954, "text": "Output:" }, { "code": null, "e": 31099, "s": 30962, "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": 31108, "s": 31099, "text": "HTML-SVG" }, { "code": null, "e": 31122, "s": 31108, "text": "SVG-Attribute" }, { "code": null, "e": 31127, "s": 31122, "text": "HTML" }, { "code": null, "e": 31144, "s": 31127, "text": "Web Technologies" }, { "code": null, "e": 31149, "s": 31144, "text": "HTML" }, { "code": null, "e": 31247, "s": 31149, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31309, "s": 31247, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31359, "s": 31309, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 31407, "s": 31359, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 31467, "s": 31407, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 31520, "s": 31467, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 31560, "s": 31520, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31593, "s": 31560, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31638, "s": 31593, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31681, "s": 31638, "text": "How to fetch data from an API in ReactJS ?" } ]
Minimize the sum of roots of a given polynomial - GeeksforGeeks
03 Jun, 2021 Given an array whose elements represent the coefficients of a polynomial of degree n, if the polynomial has a degree n then the array will have n+1 elements (one extra for the constant of a polynomial). Swap some elements of the array and print the resulting array such that the sum of the roots of the given polynomial is as minimum as possible irrespective of the nature of the roots.Note that: except the first element of the array elements can be 0 also and the degree of the polynomial is always greater than 1. Examples: Input : -4 1 6 -3 -2 -1 Output : 1 6 -4 -3 -2 -1 Here, the array is -4, 1, 6, -3, -2, -1 i.e the polynomial is -4.x^5 + 1.x^4 + 6.x^3 - 3.x^2 - 2.x^1 - 1 minimum sum = -6 Input : -9 0 9 Output :-9 0 9 Here polynomial is -9.x^2 + 0.x^1 + 9 minimum sum = 0 Solution : Let us recall the fact about the sum of the roots of a polynomial if a polynomial p(x) = a.x^n + b.x^n-1 + c.x^n-2 + ... + k, then the sum of roots of a polynomial is given by -b/a. Please see Vieta’s formulas for details.We have to minimize -b/a i.e to maximize b/a i.e maximize b and minimize a. So if somehow we are able to maximize b and minimize a, we will swap the values of the coefficients and copy the rest of the array as it is. There will be four cases : Case #1: when the number of positive coefficients and the number of negative coefficients both are greater than or equal to 2 In this case, we will find a maximum and minimum from positive elements and from negative elements also and we will check -(maxPos)/(minPos) is smaller or -( abs(maxNeg) )/ ( abs(minNeg) ) is smaller and print the answer after swapping accordingly.Case #2: when the number of positive coefficients is greater than equal to 2 but the number of negative coefficients is less than 2 In this case, we will consider the case of the maximum of positive and minimum of positive elements only. Because if we picked up one from positive elements and the other from negative elements the result of -b/a will be a positive value which is not minimum. (as we require a large negative value) Case #3: when the number of negative coefficients is greater than equal to 2 but the number of positive coefficients is less than 2 In this case, we will consider the case of the maximum of negative and minimum of negative elements only. Because if we picked up one from positive elements and the other from negative elements the result of -b/a will be a positive value which is not minimum. (as we require a large negative value)Case #4: When both the counts are less than or equal to 1 Observe carefully, You cannot swap elements in this case. C++ Java Python3 C# Javascript // C++ program to find minimum sum of roots of a// given polynomial#include <bits/stdc++.h>using namespace std; void getMinimumSum(int arr[], int n){ // resultant vector vector<int> res; // a vector that store indices of the positive // elements vector<int> pos; // a vector that store indices of the negative // elements vector<int> neg; for (int i = 0; i < n; i++) { if (arr[i] > 0) pos.push_back(i); else if (arr[i] < 0) neg.push_back(i); } // Case - 1: if (pos.size() >= 2 && neg.size() >= 2) { int posMax = INT_MIN, posMaxIdx = -1; int posMin = INT_MAX, posMinIdx = -1; int negMax = INT_MIN, negMaxIdx = -1; int negMin = INT_MAX, negMinIdx = -1; for (int i = 0; i < pos.size(); i++) { if (arr[pos[i]] > posMax) { posMaxIdx = pos[i]; posMax = arr[posMaxIdx]; } } for (int i = 0; i < pos.size(); i++) { if (arr[pos[i]] < posMin && pos[i] != posMaxIdx) { posMinIdx = pos[i]; posMin = arr[posMinIdx]; } } for (int i = 0; i < neg.size(); i++) { if (abs(arr[neg[i]]) > negMax) { negMaxIdx = neg[i]; negMax = abs(arr[negMaxIdx]); } } for (int i = 0; i < neg.size(); i++) { if (abs(arr[neg[i]]) < negMin && neg[i] != negMaxIdx) { negMinIdx = neg[i]; negMin = abs(arr[negMinIdx]); } } double posVal = -1.0 * (double)posMax / (double)posMin; double negVal = -1.0 * (double)negMax / (double)negMin; if (posVal < negVal) { res.push_back(arr[posMinIdx]); res.push_back(arr[posMaxIdx]); for (int i = 0; i < n; i++) { if (i != posMinIdx && i != posMaxIdx) { res.push_back(arr[i]); } } } else { res.push_back(arr[negMinIdx]); res.push_back(arr[negMaxIdx]); for (int i = 0; i < n; i++) { if (i != negMinIdx && i != negMaxIdx) { res.push_back(arr[i]); } } } for (int i = 0; i < res.size(); i++) { cout << res[i] << " "; } cout << "\n"; } // Case - 2: else if (pos.size() >= 2) { int posMax = INT_MIN, posMaxIdx = -1; int posMin = INT_MAX, posMinIdx = -1; for (int i = 0; i < pos.size(); i++) { if (arr[pos[i]] > posMax) { posMaxIdx = pos[i]; posMax = arr[posMaxIdx]; } } for (int i = 0; i < pos.size(); i++) { if (arr[pos[i]] < posMin && pos[i] != posMaxIdx) { posMinIdx = pos[i]; posMin = arr[posMinIdx]; } } res.push_back(arr[posMinIdx]); res.push_back(arr[posMaxIdx]); for (int i = 0; i < n; i++) { if (i != posMinIdx && i != posMaxIdx) { res.push_back(arr[i]); } } for (int i = 0; i < res.size(); i++) { cout << res[i] << " "; } cout << "\n"; } // Case - 3: else if (neg.size() >= 2) { int negMax = INT_MIN, negMaxIdx = -1; int negMin = INT_MAX, negMinIdx = -1; for (int i = 0; i < neg.size(); i++) { if (abs(arr[neg[i]]) > negMax) { negMaxIdx = neg[i]; negMax = abs(arr[negMaxIdx]); } } for (int i = 0; i < neg.size(); i++) { if (abs(arr[neg[i]]) < negMin && neg[i] != negMaxIdx) { negMinIdx = neg[i]; negMin = abs(arr[negMinIdx]); } } res.push_back(arr[negMinIdx]); res.push_back(arr[negMaxIdx]); for (int i = 0; i < n; i++) if (i != negMinIdx && i != negMaxIdx) res.push_back(arr[i]); for (int i = 0; i < res.size(); i++) cout << res[i] << " "; cout << "\n"; } // Case - 4: else { cout << "No swap required\n"; }} int main(){ int arr[] = { -4, 1, 6, -3, -2, -1 }; int n = sizeof(arr) / sizeof(arr[0]); getMinimumSum(arr, n); return 0;} // Java program to find minimum sum of roots of a// given polynomialimport java.io.*;import java.util.*; class GFG{ static void getMinimumSum(int arr[], int n) { // resultant vector ArrayList<Integer> res = new ArrayList<Integer>(); // a vector that store indices of the positive // elements ArrayList<Integer> pos = new ArrayList<Integer>(); // a vector that store indices of the negative // elements ArrayList<Integer> neg = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { if (arr[i] > 0) pos.add(i); else if (arr[i] < 0) neg.add(i); } // Case - 1: if (pos.size() >= 2 && neg.size() >= 2) { int posMax = Integer.MIN_VALUE, posMaxIdx = -1; int posMin = Integer.MAX_VALUE, posMinIdx = -1; int negMax = Integer.MIN_VALUE, negMaxIdx = -1; int negMin = Integer.MAX_VALUE, negMinIdx = -1; for (int i = 0; i < pos.size(); i++) { if (arr[pos.get(i)] > posMax) { posMaxIdx = pos.get(i); posMax = arr[posMaxIdx]; } } for (int i = 0; i < pos.size(); i++) { if (arr[pos.get(i)] < posMin && pos.get(i) != posMaxIdx) { posMinIdx = pos.get(i); posMin = arr[posMinIdx]; } } for (int i = 0; i < neg.size(); i++) { if (Math.abs(arr[neg.get(i)]) > negMax) { negMaxIdx = neg.get(i); negMax = Math.abs(arr[negMaxIdx]); } } for (int i = 0; i < neg.size(); i++) { if (Math.abs(arr[neg.get(i)]) < negMin && neg.get(i) != negMaxIdx) { negMinIdx = neg.get(i); negMin = Math.abs(arr[negMinIdx]); } } double posVal = -1.0 * (double)posMax / (double)posMin; double negVal = -1.0 * (double)negMax / (double)negMin; if (posVal < negVal) { res.add(arr[posMinIdx]); res.add(arr[posMaxIdx]); for (int i = 0; i < n; i++) { if (i != posMinIdx && i != posMaxIdx) { res.add(arr[i]); } } } else { res.add(arr[negMinIdx]); res.add(arr[negMaxIdx]); for (int i = 0; i < n; i++) { if (i != negMinIdx && i != negMaxIdx) { res.add(arr[i]); } } } for (int i = 0; i < res.size(); i++) { System.out.print(res.get(i) + " "); } System.out.println(); } // Case - 2: else if (pos.size() >= 2) { int posMax = Integer.MIN_VALUE, posMaxIdx = -1; int posMin = Integer.MAX_VALUE, posMinIdx = -1; for (int i = 0; i < pos.size(); i++) { if (arr[pos.get(i)] > posMax) { posMaxIdx = pos.get(i); posMax = arr[posMaxIdx]; } } for (int i = 0; i < pos.size(); i++) { if (arr[pos.get(i)] < posMin && pos.get(i) != posMaxIdx) { posMinIdx = pos.get(i); posMin = arr[posMinIdx]; } } res.add(arr[posMinIdx]); res.add(arr[posMaxIdx]); for (int i = 0; i < n; i++) { if (i != posMinIdx && i != posMaxIdx) { res.add(arr[i]); } } for (int i = 0; i < res.size(); i++) { System.out.print(res.get(i)+" "); } System.out.println(); } // Case - 3: else if (neg.size() >= 2) { int negMax = Integer.MIN_VALUE, negMaxIdx = -1; int negMin = Integer.MAX_VALUE, negMinIdx = -1; for (int i = 0; i < neg.size(); i++) { if (Math.abs(arr[neg.get(i)]) > negMax) { negMaxIdx = neg.get(i); negMax = Math.abs(arr[negMaxIdx]); } } for (int i = 0; i < neg.size(); i++) { if (Math.abs(arr[neg.get(i)]) < negMin && neg.get(i) != negMaxIdx) { negMinIdx = neg.get(i); negMin = Math.abs(arr[negMinIdx]); } } res.add(arr[negMinIdx]); res.add(arr[negMaxIdx]); for (int i = 0; i < n; i++) if (i != negMinIdx && i != negMaxIdx) res.add(arr[i]); for (int i = 0; i < res.size(); i++) System.out.println(res.get(i)+" "); System.out.println(); } // Case - 4: else { System.out.println("No swap required"); } } // Driver code public static void main (String[] args) { int arr[] = { -4, 1, 6, -3, -2, -1 }; int n = arr.length; getMinimumSum(arr, n); }} // This code is contributed by rag2127 # Python3 program to find# minimum sum of roots of a# given polynomialimport sys def getMinimumSum(arr, n): # resultant list res = [] # a lis that store indices # of the positive # elements pos = [] # a list that store indices # of the negative # elements neg = [] for i in range(n): if (arr[i] > 0): pos.append(i) elif (arr[i] < 0): neg.append(i) # Case - 1: if (len(pos) >= 2 and len(neg) >= 2): posMax = -sys.maxsize-1 posMaxIdx = -1 posMin = sys.maxsize posMinIdx = -1 negMax = -sys.maxsize-1 negMaxIdx = -1 negMin = sys.maxsize negMinIdx = -1 for i in range(len(pos)): if (arr[pos[i]] > posMax): posMaxIdx = pos[i] posMax = arr[posMaxIdx] for i in range(len(pos)): if (arr[pos[i]] < posMin and pos[i] != posMaxIdx): posMinIdx = pos[i] posMin = arr[posMinIdx] for i in range(len(neg)): if (abs(arr[neg[i]]) > negMax): negMaxIdx = neg[i] negMax = abs(arr[negMaxIdx]) for i in range(len(neg)): if (abs(arr[neg[i]]) < negMin and neg[i] != negMaxIdx): negMinIdx = neg[i] negMin = abs(arr[negMinIdx]) posVal = (-1.0 * posMax / posMin) negVal = (-1.0 * negMax / negMin) if (posVal < negVal): res.append(arr[posMinIdx]) res.append(arr[posMaxIdx]) for i in range(n): if (i != posMinIdx and i != posMaxIdx): res.append(arr[i]) else: res.append(arr[negMinIdx]) res.append(arr[negMaxIdx]) for i in range(n): if (i != negMinIdx and i != negMaxIdx): resal.append(arr[i]) for i in range(len(res)): print(res[i], end = " ") print() # Case - 2: elif (len(pos) >= 2): posMax = -sys.maxsize posMaxIdx = -1 posMin = sys.maxsize posMinIdx = -1 for i in range(len(pos)): if (arr[pos[i]] > posMax): posMaxIdx = pos[i] posMax = arr[posMaxIdx] for i in range(len(pos)): if (arr[pos[i]] < posMin and pos[i] != posMaxIdx): posMinIdx = pos[i] posMin = arr[posMinIdx] res.append(arr[posMinIdx]) res.append(arr[posMaxIdx]) for i in range(n): if (i != posMinIdx and i != posMaxIdx): res.append(arr[i]) for i in range(len(res)): print(res[i], end = " ") print() # Case - 3: elif (len(neg) >= 2): negMax = -sys.maxsize negMaxIdx = -1 negMin = sys.maxsize negMinIdx = -1 for i in range(len(neg)): if (abs(arr[neg[i]]) > negMax): negMaxIdx = neg[i] negMax = abs(arr[negMaxIdx]) for i in range(len(neg)): if (abs(arr[neg[i]]) < negMin and neg[i] != negMaxIdx): negMinIdx = neg[i] negMin = abs(arr[negMinIdx]) res.append(arr[negMinIdx]) res.append(arr[negMaxIdx]) for i in range(n): if (i != negMinIdx and i != negMaxIdx): res.append(arr[i]) for i in range(len(res)): print(res[i], end = " ") print() # Case - 4: else: print("No swap required") # Driver codeif __name__ == "__main__": arr = [-4, 1, 6, -3, -2, -1] n = len(arr) getMinimumSum(arr, n) # This code is contributed by Chitranayal // C# program to find minimum sum of// roots of a given polynomialusing System;using System.Collections.Generic; class GFG{ static void getMinimumSum(int[] arr, int n){ // resultant vector List<int> res = new List<int>(); // a vector that store indices of the positive // elements List<int> pos = new List<int>(); // a vector that store indices of the negative // elements List<int> neg = new List<int>(); for(int i = 0; i < n; i++) { if (arr[i] > 0) pos.Add(i); else if (arr[i] < 0) neg.Add(i); } // Case - 1: if (pos.Count >= 2 && neg.Count >= 2) { int posMax = Int32.MinValue, posMaxIdx = -1; int posMin = Int32.MaxValue, posMinIdx = -1; int negMax = Int32.MinValue, negMaxIdx = -1; int negMin = Int32.MaxValue, negMinIdx = -1; for(int i = 0; i < pos.Count; i++) { if (arr[pos[i]] > posMax) { posMaxIdx = pos[i]; posMax = arr[posMaxIdx]; } } for(int i = 0; i < pos.Count; i++) { if (arr[pos[i]] < posMin && pos[i] != posMaxIdx) { posMinIdx = pos[i]; posMin = arr[posMinIdx]; } } for(int i = 0; i < neg.Count; i++) { if (Math.Abs(arr[neg[i]]) > negMax) { negMaxIdx = neg[i]; negMax = Math.Abs(arr[negMaxIdx]); } } for(int i = 0; i < neg.Count; i++) { if (Math.Abs(arr[neg[i]]) < negMin && neg[i] != negMaxIdx) { negMinIdx = neg[i]; negMin = Math.Abs(arr[negMinIdx]); } } double posVal = -1.0 * (double)posMax / (double)posMin; double negVal = -1.0 * (double)negMax / (double)negMin; if (posVal < negVal) { res.Add(arr[posMinIdx]); res.Add(arr[posMaxIdx]); for(int i = 0; i < n; i++) { if (i != posMinIdx && i != posMaxIdx) { res.Add(arr[i]); } } } else { res.Add(arr[negMinIdx]); res.Add(arr[negMaxIdx]); for(int i = 0; i < n; i++) { if (i != negMinIdx && i != negMaxIdx) { res.Add(arr[i]); } } } for(int i = 0; i < res.Count; i++) { Console.Write(res[i] + " "); } Console.WriteLine(); } // Case - 2: else if (pos.Count >= 2) { int posMax = Int32.MinValue, posMaxIdx = -1; int posMin = Int32.MaxValue, posMinIdx = -1; for(int i = 0; i < pos.Count; i++) { if (arr[pos[i]] > posMax) { posMaxIdx = pos[i]; posMax = arr[posMaxIdx]; } } for(int i = 0; i < pos.Count; i++) { if (arr[pos[i]] < posMin && pos[i] != posMaxIdx) { posMinIdx = pos[i]; posMin = arr[posMinIdx]; } } res.Add(arr[posMinIdx]); res.Add(arr[posMaxIdx]); for(int i = 0; i < n; i++) { if (i != posMinIdx && i != posMaxIdx) { res.Add(arr[i]); } } for(int i = 0; i < res.Count; i++) { Console.Write(res[i] + " "); } Console.WriteLine(); } // Case - 3: else if (neg.Count >= 2) { int negMax = Int32.MinValue, negMaxIdx = -1; int negMin = Int32.MaxValue, negMinIdx = -1; for(int i = 0; i < neg.Count; i++) { if (Math.Abs(arr[neg[i]]) > negMax) { negMaxIdx = neg[i]; negMax = Math.Abs(arr[negMaxIdx]); } } for(int i = 0; i < neg.Count; i++) { if (Math.Abs(arr[neg[i]]) < negMin && neg[i] != negMaxIdx) { negMinIdx = neg[i]; negMin = Math.Abs(arr[negMinIdx]); } } res.Add(arr[negMinIdx]); res.Add(arr[negMaxIdx]); for(int i = 0; i < n; i++) if (i != negMinIdx && i != negMaxIdx) res.Add(arr[i]); for(int i = 0; i < res.Count; i++) Console.WriteLine(res[i] + " "); Console.WriteLine(); } // Case - 4: else { Console.WriteLine("No swap required"); }} // Driver codestatic public void Main(){ int[] arr = { -4, 1, 6, -3, -2, -1 }; int n = arr.Length; getMinimumSum(arr, n);}} // This code is contributed by avanitrachhadiya2155 <script>// Javascript program to find minimum sum of roots of a// given polynomial function getMinimumSum(arr,n){ // resultant vector let res = [] ; // a vector that store indices of the positive // elements let pos = [] ; // a vector that store indices of the negative // elements let neg = []; for (let i = 0; i < n; i++) { if (arr[i] > 0) pos.push(i); else if (arr[i] < 0) neg.push(i); } // Case - 1: if (pos.length >= 2 && neg.length >= 2) { let posMax = Number.MIN_VALUE, posMaxIdx = -1; let posMin = Number.MAX_VALUE, posMinIdx = -1; let negMax = Number.MIN_VALUE, negMaxIdx = -1; let negMin = Number.MAX_VALUE, negMinIdx = -1; for (let i = 0; i < pos.length; i++) { if (arr[pos[i]] > posMax) { posMaxIdx = pos[i]; posMax = arr[posMaxIdx]; } } for (let i = 0; i < pos.length; i++) { if (arr[pos[i]] < posMin && pos[i] != posMaxIdx) { posMinIdx = pos[i]; posMin = arr[posMinIdx]; } } for (let i = 0; i < neg.length; i++) { if (Math.abs(arr[neg[i]]) > negMax) { negMaxIdx = neg[i]; negMax = Math.abs(arr[negMaxIdx]); } } for (let i = 0; i < neg.length; i++) { if (Math.abs(arr[neg[i]]) < negMin && neg[i] != negMaxIdx) { negMinIdx = neg[i]; negMin = Math.abs(arr[negMinIdx]); } } let posVal = -1.0 * posMax / posMin; let negVal = -1.0 * negMax / negMin; if (posVal < negVal) { res.push(arr[posMinIdx]); res.push(arr[posMaxIdx]); for (let i = 0; i < n; i++) { if (i != posMinIdx && i != posMaxIdx) { res.push(arr[i]); } } } else { res.push(arr[negMinIdx]); res.push(arr[negMaxIdx]); for (let i = 0; i < n; i++) { if (i != negMinIdx && i != negMaxIdx) { res.push(arr[i]); } } } for (let i = 0; i < res.length; i++) { document.write(res[i] + " "); } document.write("<br>"); } // Case - 2: else if (pos.length >= 2) { let posMax = Number.MIN_VALUE, posMaxIdx = -1; let posMin = Number.MAX_VALUE, posMinIdx = -1; for (let i = 0; i < pos.length; i++) { if (arr[pos[i]] > posMax) { posMaxIdx = pos[i]; posMax = arr[posMaxIdx]; } } for (let i = 0; i < pos.length; i++) { if (arr[pos[i]] < posMin && pos[i] != posMaxIdx) { posMinIdx = pos[i]; posMin = arr[posMinIdx]; } } res.push(arr[posMinIdx]); res.push(arr[posMaxIdx]); for (let i = 0; i < n; i++) { if (i != posMinIdx && i != posMaxIdx) { res.push(arr[i]); } } for (let i = 0; i < res.length; i++) { document.write(res[i]+" "); } document.write("<br>"); } // Case - 3: else if (neg.length >= 2) { let negMax = Number.MIN_VALUE, negMaxIdx = -1; let negMin = Number.MAX_VALUE, negMinIdx = -1; for (let i = 0; i < neg.length; i++) { if (Math.abs(arr[neg[i]]) > negMax) { negMaxIdx = neg[i]; negMax = Math.abs(arr[negMaxIdx]); } } for (let i = 0; i < neg.length; i++) { if (Math.abs(arr[neg[i]]) < negMin && neg[i] != negMaxIdx) { negMinIdx = neg[i]; negMin = Math.abs(arr[negMinIdx]); } } res.push(arr[negMinIdx]); res.push(arr[negMaxIdx]); for (let i = 0; i < n; i++) if (i != negMinIdx && i != negMaxIdx) res.push(arr[i]); for (let i = 0; i < res.length; i++) document.write(res[i]+" "); document.write("<br>"); } // Case - 4: else { document.write("No swap required"); } } // Driver codelet arr=[-4, 1, 6, -3, -2, -1];let n = arr.length;getMinimumSum(arr, n); // This code is contributed by unknown2108</script> 1 6 -4 -3 -2 -1 ukasp rag2127 avanitrachhadiya2155 unknown2108 surinderdawra388 maths-polynomial Arrays Searching Arrays Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Binary Search Median of two sorted arrays of different sizes Find the index of an array element in Java Two Pointers Technique Count number of occurrences (or frequency) in a sorted array
[ { "code": null, "e": 26041, "s": 26013, "text": "\n03 Jun, 2021" }, { "code": null, "e": 26558, "s": 26041, "text": "Given an array whose elements represent the coefficients of a polynomial of degree n, if the polynomial has a degree n then the array will have n+1 elements (one extra for the constant of a polynomial). Swap some elements of the array and print the resulting array such that the sum of the roots of the given polynomial is as minimum as possible irrespective of the nature of the roots.Note that: except the first element of the array elements can be 0 also and the degree of the polynomial is always greater than 1." }, { "code": null, "e": 26569, "s": 26558, "text": "Examples: " }, { "code": null, "e": 26872, "s": 26569, "text": "Input : -4 1 6 -3 -2 -1\nOutput : 1 6 -4 -3 -2 -1\n Here, the array is -4, 1, 6, -3, -2, -1\n i.e the polynomial is -4.x^5 + 1.x^4 + 6.x^3 - 3.x^2 - 2.x^1 - 1\n minimum sum = -6 \n\nInput : -9 0 9\nOutput :-9 0 9\n Here polynomial is \n -9.x^2 + 0.x^1 + 9\n minimum sum = 0" }, { "code": null, "e": 27322, "s": 26872, "text": "Solution : Let us recall the fact about the sum of the roots of a polynomial if a polynomial p(x) = a.x^n + b.x^n-1 + c.x^n-2 + ... + k, then the sum of roots of a polynomial is given by -b/a. Please see Vieta’s formulas for details.We have to minimize -b/a i.e to maximize b/a i.e maximize b and minimize a. So if somehow we are able to maximize b and minimize a, we will swap the values of the coefficients and copy the rest of the array as it is." }, { "code": null, "e": 28701, "s": 27322, "text": "There will be four cases : Case #1: when the number of positive coefficients and the number of negative coefficients both are greater than or equal to 2 In this case, we will find a maximum and minimum from positive elements and from negative elements also and we will check -(maxPos)/(minPos) is smaller or -( abs(maxNeg) )/ ( abs(minNeg) ) is smaller and print the answer after swapping accordingly.Case #2: when the number of positive coefficients is greater than equal to 2 but the number of negative coefficients is less than 2 In this case, we will consider the case of the maximum of positive and minimum of positive elements only. Because if we picked up one from positive elements and the other from negative elements the result of -b/a will be a positive value which is not minimum. (as we require a large negative value) Case #3: when the number of negative coefficients is greater than equal to 2 but the number of positive coefficients is less than 2 In this case, we will consider the case of the maximum of negative and minimum of negative elements only. Because if we picked up one from positive elements and the other from negative elements the result of -b/a will be a positive value which is not minimum. (as we require a large negative value)Case #4: When both the counts are less than or equal to 1 Observe carefully, You cannot swap elements in this case. " }, { "code": null, "e": 28705, "s": 28701, "text": "C++" }, { "code": null, "e": 28710, "s": 28705, "text": "Java" }, { "code": null, "e": 28718, "s": 28710, "text": "Python3" }, { "code": null, "e": 28721, "s": 28718, "text": "C#" }, { "code": null, "e": 28732, "s": 28721, "text": "Javascript" }, { "code": "// C++ program to find minimum sum of roots of a// given polynomial#include <bits/stdc++.h>using namespace std; void getMinimumSum(int arr[], int n){ // resultant vector vector<int> res; // a vector that store indices of the positive // elements vector<int> pos; // a vector that store indices of the negative // elements vector<int> neg; for (int i = 0; i < n; i++) { if (arr[i] > 0) pos.push_back(i); else if (arr[i] < 0) neg.push_back(i); } // Case - 1: if (pos.size() >= 2 && neg.size() >= 2) { int posMax = INT_MIN, posMaxIdx = -1; int posMin = INT_MAX, posMinIdx = -1; int negMax = INT_MIN, negMaxIdx = -1; int negMin = INT_MAX, negMinIdx = -1; for (int i = 0; i < pos.size(); i++) { if (arr[pos[i]] > posMax) { posMaxIdx = pos[i]; posMax = arr[posMaxIdx]; } } for (int i = 0; i < pos.size(); i++) { if (arr[pos[i]] < posMin && pos[i] != posMaxIdx) { posMinIdx = pos[i]; posMin = arr[posMinIdx]; } } for (int i = 0; i < neg.size(); i++) { if (abs(arr[neg[i]]) > negMax) { negMaxIdx = neg[i]; negMax = abs(arr[negMaxIdx]); } } for (int i = 0; i < neg.size(); i++) { if (abs(arr[neg[i]]) < negMin && neg[i] != negMaxIdx) { negMinIdx = neg[i]; negMin = abs(arr[negMinIdx]); } } double posVal = -1.0 * (double)posMax / (double)posMin; double negVal = -1.0 * (double)negMax / (double)negMin; if (posVal < negVal) { res.push_back(arr[posMinIdx]); res.push_back(arr[posMaxIdx]); for (int i = 0; i < n; i++) { if (i != posMinIdx && i != posMaxIdx) { res.push_back(arr[i]); } } } else { res.push_back(arr[negMinIdx]); res.push_back(arr[negMaxIdx]); for (int i = 0; i < n; i++) { if (i != negMinIdx && i != negMaxIdx) { res.push_back(arr[i]); } } } for (int i = 0; i < res.size(); i++) { cout << res[i] << \" \"; } cout << \"\\n\"; } // Case - 2: else if (pos.size() >= 2) { int posMax = INT_MIN, posMaxIdx = -1; int posMin = INT_MAX, posMinIdx = -1; for (int i = 0; i < pos.size(); i++) { if (arr[pos[i]] > posMax) { posMaxIdx = pos[i]; posMax = arr[posMaxIdx]; } } for (int i = 0; i < pos.size(); i++) { if (arr[pos[i]] < posMin && pos[i] != posMaxIdx) { posMinIdx = pos[i]; posMin = arr[posMinIdx]; } } res.push_back(arr[posMinIdx]); res.push_back(arr[posMaxIdx]); for (int i = 0; i < n; i++) { if (i != posMinIdx && i != posMaxIdx) { res.push_back(arr[i]); } } for (int i = 0; i < res.size(); i++) { cout << res[i] << \" \"; } cout << \"\\n\"; } // Case - 3: else if (neg.size() >= 2) { int negMax = INT_MIN, negMaxIdx = -1; int negMin = INT_MAX, negMinIdx = -1; for (int i = 0; i < neg.size(); i++) { if (abs(arr[neg[i]]) > negMax) { negMaxIdx = neg[i]; negMax = abs(arr[negMaxIdx]); } } for (int i = 0; i < neg.size(); i++) { if (abs(arr[neg[i]]) < negMin && neg[i] != negMaxIdx) { negMinIdx = neg[i]; negMin = abs(arr[negMinIdx]); } } res.push_back(arr[negMinIdx]); res.push_back(arr[negMaxIdx]); for (int i = 0; i < n; i++) if (i != negMinIdx && i != negMaxIdx) res.push_back(arr[i]); for (int i = 0; i < res.size(); i++) cout << res[i] << \" \"; cout << \"\\n\"; } // Case - 4: else { cout << \"No swap required\\n\"; }} int main(){ int arr[] = { -4, 1, 6, -3, -2, -1 }; int n = sizeof(arr) / sizeof(arr[0]); getMinimumSum(arr, n); return 0;}", "e": 33104, "s": 28732, "text": null }, { "code": "// Java program to find minimum sum of roots of a// given polynomialimport java.io.*;import java.util.*; class GFG{ static void getMinimumSum(int arr[], int n) { // resultant vector ArrayList<Integer> res = new ArrayList<Integer>(); // a vector that store indices of the positive // elements ArrayList<Integer> pos = new ArrayList<Integer>(); // a vector that store indices of the negative // elements ArrayList<Integer> neg = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { if (arr[i] > 0) pos.add(i); else if (arr[i] < 0) neg.add(i); } // Case - 1: if (pos.size() >= 2 && neg.size() >= 2) { int posMax = Integer.MIN_VALUE, posMaxIdx = -1; int posMin = Integer.MAX_VALUE, posMinIdx = -1; int negMax = Integer.MIN_VALUE, negMaxIdx = -1; int negMin = Integer.MAX_VALUE, negMinIdx = -1; for (int i = 0; i < pos.size(); i++) { if (arr[pos.get(i)] > posMax) { posMaxIdx = pos.get(i); posMax = arr[posMaxIdx]; } } for (int i = 0; i < pos.size(); i++) { if (arr[pos.get(i)] < posMin && pos.get(i) != posMaxIdx) { posMinIdx = pos.get(i); posMin = arr[posMinIdx]; } } for (int i = 0; i < neg.size(); i++) { if (Math.abs(arr[neg.get(i)]) > negMax) { negMaxIdx = neg.get(i); negMax = Math.abs(arr[negMaxIdx]); } } for (int i = 0; i < neg.size(); i++) { if (Math.abs(arr[neg.get(i)]) < negMin && neg.get(i) != negMaxIdx) { negMinIdx = neg.get(i); negMin = Math.abs(arr[negMinIdx]); } } double posVal = -1.0 * (double)posMax / (double)posMin; double negVal = -1.0 * (double)negMax / (double)negMin; if (posVal < negVal) { res.add(arr[posMinIdx]); res.add(arr[posMaxIdx]); for (int i = 0; i < n; i++) { if (i != posMinIdx && i != posMaxIdx) { res.add(arr[i]); } } } else { res.add(arr[negMinIdx]); res.add(arr[negMaxIdx]); for (int i = 0; i < n; i++) { if (i != negMinIdx && i != negMaxIdx) { res.add(arr[i]); } } } for (int i = 0; i < res.size(); i++) { System.out.print(res.get(i) + \" \"); } System.out.println(); } // Case - 2: else if (pos.size() >= 2) { int posMax = Integer.MIN_VALUE, posMaxIdx = -1; int posMin = Integer.MAX_VALUE, posMinIdx = -1; for (int i = 0; i < pos.size(); i++) { if (arr[pos.get(i)] > posMax) { posMaxIdx = pos.get(i); posMax = arr[posMaxIdx]; } } for (int i = 0; i < pos.size(); i++) { if (arr[pos.get(i)] < posMin && pos.get(i) != posMaxIdx) { posMinIdx = pos.get(i); posMin = arr[posMinIdx]; } } res.add(arr[posMinIdx]); res.add(arr[posMaxIdx]); for (int i = 0; i < n; i++) { if (i != posMinIdx && i != posMaxIdx) { res.add(arr[i]); } } for (int i = 0; i < res.size(); i++) { System.out.print(res.get(i)+\" \"); } System.out.println(); } // Case - 3: else if (neg.size() >= 2) { int negMax = Integer.MIN_VALUE, negMaxIdx = -1; int negMin = Integer.MAX_VALUE, negMinIdx = -1; for (int i = 0; i < neg.size(); i++) { if (Math.abs(arr[neg.get(i)]) > negMax) { negMaxIdx = neg.get(i); negMax = Math.abs(arr[negMaxIdx]); } } for (int i = 0; i < neg.size(); i++) { if (Math.abs(arr[neg.get(i)]) < negMin && neg.get(i) != negMaxIdx) { negMinIdx = neg.get(i); negMin = Math.abs(arr[negMinIdx]); } } res.add(arr[negMinIdx]); res.add(arr[negMaxIdx]); for (int i = 0; i < n; i++) if (i != negMinIdx && i != negMaxIdx) res.add(arr[i]); for (int i = 0; i < res.size(); i++) System.out.println(res.get(i)+\" \"); System.out.println(); } // Case - 4: else { System.out.println(\"No swap required\"); } } // Driver code public static void main (String[] args) { int arr[] = { -4, 1, 6, -3, -2, -1 }; int n = arr.length; getMinimumSum(arr, n); }} // This code is contributed by rag2127", "e": 37459, "s": 33104, "text": null }, { "code": "# Python3 program to find# minimum sum of roots of a# given polynomialimport sys def getMinimumSum(arr, n): # resultant list res = [] # a lis that store indices # of the positive # elements pos = [] # a list that store indices # of the negative # elements neg = [] for i in range(n): if (arr[i] > 0): pos.append(i) elif (arr[i] < 0): neg.append(i) # Case - 1: if (len(pos) >= 2 and len(neg) >= 2): posMax = -sys.maxsize-1 posMaxIdx = -1 posMin = sys.maxsize posMinIdx = -1 negMax = -sys.maxsize-1 negMaxIdx = -1 negMin = sys.maxsize negMinIdx = -1 for i in range(len(pos)): if (arr[pos[i]] > posMax): posMaxIdx = pos[i] posMax = arr[posMaxIdx] for i in range(len(pos)): if (arr[pos[i]] < posMin and pos[i] != posMaxIdx): posMinIdx = pos[i] posMin = arr[posMinIdx] for i in range(len(neg)): if (abs(arr[neg[i]]) > negMax): negMaxIdx = neg[i] negMax = abs(arr[negMaxIdx]) for i in range(len(neg)): if (abs(arr[neg[i]]) < negMin and neg[i] != negMaxIdx): negMinIdx = neg[i] negMin = abs(arr[negMinIdx]) posVal = (-1.0 * posMax / posMin) negVal = (-1.0 * negMax / negMin) if (posVal < negVal): res.append(arr[posMinIdx]) res.append(arr[posMaxIdx]) for i in range(n): if (i != posMinIdx and i != posMaxIdx): res.append(arr[i]) else: res.append(arr[negMinIdx]) res.append(arr[negMaxIdx]) for i in range(n): if (i != negMinIdx and i != negMaxIdx): resal.append(arr[i]) for i in range(len(res)): print(res[i], end = \" \") print() # Case - 2: elif (len(pos) >= 2): posMax = -sys.maxsize posMaxIdx = -1 posMin = sys.maxsize posMinIdx = -1 for i in range(len(pos)): if (arr[pos[i]] > posMax): posMaxIdx = pos[i] posMax = arr[posMaxIdx] for i in range(len(pos)): if (arr[pos[i]] < posMin and pos[i] != posMaxIdx): posMinIdx = pos[i] posMin = arr[posMinIdx] res.append(arr[posMinIdx]) res.append(arr[posMaxIdx]) for i in range(n): if (i != posMinIdx and i != posMaxIdx): res.append(arr[i]) for i in range(len(res)): print(res[i], end = \" \") print() # Case - 3: elif (len(neg) >= 2): negMax = -sys.maxsize negMaxIdx = -1 negMin = sys.maxsize negMinIdx = -1 for i in range(len(neg)): if (abs(arr[neg[i]]) > negMax): negMaxIdx = neg[i] negMax = abs(arr[negMaxIdx]) for i in range(len(neg)): if (abs(arr[neg[i]]) < negMin and neg[i] != negMaxIdx): negMinIdx = neg[i] negMin = abs(arr[negMinIdx]) res.append(arr[negMinIdx]) res.append(arr[negMaxIdx]) for i in range(n): if (i != negMinIdx and i != negMaxIdx): res.append(arr[i]) for i in range(len(res)): print(res[i], end = \" \") print() # Case - 4: else: print(\"No swap required\") # Driver codeif __name__ == \"__main__\": arr = [-4, 1, 6, -3, -2, -1] n = len(arr) getMinimumSum(arr, n) # This code is contributed by Chitranayal", "e": 41294, "s": 37459, "text": null }, { "code": "// C# program to find minimum sum of// roots of a given polynomialusing System;using System.Collections.Generic; class GFG{ static void getMinimumSum(int[] arr, int n){ // resultant vector List<int> res = new List<int>(); // a vector that store indices of the positive // elements List<int> pos = new List<int>(); // a vector that store indices of the negative // elements List<int> neg = new List<int>(); for(int i = 0; i < n; i++) { if (arr[i] > 0) pos.Add(i); else if (arr[i] < 0) neg.Add(i); } // Case - 1: if (pos.Count >= 2 && neg.Count >= 2) { int posMax = Int32.MinValue, posMaxIdx = -1; int posMin = Int32.MaxValue, posMinIdx = -1; int negMax = Int32.MinValue, negMaxIdx = -1; int negMin = Int32.MaxValue, negMinIdx = -1; for(int i = 0; i < pos.Count; i++) { if (arr[pos[i]] > posMax) { posMaxIdx = pos[i]; posMax = arr[posMaxIdx]; } } for(int i = 0; i < pos.Count; i++) { if (arr[pos[i]] < posMin && pos[i] != posMaxIdx) { posMinIdx = pos[i]; posMin = arr[posMinIdx]; } } for(int i = 0; i < neg.Count; i++) { if (Math.Abs(arr[neg[i]]) > negMax) { negMaxIdx = neg[i]; negMax = Math.Abs(arr[negMaxIdx]); } } for(int i = 0; i < neg.Count; i++) { if (Math.Abs(arr[neg[i]]) < negMin && neg[i] != negMaxIdx) { negMinIdx = neg[i]; negMin = Math.Abs(arr[negMinIdx]); } } double posVal = -1.0 * (double)posMax / (double)posMin; double negVal = -1.0 * (double)negMax / (double)negMin; if (posVal < negVal) { res.Add(arr[posMinIdx]); res.Add(arr[posMaxIdx]); for(int i = 0; i < n; i++) { if (i != posMinIdx && i != posMaxIdx) { res.Add(arr[i]); } } } else { res.Add(arr[negMinIdx]); res.Add(arr[negMaxIdx]); for(int i = 0; i < n; i++) { if (i != negMinIdx && i != negMaxIdx) { res.Add(arr[i]); } } } for(int i = 0; i < res.Count; i++) { Console.Write(res[i] + \" \"); } Console.WriteLine(); } // Case - 2: else if (pos.Count >= 2) { int posMax = Int32.MinValue, posMaxIdx = -1; int posMin = Int32.MaxValue, posMinIdx = -1; for(int i = 0; i < pos.Count; i++) { if (arr[pos[i]] > posMax) { posMaxIdx = pos[i]; posMax = arr[posMaxIdx]; } } for(int i = 0; i < pos.Count; i++) { if (arr[pos[i]] < posMin && pos[i] != posMaxIdx) { posMinIdx = pos[i]; posMin = arr[posMinIdx]; } } res.Add(arr[posMinIdx]); res.Add(arr[posMaxIdx]); for(int i = 0; i < n; i++) { if (i != posMinIdx && i != posMaxIdx) { res.Add(arr[i]); } } for(int i = 0; i < res.Count; i++) { Console.Write(res[i] + \" \"); } Console.WriteLine(); } // Case - 3: else if (neg.Count >= 2) { int negMax = Int32.MinValue, negMaxIdx = -1; int negMin = Int32.MaxValue, negMinIdx = -1; for(int i = 0; i < neg.Count; i++) { if (Math.Abs(arr[neg[i]]) > negMax) { negMaxIdx = neg[i]; negMax = Math.Abs(arr[negMaxIdx]); } } for(int i = 0; i < neg.Count; i++) { if (Math.Abs(arr[neg[i]]) < negMin && neg[i] != negMaxIdx) { negMinIdx = neg[i]; negMin = Math.Abs(arr[negMinIdx]); } } res.Add(arr[negMinIdx]); res.Add(arr[negMaxIdx]); for(int i = 0; i < n; i++) if (i != negMinIdx && i != negMaxIdx) res.Add(arr[i]); for(int i = 0; i < res.Count; i++) Console.WriteLine(res[i] + \" \"); Console.WriteLine(); } // Case - 4: else { Console.WriteLine(\"No swap required\"); }} // Driver codestatic public void Main(){ int[] arr = { -4, 1, 6, -3, -2, -1 }; int n = arr.Length; getMinimumSum(arr, n);}} // This code is contributed by avanitrachhadiya2155", "e": 46278, "s": 41294, "text": null }, { "code": "<script>// Javascript program to find minimum sum of roots of a// given polynomial function getMinimumSum(arr,n){ // resultant vector let res = [] ; // a vector that store indices of the positive // elements let pos = [] ; // a vector that store indices of the negative // elements let neg = []; for (let i = 0; i < n; i++) { if (arr[i] > 0) pos.push(i); else if (arr[i] < 0) neg.push(i); } // Case - 1: if (pos.length >= 2 && neg.length >= 2) { let posMax = Number.MIN_VALUE, posMaxIdx = -1; let posMin = Number.MAX_VALUE, posMinIdx = -1; let negMax = Number.MIN_VALUE, negMaxIdx = -1; let negMin = Number.MAX_VALUE, negMinIdx = -1; for (let i = 0; i < pos.length; i++) { if (arr[pos[i]] > posMax) { posMaxIdx = pos[i]; posMax = arr[posMaxIdx]; } } for (let i = 0; i < pos.length; i++) { if (arr[pos[i]] < posMin && pos[i] != posMaxIdx) { posMinIdx = pos[i]; posMin = arr[posMinIdx]; } } for (let i = 0; i < neg.length; i++) { if (Math.abs(arr[neg[i]]) > negMax) { negMaxIdx = neg[i]; negMax = Math.abs(arr[negMaxIdx]); } } for (let i = 0; i < neg.length; i++) { if (Math.abs(arr[neg[i]]) < negMin && neg[i] != negMaxIdx) { negMinIdx = neg[i]; negMin = Math.abs(arr[negMinIdx]); } } let posVal = -1.0 * posMax / posMin; let negVal = -1.0 * negMax / negMin; if (posVal < negVal) { res.push(arr[posMinIdx]); res.push(arr[posMaxIdx]); for (let i = 0; i < n; i++) { if (i != posMinIdx && i != posMaxIdx) { res.push(arr[i]); } } } else { res.push(arr[negMinIdx]); res.push(arr[negMaxIdx]); for (let i = 0; i < n; i++) { if (i != negMinIdx && i != negMaxIdx) { res.push(arr[i]); } } } for (let i = 0; i < res.length; i++) { document.write(res[i] + \" \"); } document.write(\"<br>\"); } // Case - 2: else if (pos.length >= 2) { let posMax = Number.MIN_VALUE, posMaxIdx = -1; let posMin = Number.MAX_VALUE, posMinIdx = -1; for (let i = 0; i < pos.length; i++) { if (arr[pos[i]] > posMax) { posMaxIdx = pos[i]; posMax = arr[posMaxIdx]; } } for (let i = 0; i < pos.length; i++) { if (arr[pos[i]] < posMin && pos[i] != posMaxIdx) { posMinIdx = pos[i]; posMin = arr[posMinIdx]; } } res.push(arr[posMinIdx]); res.push(arr[posMaxIdx]); for (let i = 0; i < n; i++) { if (i != posMinIdx && i != posMaxIdx) { res.push(arr[i]); } } for (let i = 0; i < res.length; i++) { document.write(res[i]+\" \"); } document.write(\"<br>\"); } // Case - 3: else if (neg.length >= 2) { let negMax = Number.MIN_VALUE, negMaxIdx = -1; let negMin = Number.MAX_VALUE, negMinIdx = -1; for (let i = 0; i < neg.length; i++) { if (Math.abs(arr[neg[i]]) > negMax) { negMaxIdx = neg[i]; negMax = Math.abs(arr[negMaxIdx]); } } for (let i = 0; i < neg.length; i++) { if (Math.abs(arr[neg[i]]) < negMin && neg[i] != negMaxIdx) { negMinIdx = neg[i]; negMin = Math.abs(arr[negMinIdx]); } } res.push(arr[negMinIdx]); res.push(arr[negMaxIdx]); for (let i = 0; i < n; i++) if (i != negMinIdx && i != negMaxIdx) res.push(arr[i]); for (let i = 0; i < res.length; i++) document.write(res[i]+\" \"); document.write(\"<br>\"); } // Case - 4: else { document.write(\"No swap required\"); } } // Driver codelet arr=[-4, 1, 6, -3, -2, -1];let n = arr.length;getMinimumSum(arr, n); // This code is contributed by unknown2108</script>", "e": 50335, "s": 46278, "text": null }, { "code": null, "e": 50351, "s": 50335, "text": "1 6 -4 -3 -2 -1" }, { "code": null, "e": 50359, "s": 50353, "text": "ukasp" }, { "code": null, "e": 50367, "s": 50359, "text": "rag2127" }, { "code": null, "e": 50388, "s": 50367, "text": "avanitrachhadiya2155" }, { "code": null, "e": 50400, "s": 50388, "text": "unknown2108" }, { "code": null, "e": 50417, "s": 50400, "text": "surinderdawra388" }, { "code": null, "e": 50434, "s": 50417, "text": "maths-polynomial" }, { "code": null, "e": 50441, "s": 50434, "text": "Arrays" }, { "code": null, "e": 50451, "s": 50441, "text": "Searching" }, { "code": null, "e": 50458, "s": 50451, "text": "Arrays" }, { "code": null, "e": 50468, "s": 50458, "text": "Searching" }, { "code": null, "e": 50566, "s": 50468, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 50593, "s": 50566, "text": "Count pairs with given sum" }, { "code": null, "e": 50624, "s": 50593, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 50649, "s": 50624, "text": "Window Sliding Technique" }, { "code": null, "e": 50687, "s": 50649, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 50708, "s": 50687, "text": "Next Greater Element" }, { "code": null, "e": 50722, "s": 50708, "text": "Binary Search" }, { "code": null, "e": 50769, "s": 50722, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 50812, "s": 50769, "text": "Find the index of an array element in Java" }, { "code": null, "e": 50835, "s": 50812, "text": "Two Pointers Technique" } ]
How to Convert Models Data into JSON in Django ? - GeeksforGeeks
16 Mar, 2021 Django is a high-level Python based Web Framework that allows rapid development and clean, pragmatic design. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database SQLlite3, etc. How to Convert Models Data Into Json Data In Django ? First create new project django-admin startproject tryJson cd tryJson Then create new app inside your project python manage.py startapp main Add your main app inside the tryJson/settings.py in INSTALLED_APPS Edit the models.py in main app Python3 from django.db import models class Student(models.Model): course_choices = ( ('1','Java'), ('2','Python'), ('3','Javascript') ) name = models.CharField(max_length=50) rollno = models.IntegerField() course = models.CharField(max_length=15, choices = course_choices) Then to create model we have to write below commands in cmd or terminal python manage.py makemigrations python manage.py migrate So we have created our model Students with some fields like name , roll no , course. Insert Some data into model. Create a new file inside your main app urls.py Python3 from django.urls import pathfrom . import * urlpatterns = [ path("",views.jsondata,name = "jsondata"),] Write logic to convert models data into Json data views.py Python3 from django.http import JsonResponsefrom .models import Students def jsondata(request): data list(Students.objects.values()) return JsonResponse(data,safe = False) Use values() method to get all the data and convert into list using list() function and store in a variable. return a JsonResponse and pass the data and put safe = False Then open cmd or terminal to run this app python manage.py runserver Output :- Django-models JSON Python Django Python Framework 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 | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25555, "s": 25527, "text": "\n16 Mar, 2021" }, { "code": null, "e": 25835, "s": 25555, "text": "Django is a high-level Python based Web Framework that allows rapid development and clean, pragmatic design. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database SQLlite3, etc." }, { "code": null, "e": 25889, "s": 25835, "text": "How to Convert Models Data Into Json Data In Django ?" }, { "code": null, "e": 25914, "s": 25889, "text": "First create new project" }, { "code": null, "e": 25948, "s": 25914, "text": "django-admin startproject tryJson" }, { "code": null, "e": 25959, "s": 25948, "text": "cd tryJson" }, { "code": null, "e": 25999, "s": 25959, "text": "Then create new app inside your project" }, { "code": null, "e": 26030, "s": 25999, "text": "python manage.py startapp main" }, { "code": null, "e": 26097, "s": 26030, "text": "Add your main app inside the tryJson/settings.py in INSTALLED_APPS" }, { "code": null, "e": 26128, "s": 26097, "text": "Edit the models.py in main app" }, { "code": null, "e": 26136, "s": 26128, "text": "Python3" }, { "code": "from django.db import models class Student(models.Model): course_choices = ( ('1','Java'), ('2','Python'), ('3','Javascript') ) name = models.CharField(max_length=50) rollno = models.IntegerField() course = models.CharField(max_length=15, choices = course_choices)", "e": 26449, "s": 26136, "text": null }, { "code": null, "e": 26521, "s": 26449, "text": "Then to create model we have to write below commands in cmd or terminal" }, { "code": null, "e": 26553, "s": 26521, "text": "python manage.py makemigrations" }, { "code": null, "e": 26578, "s": 26553, "text": "python manage.py migrate" }, { "code": null, "e": 26663, "s": 26578, "text": "So we have created our model Students with some fields like name , roll no , course." }, { "code": null, "e": 26692, "s": 26663, "text": "Insert Some data into model." }, { "code": null, "e": 26732, "s": 26692, "text": "Create a new file inside your main app " }, { "code": null, "e": 26740, "s": 26732, "text": "urls.py" }, { "code": null, "e": 26748, "s": 26740, "text": "Python3" }, { "code": "from django.urls import pathfrom . import * urlpatterns = [ path(\"\",views.jsondata,name = \"jsondata\"),]", "e": 26857, "s": 26748, "text": null }, { "code": null, "e": 26907, "s": 26857, "text": "Write logic to convert models data into Json data" }, { "code": null, "e": 26916, "s": 26907, "text": "views.py" }, { "code": null, "e": 26924, "s": 26916, "text": "Python3" }, { "code": "from django.http import JsonResponsefrom .models import Students def jsondata(request): data list(Students.objects.values()) return JsonResponse(data,safe = False)", "e": 27097, "s": 26924, "text": null }, { "code": null, "e": 27206, "s": 27097, "text": "Use values() method to get all the data and convert into list using list() function and store in a variable." }, { "code": null, "e": 27269, "s": 27206, "text": "return a JsonResponse and pass the data and put safe = False" }, { "code": null, "e": 27312, "s": 27269, "text": "Then open cmd or terminal to run this app" }, { "code": null, "e": 27339, "s": 27312, "text": "python manage.py runserver" }, { "code": null, "e": 27349, "s": 27339, "text": "Output :-" }, { "code": null, "e": 27363, "s": 27349, "text": "Django-models" }, { "code": null, "e": 27368, "s": 27363, "text": "JSON" }, { "code": null, "e": 27382, "s": 27368, "text": "Python Django" }, { "code": null, "e": 27399, "s": 27382, "text": "Python Framework" }, { "code": null, "e": 27406, "s": 27399, "text": "Python" }, { "code": null, "e": 27504, "s": 27406, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27536, "s": 27504, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27578, "s": 27536, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27620, "s": 27578, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27676, "s": 27620, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27703, "s": 27676, "text": "Python Classes and Objects" }, { "code": null, "e": 27734, "s": 27703, "text": "Python | os.path.join() method" }, { "code": null, "e": 27773, "s": 27734, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27802, "s": 27773, "text": "Create a directory in Python" }, { "code": null, "e": 27824, "s": 27802, "text": "Defaultdict in Python" } ]
Designing Finite Automata from Regular Expression (Set 3) - GeeksforGeeks
20 Nov, 2019 Prerequisite: Finite automata, Regular expressions, grammar and language, Designing finite automata from Regular expression (Set 2) In the below article, we shall see some Designing of Finite Automata form the given Regular Expression. Regular Expression 1: ‘ab*’ (‘a’ followed by any number of ‘b’). The language of the given RE is, L1 = {a, ab, abb, abbb, .........} Its finite automata will be like below-In the above transition diagram, as we can see that state ‘X’ on getting ‘a’ as the input it transits to a final state ‘Y’ which on getting ‘b’ as the input it remains in the state of itself. Thus this FA accepting all the strings of the given RE language. Regular Expression 2: ‘(ab)*’ (‘a’ followed by ‘b’ but substring ‘ab’ can be repeated any number of times). The language of the given RE is, L2 = {ε, ab, abab, ababab, .........} Its finite automata will be like below-In the above transition diagram, as we can see that initial and final state ‘X’ on getting ‘a’ as the input it transits to a final state ‘Y’ which on getting ‘b’ as the input it comes back to the state ‘X’. Thus this FA accepting all the strings of the given RE language. Regular Expression 3: ‘(a+b)*’ (‘a’ union ‘b’ but substring ‘a+b’ can be repeated any number of times). The language of the given RE is, L3 = {ε, a, b, aa, aaab, bbbbb, ba, .......} The language containing ε and any number of ‘a’ or ‘b’ or both combined.Its finite automata will be like below-In the above transition diagram, as we can see that state ‘X’ on getting ‘a’ as the input it remains in the state of itself and on getting ‘b’ as the input it transits to an another final state ‘Y’ which on getting ‘b’ or ‘a’ as the input it remains in the state of itself. Thus this FA accepting all the strings of the given RE language. Note – The minimal DFA of regular expression (a+b)* will have only single state, which is both starting and final state. This will contain only loop of alphabet ‘a’ and ‘b’. Regular Expression 4: ‘(ab+ba)*’ (‘ab’ union ‘ba’ but substring ‘ab+ba’ can be repeated any number of times). The language of the given RE is, L4 = {ε, ab, abab, abba, ba, baba, ........ } The language containing ε and any number of ‘ab’ or ‘ba’ or both combined.Its finite automata will be like below- In the above transition diagram, the initial and final state ‘X’ on getting ‘a’ as input it go to a state ‘Y’ and on getting ‘b’ as the input it go to an another state ‘Z’ and so on for the remaining states. Thus this FA accepting all the strings of the given RE language. Regular Expression 5: ‘a+’ (Any number of ‘a’ excluding ε).The language of the given RE is L5 = {a, aa, aaa, aaaa, .........} Its finite automata will be like below-In the above transition diagram, initial state ‘X’ on getting ‘a’ as the input it transits to a final state ‘Y’ which on getting ‘a’ as the input it remains in the state of itself. Thus this FA accepting all the strings of the given RE language. GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Page Replacement Algorithms in Operating Systems Differences between TCP and UDP Semaphores in Process Synchronization Data encryption standard (DES) | Set 1 LRU Cache Implementation Difference between DFA and NFA Turing Machine in TOC Difference between Mealy machine and Moore machine Conversion from NFA to DFA Mealy and Moore Machines in TOC
[ { "code": null, "e": 24546, "s": 24518, "text": "\n20 Nov, 2019" }, { "code": null, "e": 24678, "s": 24546, "text": "Prerequisite: Finite automata, Regular expressions, grammar and language, Designing finite automata from Regular expression (Set 2)" }, { "code": null, "e": 24782, "s": 24678, "text": "In the below article, we shall see some Designing of Finite Automata form the given Regular Expression." }, { "code": null, "e": 24880, "s": 24782, "text": "Regular Expression 1: ‘ab*’ (‘a’ followed by any number of ‘b’). The language of the given RE is," }, { "code": null, "e": 24916, "s": 24880, "text": "L1 = {a, ab, abb, abbb, .........} " }, { "code": null, "e": 25212, "s": 24916, "text": "Its finite automata will be like below-In the above transition diagram, as we can see that state ‘X’ on getting ‘a’ as the input it transits to a final state ‘Y’ which on getting ‘b’ as the input it remains in the state of itself. Thus this FA accepting all the strings of the given RE language." }, { "code": null, "e": 25353, "s": 25212, "text": "Regular Expression 2: ‘(ab)*’ (‘a’ followed by ‘b’ but substring ‘ab’ can be repeated any number of times). The language of the given RE is," }, { "code": null, "e": 25392, "s": 25353, "text": "L2 = {ε, ab, abab, ababab, .........} " }, { "code": null, "e": 25703, "s": 25392, "text": "Its finite automata will be like below-In the above transition diagram, as we can see that initial and final state ‘X’ on getting ‘a’ as the input it transits to a final state ‘Y’ which on getting ‘b’ as the input it comes back to the state ‘X’. Thus this FA accepting all the strings of the given RE language." }, { "code": null, "e": 25840, "s": 25703, "text": "Regular Expression 3: ‘(a+b)*’ (‘a’ union ‘b’ but substring ‘a+b’ can be repeated any number of times). The language of the given RE is," }, { "code": null, "e": 25886, "s": 25840, "text": "L3 = {ε, a, b, aa, aaab, bbbbb, ba, .......} " }, { "code": null, "e": 26336, "s": 25886, "text": "The language containing ε and any number of ‘a’ or ‘b’ or both combined.Its finite automata will be like below-In the above transition diagram, as we can see that state ‘X’ on getting ‘a’ as the input it remains in the state of itself and on getting ‘b’ as the input it transits to an another final state ‘Y’ which on getting ‘b’ or ‘a’ as the input it remains in the state of itself. Thus this FA accepting all the strings of the given RE language." }, { "code": null, "e": 26510, "s": 26336, "text": "Note – The minimal DFA of regular expression (a+b)* will have only single state, which is both starting and final state. This will contain only loop of alphabet ‘a’ and ‘b’." }, { "code": null, "e": 26653, "s": 26510, "text": "Regular Expression 4: ‘(ab+ba)*’ (‘ab’ union ‘ba’ but substring ‘ab+ba’ can be repeated any number of times). The language of the given RE is," }, { "code": null, "e": 26700, "s": 26653, "text": "L4 = {ε, ab, abab, abba, ba, baba, ........ } " }, { "code": null, "e": 26814, "s": 26700, "text": "The language containing ε and any number of ‘ab’ or ‘ba’ or both combined.Its finite automata will be like below-" }, { "code": null, "e": 27087, "s": 26814, "text": "In the above transition diagram, the initial and final state ‘X’ on getting ‘a’ as input it go to a state ‘Y’ and on getting ‘b’ as the input it go to an another state ‘Z’ and so on for the remaining states. Thus this FA accepting all the strings of the given RE language." }, { "code": null, "e": 27178, "s": 27087, "text": "Regular Expression 5: ‘a+’ (Any number of ‘a’ excluding ε).The language of the given RE is" }, { "code": null, "e": 27214, "s": 27178, "text": "L5 = {a, aa, aaa, aaaa, .........} " }, { "code": null, "e": 27499, "s": 27214, "text": "Its finite automata will be like below-In the above transition diagram, initial state ‘X’ on getting ‘a’ as the input it transits to a final state ‘Y’ which on getting ‘a’ as the input it remains in the state of itself. Thus this FA accepting all the strings of the given RE language." }, { "code": null, "e": 27507, "s": 27499, "text": "GATE CS" }, { "code": null, "e": 27540, "s": 27507, "text": "Theory of Computation & Automata" }, { "code": null, "e": 27638, "s": 27540, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27647, "s": 27638, "text": "Comments" }, { "code": null, "e": 27660, "s": 27647, "text": "Old Comments" }, { "code": null, "e": 27709, "s": 27660, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 27741, "s": 27709, "text": "Differences between TCP and UDP" }, { "code": null, "e": 27779, "s": 27741, "text": "Semaphores in Process Synchronization" }, { "code": null, "e": 27818, "s": 27779, "text": "Data encryption standard (DES) | Set 1" }, { "code": null, "e": 27843, "s": 27818, "text": "LRU Cache Implementation" }, { "code": null, "e": 27874, "s": 27843, "text": "Difference between DFA and NFA" }, { "code": null, "e": 27896, "s": 27874, "text": "Turing Machine in TOC" }, { "code": null, "e": 27947, "s": 27896, "text": "Difference between Mealy machine and Moore machine" }, { "code": null, "e": 27974, "s": 27947, "text": "Conversion from NFA to DFA" } ]
Selenium WebDriver Error: AttributeError: 'list' object has no attribute 'click'
We can get the Selenium webdriver error: AttributeError: 'list' object has no attribute 'click' while working on a test. Let us see an example of code where we have encountered such an error. Code Implementation from selenium import webdriver driver = webdriver.Chrome(executable_path='../drivers/chromedriver') #implicit wait driver.implicitly_wait(0.5) #url launch driver.get("https://www.tutorialspoint.com/index.htm") #identify an element m = driver.find_elements_by_name('search') m.click() #browser quit driver.quit() In the above code, we have got the error as we have used find_elements_by_name instead of find_element_by_name to perform a click operation on a single element. The method find_elements_by_name returns a list of elements. Here, we want to perform click operation on an element, so the webdriver fails to identify the element on which it should perform the click. In this scenario, if we want to use the find_elements_by_name method, we have to explicitly mention the index of the element to be clicked. Code Implementation from selenium import webdriver driver = webdriver.Chrome(executable_path='../drivers/chromedriver') #implicit wait driver.implicitly_wait(0.5) #url launch driver.get("https://www.tutorialspoint.com/index.htm") #identify an element with find_element_by_name m = driver.find_element_by_name('search') m.click() m.send_keys('Selenium') s = m.get_attribute('value') print('Value entered: ' + s) #browser quit driver.quit()
[ { "code": null, "e": 1254, "s": 1062, "text": "We can get the Selenium webdriver error: AttributeError: 'list' object has no attribute 'click' while working on a test. Let us see an example of code where we have encountered such an error." }, { "code": null, "e": 1274, "s": 1254, "text": "Code Implementation" }, { "code": null, "e": 1586, "s": 1274, "text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#implicit wait\ndriver.implicitly_wait(0.5)\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#identify an element\nm = driver.find_elements_by_name('search')\nm.click()\n#browser quit\ndriver.quit()" }, { "code": null, "e": 1808, "s": 1586, "text": "In the above code, we have got the error as we have used find_elements_by_name instead of find_element_by_name to perform a click operation on a single element. The method find_elements_by_name returns a list of elements." }, { "code": null, "e": 2089, "s": 1808, "text": "Here, we want to perform click operation on an element, so the webdriver fails to identify the element on which it should perform the click. In this scenario, if we want to use the find_elements_by_name method, we have to explicitly mention the index of the element to be clicked." }, { "code": null, "e": 2109, "s": 2089, "text": "Code Implementation" }, { "code": null, "e": 2528, "s": 2109, "text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#implicit wait\ndriver.implicitly_wait(0.5)\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#identify an element with find_element_by_name\nm = driver.find_element_by_name('search')\nm.click()\nm.send_keys('Selenium')\ns = m.get_attribute('value')\nprint('Value entered: ' + s)\n#browser quit\ndriver.quit()" } ]
Convert decimal fraction to binary number - GeeksforGeeks
01 Jun, 2021 Given a fraction decimal number n and integer k, convert decimal number n into equivalent binary number up-to k precision after decimal point. Examples: Input: n = 2.47, k = 5 Output: 10.01111 Input: n = 6.986 k = 8 Output: 110.11111100 A) Convert the integral part of decimal to binary equivalent Divide the decimal number by 2 and store remainders in array. Divide the quotient by 2. Repeat step 2 until we get the quotient equal to zero.Equivalent binary number would be reverse of all remainders of step 1. Divide the decimal number by 2 and store remainders in array. Divide the quotient by 2. Repeat step 2 until we get the quotient equal to zero. Equivalent binary number would be reverse of all remainders of step 1. B) Convert the fractional part of decimal to binary equivalent Multiply the fractional decimal number by 2. Integral part of resultant decimal number will be first digit of fraction binary number. Repeat step 1 using only fractional part of decimal number and then step 2. Multiply the fractional decimal number by 2. Integral part of resultant decimal number will be first digit of fraction binary number. Repeat step 1 using only fractional part of decimal number and then step 2. C) Combine both integral and fractional part of binary number.Illustration Let's take an example for n = 4.47 k = 3 Step 1: Conversion of 4 to binary 1. 4/2 : Remainder = 0 : Quotient = 2 2. 2/2 : Remainder = 0 : Quotient = 1 3. 1/2 : Remainder = 1 : Quotient = 0 So equivalent binary of integral part of decimal is 100. Step 2: Conversion of .47 to binary 1. 0.47 * 2 = 0.94, Integral part: 0 2. 0.94 * 2 = 1.88, Integral part: 1 3. 0.88 * 2 = 1.76, Integral part: 1 So equivalent binary of fractional part of decimal is .011 Step 3: Combined the result of step 1 and 2. Final answer can be written as: 100 + .011 = 100.011 Program to demonstrate above steps: C++ Java Python3 C# PHP Javascript // C++ program to convert fractional decimal// to binary number#include<bits/stdc++.h>using namespace std; // Function to convert decimal to binary upto// k-precision after decimal pointstring decimalToBinary(double num, int k_prec){ string binary = ""; // Fetch the integral part of decimal number int Integral = num; // Fetch the fractional part decimal number double fractional = num - Integral; // Conversion of integral part to // binary equivalent while (Integral) { int rem = Integral % 2; // Append 0 in binary binary.push_back(rem +'0'); Integral /= 2; } // Reverse string to get original binary // equivalent reverse(binary.begin(),binary.end()); // Append point before conversion of // fractional part binary.push_back('.'); // Conversion of fractional part to // binary equivalent while (k_prec--) { // Find next bit in fraction fractional *= 2; int fract_bit = fractional; if (fract_bit == 1) { fractional -= fract_bit; binary.push_back(1 + '0'); } else binary.push_back(0 + '0'); } return binary;} // Driver codeint main(){ double n = 4.47; int k = 3; cout << decimalToBinary(n, k) << "\n"; n = 6.986 , k = 5; cout << decimalToBinary(n, k); return 0;} // Java program to convert fractional decimal// to binary numberimport java.util.*; class GFG{ // Function to convert decimal to binary upto // k-precision after decimal point static String decimalToBinary(double num, int k_prec) { String binary = ""; // Fetch the integral part of decimal number int Integral = (int) num; // Fetch the fractional part decimal number double fractional = num - Integral; // Conversion of integral part to // binary equivalent while (Integral > 0) { int rem = Integral % 2; // Append 0 in binary binary += ((char)(rem + '0')); Integral /= 2; } // Reverse string to get original binary // equivalent binary = reverse(binary); // Append point before conversion of // fractional part binary += ('.'); // Conversion of fractional part to // binary equivalent while (k_prec-- > 0) { // Find next bit in fraction fractional *= 2; int fract_bit = (int) fractional; if (fract_bit == 1) { fractional -= fract_bit; binary += (char)(1 + '0'); } else { binary += (char)(0 + '0'); } } return binary; } static String reverse(String input) { char[] temparray = input.toCharArray(); int left, right = 0; right = temparray.length - 1; for (left = 0; left < right; left++, right--) { // Swap values of left and right char temp = temparray[left]; temparray[left] = temparray[right]; temparray[right] = temp; } return String.valueOf(temparray); } // Driver code public static void main(String[] args) { double n = 4.47; int k = 3; System.out.println(decimalToBinary(n, k)); n = 6.986; k = 5; System.out.println(decimalToBinary(n, k)); }} // This code contributed by Rajput-Ji # Python3 program to convert fractional# decimal to binary number # Function to convert decimal to binary# upto k-precision after decimal pointdef decimalToBinary(num, k_prec) : binary = "" # Fetch the integral part of # decimal number Integral = int(num) # Fetch the fractional part # decimal number fractional = num - Integral # Conversion of integral part to # binary equivalent while (Integral) : rem = Integral % 2 # Append 0 in binary binary += str(rem); Integral //= 2 # Reverse string to get original # binary equivalent binary = binary[ : : -1] # Append point before conversion # of fractional part binary += '.' # Conversion of fractional part # to binary equivalent while (k_prec) : # Find next bit in fraction fractional *= 2 fract_bit = int(fractional) if (fract_bit == 1) : fractional -= fract_bit binary += '1' else : binary += '0' k_prec -= 1 return binary # Driver codeif __name__ == "__main__" : n = 4.47 k = 3 print(decimalToBinary(n, k)) n = 6.986 k = 5 print(decimalToBinary(n, k)) # This code is contributed by Ryuga // C# program to convert fractional decimal// to binary numberusing System; class GFG{ // Function to convert decimal to binary upto // k-precision after decimal point static String decimalToBinary(double num, int k_prec) { String binary = ""; // Fetch the integral part of decimal number int Integral = (int) num; // Fetch the fractional part decimal number double fractional = num - Integral; // Conversion of integral part to // binary equivalent while (Integral > 0) { int rem = Integral % 2; // Append 0 in binary binary += ((char)(rem + '0')); Integral /= 2; } // Reverse string to get original binary // equivalent binary = reverse(binary); // Append point before conversion of // fractional part binary += ('.'); // Conversion of fractional part to // binary equivalent while (k_prec-- > 0) { // Find next bit in fraction fractional *= 2; int fract_bit = (int) fractional; if (fract_bit == 1) { fractional -= fract_bit; binary += (char)(1 + '0'); } else { binary += (char)(0 + '0'); } } return binary; } static String reverse(String input) { char[] temparray = input.ToCharArray(); int left, right = 0; right = temparray.Length - 1; for (left = 0; left < right; left++, right--) { // Swap values of left and right char temp = temparray[left]; temparray[left] = temparray[right]; temparray[right] = temp; } return String.Join("",temparray); } // Driver code public static void Main(String[] args) { double n = 4.47; int k = 3; Console.WriteLine(decimalToBinary(n, k)); n = 6.986; k = 5; Console.WriteLine(decimalToBinary(n, k)); }} // This code has been contributed by 29AjayKumar <?php// PHP program to convert fractional decimal// to binary number // Function to convert decimal to binary upto// k-precision after decimal pointfunction decimalToBinary($num, $k_prec){ $binary = ""; // Fetch the integral part of decimal number $Integral = (int)($num); // Fetch the fractional part decimal number $fractional = $num - $Integral; // Conversion of integral part to // binary equivalent while ($Integral) { $rem = $Integral % 2; // Append 0 in binary $binary.=chr($rem + 48 ); $Integral = (int)($Integral/2); } // Reverse string to get original binary // equivalent $binary=strrev($binary); // Append point before conversion of // fractional part $binary.='.'; // Conversion of fractional part to // binary equivalent while ($k_prec--) { // Find next bit in fraction $fractional *= 2; $fract_bit = (int)$fractional; if ($fract_bit == 1) { $fractional -= $fract_bit; $binary.=chr(1 + 48 ); } else $binary.=chr(0 + 48 ); } return $binary;} // Driver code $n = 4.47; $k = 3; echo decimalToBinary($n, $k)."\n"; $n = 6.986; $k = 5; echo decimalToBinary($n, $k); // This code is contributed by mits?> <script> // JavaScript program to convert fractional // decimal to binary number // Function to convert decimal to binary upto // k-precision after decimal point function decimalToBinary(num, k_prec) { let binary = ""; // Fetch the integral part of decimal number let Integral = parseInt(num, 10); // Fetch the fractional part decimal number let fractional = num - Integral; // Conversion of integral part to // binary equivalent while (Integral > 0) { let rem = Integral % 2; // Append 0 in binary binary += (String.fromCharCode(rem + '0'.charCodeAt())); Integral = parseInt(Integral / 2, 10); } // Reverse string to get original binary // equivalent binary = reverse(binary); // Append point before conversion of // fractional part binary += ('.'); // Conversion of fractional part to // binary equivalent while (k_prec-- > 0) { // Find next bit in fraction fractional *= 2; let fract_bit = parseInt(fractional, 10); if (fract_bit == 1) { fractional -= fract_bit; binary += String.fromCharCode(1 + '0'.charCodeAt()); } else { binary += String.fromCharCode(0 + '0'.charCodeAt()); } } return binary; } function reverse(input) { let temparray = input.split(''); let left, right = 0; right = temparray.length - 1; for (left = 0; left < right; left++, right--) { // Swap values of left and right let temp = temparray[left]; temparray[left] = temparray[right]; temparray[right] = temp; } return temparray.join(""); } let n = 4.47; let k = 3; document.write(decimalToBinary(n, k) + "</br>"); n = 6.986; k = 5; document.write(decimalToBinary(n, k)); </script> Output: 100.011 110.11111 Time complexity: O(len(n)) Auxiliary space: O(len(n)) where len() is the total digits contain in number n.Convert Binary fraction to DecimalReference: http://cs.furman.edu/digitaldomain/more/ch6/dec_frac_to_bin.htm http://www.cquestions.com/2011/07/c-program-for-fractional-decimal-to.htmlThis article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ankthon Mithun Kumar Rajput-Ji 29AjayKumar nidhi_biet divyeshrabadiya07 binary-representation Fraction Bit Magic Strings Strings Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Cyclic Redundancy Check and Modulo-2 Division Little and Big Endian Mystery Program to find whether a given number is power of 2 Binary representation of a given number Bits manipulation (Important tactics) Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 24932, "s": 24904, "text": "\n01 Jun, 2021" }, { "code": null, "e": 25087, "s": 24932, "text": "Given a fraction decimal number n and integer k, convert decimal number n into equivalent binary number up-to k precision after decimal point. Examples: " }, { "code": null, "e": 25172, "s": 25087, "text": "Input: n = 2.47, k = 5\nOutput: 10.01111\n\nInput: n = 6.986 k = 8\nOutput: 110.11111100" }, { "code": null, "e": 25237, "s": 25174, "text": "A) Convert the integral part of decimal to binary equivalent " }, { "code": null, "e": 25450, "s": 25237, "text": "Divide the decimal number by 2 and store remainders in array. Divide the quotient by 2. Repeat step 2 until we get the quotient equal to zero.Equivalent binary number would be reverse of all remainders of step 1." }, { "code": null, "e": 25513, "s": 25450, "text": "Divide the decimal number by 2 and store remainders in array. " }, { "code": null, "e": 25540, "s": 25513, "text": "Divide the quotient by 2. " }, { "code": null, "e": 25595, "s": 25540, "text": "Repeat step 2 until we get the quotient equal to zero." }, { "code": null, "e": 25666, "s": 25595, "text": "Equivalent binary number would be reverse of all remainders of step 1." }, { "code": null, "e": 25731, "s": 25666, "text": "B) Convert the fractional part of decimal to binary equivalent " }, { "code": null, "e": 25943, "s": 25731, "text": "Multiply the fractional decimal number by 2. Integral part of resultant decimal number will be first digit of fraction binary number. Repeat step 1 using only fractional part of decimal number and then step 2. " }, { "code": null, "e": 25989, "s": 25943, "text": "Multiply the fractional decimal number by 2. " }, { "code": null, "e": 26079, "s": 25989, "text": "Integral part of resultant decimal number will be first digit of fraction binary number. " }, { "code": null, "e": 26157, "s": 26079, "text": "Repeat step 1 using only fractional part of decimal number and then step 2. " }, { "code": null, "e": 26234, "s": 26157, "text": "C) Combine both integral and fractional part of binary number.Illustration " }, { "code": null, "e": 26790, "s": 26234, "text": "Let's take an example for n = 4.47 k = 3\n\nStep 1: Conversion of 4 to binary\n1. 4/2 : Remainder = 0 : Quotient = 2\n2. 2/2 : Remainder = 0 : Quotient = 1\n3. 1/2 : Remainder = 1 : Quotient = 0\n\nSo equivalent binary of integral part of decimal is 100.\n\nStep 2: Conversion of .47 to binary\n1. 0.47 * 2 = 0.94, Integral part: 0\n2. 0.94 * 2 = 1.88, Integral part: 1\n3. 0.88 * 2 = 1.76, Integral part: 1\n\nSo equivalent binary of fractional part of decimal is .011\n\nStep 3: Combined the result of step 1 and 2.\n\nFinal answer can be written as:\n100 + .011 = 100.011" }, { "code": null, "e": 26828, "s": 26790, "text": "Program to demonstrate above steps: " }, { "code": null, "e": 26832, "s": 26828, "text": "C++" }, { "code": null, "e": 26837, "s": 26832, "text": "Java" }, { "code": null, "e": 26845, "s": 26837, "text": "Python3" }, { "code": null, "e": 26848, "s": 26845, "text": "C#" }, { "code": null, "e": 26852, "s": 26848, "text": "PHP" }, { "code": null, "e": 26863, "s": 26852, "text": "Javascript" }, { "code": "// C++ program to convert fractional decimal// to binary number#include<bits/stdc++.h>using namespace std; // Function to convert decimal to binary upto// k-precision after decimal pointstring decimalToBinary(double num, int k_prec){ string binary = \"\"; // Fetch the integral part of decimal number int Integral = num; // Fetch the fractional part decimal number double fractional = num - Integral; // Conversion of integral part to // binary equivalent while (Integral) { int rem = Integral % 2; // Append 0 in binary binary.push_back(rem +'0'); Integral /= 2; } // Reverse string to get original binary // equivalent reverse(binary.begin(),binary.end()); // Append point before conversion of // fractional part binary.push_back('.'); // Conversion of fractional part to // binary equivalent while (k_prec--) { // Find next bit in fraction fractional *= 2; int fract_bit = fractional; if (fract_bit == 1) { fractional -= fract_bit; binary.push_back(1 + '0'); } else binary.push_back(0 + '0'); } return binary;} // Driver codeint main(){ double n = 4.47; int k = 3; cout << decimalToBinary(n, k) << \"\\n\"; n = 6.986 , k = 5; cout << decimalToBinary(n, k); return 0;}", "e": 28235, "s": 26863, "text": null }, { "code": "// Java program to convert fractional decimal// to binary numberimport java.util.*; class GFG{ // Function to convert decimal to binary upto // k-precision after decimal point static String decimalToBinary(double num, int k_prec) { String binary = \"\"; // Fetch the integral part of decimal number int Integral = (int) num; // Fetch the fractional part decimal number double fractional = num - Integral; // Conversion of integral part to // binary equivalent while (Integral > 0) { int rem = Integral % 2; // Append 0 in binary binary += ((char)(rem + '0')); Integral /= 2; } // Reverse string to get original binary // equivalent binary = reverse(binary); // Append point before conversion of // fractional part binary += ('.'); // Conversion of fractional part to // binary equivalent while (k_prec-- > 0) { // Find next bit in fraction fractional *= 2; int fract_bit = (int) fractional; if (fract_bit == 1) { fractional -= fract_bit; binary += (char)(1 + '0'); } else { binary += (char)(0 + '0'); } } return binary; } static String reverse(String input) { char[] temparray = input.toCharArray(); int left, right = 0; right = temparray.length - 1; for (left = 0; left < right; left++, right--) { // Swap values of left and right char temp = temparray[left]; temparray[left] = temparray[right]; temparray[right] = temp; } return String.valueOf(temparray); } // Driver code public static void main(String[] args) { double n = 4.47; int k = 3; System.out.println(decimalToBinary(n, k)); n = 6.986; k = 5; System.out.println(decimalToBinary(n, k)); }} // This code contributed by Rajput-Ji", "e": 30350, "s": 28235, "text": null }, { "code": "# Python3 program to convert fractional# decimal to binary number # Function to convert decimal to binary# upto k-precision after decimal pointdef decimalToBinary(num, k_prec) : binary = \"\" # Fetch the integral part of # decimal number Integral = int(num) # Fetch the fractional part # decimal number fractional = num - Integral # Conversion of integral part to # binary equivalent while (Integral) : rem = Integral % 2 # Append 0 in binary binary += str(rem); Integral //= 2 # Reverse string to get original # binary equivalent binary = binary[ : : -1] # Append point before conversion # of fractional part binary += '.' # Conversion of fractional part # to binary equivalent while (k_prec) : # Find next bit in fraction fractional *= 2 fract_bit = int(fractional) if (fract_bit == 1) : fractional -= fract_bit binary += '1' else : binary += '0' k_prec -= 1 return binary # Driver codeif __name__ == \"__main__\" : n = 4.47 k = 3 print(decimalToBinary(n, k)) n = 6.986 k = 5 print(decimalToBinary(n, k)) # This code is contributed by Ryuga", "e": 31636, "s": 30350, "text": null }, { "code": "// C# program to convert fractional decimal// to binary numberusing System; class GFG{ // Function to convert decimal to binary upto // k-precision after decimal point static String decimalToBinary(double num, int k_prec) { String binary = \"\"; // Fetch the integral part of decimal number int Integral = (int) num; // Fetch the fractional part decimal number double fractional = num - Integral; // Conversion of integral part to // binary equivalent while (Integral > 0) { int rem = Integral % 2; // Append 0 in binary binary += ((char)(rem + '0')); Integral /= 2; } // Reverse string to get original binary // equivalent binary = reverse(binary); // Append point before conversion of // fractional part binary += ('.'); // Conversion of fractional part to // binary equivalent while (k_prec-- > 0) { // Find next bit in fraction fractional *= 2; int fract_bit = (int) fractional; if (fract_bit == 1) { fractional -= fract_bit; binary += (char)(1 + '0'); } else { binary += (char)(0 + '0'); } } return binary; } static String reverse(String input) { char[] temparray = input.ToCharArray(); int left, right = 0; right = temparray.Length - 1; for (left = 0; left < right; left++, right--) { // Swap values of left and right char temp = temparray[left]; temparray[left] = temparray[right]; temparray[right] = temp; } return String.Join(\"\",temparray); } // Driver code public static void Main(String[] args) { double n = 4.47; int k = 3; Console.WriteLine(decimalToBinary(n, k)); n = 6.986; k = 5; Console.WriteLine(decimalToBinary(n, k)); }} // This code has been contributed by 29AjayKumar", "e": 33767, "s": 31636, "text": null }, { "code": "<?php// PHP program to convert fractional decimal// to binary number // Function to convert decimal to binary upto// k-precision after decimal pointfunction decimalToBinary($num, $k_prec){ $binary = \"\"; // Fetch the integral part of decimal number $Integral = (int)($num); // Fetch the fractional part decimal number $fractional = $num - $Integral; // Conversion of integral part to // binary equivalent while ($Integral) { $rem = $Integral % 2; // Append 0 in binary $binary.=chr($rem + 48 ); $Integral = (int)($Integral/2); } // Reverse string to get original binary // equivalent $binary=strrev($binary); // Append point before conversion of // fractional part $binary.='.'; // Conversion of fractional part to // binary equivalent while ($k_prec--) { // Find next bit in fraction $fractional *= 2; $fract_bit = (int)$fractional; if ($fract_bit == 1) { $fractional -= $fract_bit; $binary.=chr(1 + 48 ); } else $binary.=chr(0 + 48 ); } return $binary;} // Driver code $n = 4.47; $k = 3; echo decimalToBinary($n, $k).\"\\n\"; $n = 6.986; $k = 5; echo decimalToBinary($n, $k); // This code is contributed by mits?>", "e": 35089, "s": 33767, "text": null }, { "code": "<script> // JavaScript program to convert fractional // decimal to binary number // Function to convert decimal to binary upto // k-precision after decimal point function decimalToBinary(num, k_prec) { let binary = \"\"; // Fetch the integral part of decimal number let Integral = parseInt(num, 10); // Fetch the fractional part decimal number let fractional = num - Integral; // Conversion of integral part to // binary equivalent while (Integral > 0) { let rem = Integral % 2; // Append 0 in binary binary += (String.fromCharCode(rem + '0'.charCodeAt())); Integral = parseInt(Integral / 2, 10); } // Reverse string to get original binary // equivalent binary = reverse(binary); // Append point before conversion of // fractional part binary += ('.'); // Conversion of fractional part to // binary equivalent while (k_prec-- > 0) { // Find next bit in fraction fractional *= 2; let fract_bit = parseInt(fractional, 10); if (fract_bit == 1) { fractional -= fract_bit; binary += String.fromCharCode(1 + '0'.charCodeAt()); } else { binary += String.fromCharCode(0 + '0'.charCodeAt()); } } return binary; } function reverse(input) { let temparray = input.split(''); let left, right = 0; right = temparray.length - 1; for (left = 0; left < right; left++, right--) { // Swap values of left and right let temp = temparray[left]; temparray[left] = temparray[right]; temparray[right] = temp; } return temparray.join(\"\"); } let n = 4.47; let k = 3; document.write(decimalToBinary(n, k) + \"</br>\"); n = 6.986; k = 5; document.write(decimalToBinary(n, k)); </script>", "e": 37231, "s": 35089, "text": null }, { "code": null, "e": 37241, "s": 37231, "text": "Output: " }, { "code": null, "e": 37259, "s": 37241, "text": "100.011\n110.11111" }, { "code": null, "e": 37970, "s": 37259, "text": "Time complexity: O(len(n)) Auxiliary space: O(len(n)) where len() is the total digits contain in number n.Convert Binary fraction to DecimalReference: http://cs.furman.edu/digitaldomain/more/ch6/dec_frac_to_bin.htm http://www.cquestions.com/2011/07/c-program-for-fractional-decimal-to.htmlThis article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 37978, "s": 37970, "text": "ankthon" }, { "code": null, "e": 37991, "s": 37978, "text": "Mithun Kumar" }, { "code": null, "e": 38001, "s": 37991, "text": "Rajput-Ji" }, { "code": null, "e": 38013, "s": 38001, "text": "29AjayKumar" }, { "code": null, "e": 38024, "s": 38013, "text": "nidhi_biet" }, { "code": null, "e": 38042, "s": 38024, "text": "divyeshrabadiya07" }, { "code": null, "e": 38064, "s": 38042, "text": "binary-representation" }, { "code": null, "e": 38073, "s": 38064, "text": "Fraction" }, { "code": null, "e": 38083, "s": 38073, "text": "Bit Magic" }, { "code": null, "e": 38091, "s": 38083, "text": "Strings" }, { "code": null, "e": 38099, "s": 38091, "text": "Strings" }, { "code": null, "e": 38109, "s": 38099, "text": "Bit Magic" }, { "code": null, "e": 38207, "s": 38109, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38253, "s": 38207, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 38283, "s": 38253, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 38336, "s": 38283, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 38376, "s": 38336, "text": "Binary representation of a given number" }, { "code": null, "e": 38414, "s": 38376, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 38439, "s": 38414, "text": "Reverse a string in Java" }, { "code": null, "e": 38485, "s": 38439, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 38519, "s": 38485, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 38579, "s": 38519, "text": "Write a program to print all permutations of a given string" } ]
Why main() method must be static in java?
Static − If you declare a method, subclass, block, or a variable static it is loaded along with the class. In Java whenever we need to call an (instance) method we should instantiate the class (containing it) and call it. If we need to call a method without instantiation it should be static. Moreover, static methods are loaded into the memory along with the class. In the case of the main method, it is invoked by the JVM directly, so it is not possible to call it by instantiating its class. And, it should be loaded into the memory along with the class and be available for execution. Therefore, the main method should be static. The public static void main(String ar[]) method is the entry point of the execution in Java. When we run a .class file JVM searches for the main method and executes the contents of it line by line. You can write the main method in your program without the static modifier, the program gets compiled without compilation errors. But, at the time of execution JVM does not consider this new method (without static) as the entry point of the program. It searches for the main method which is public, static, with return type void, and a String array as an argument. public static int main(String[] args){ } If such a method is not found, a run time error is generated. In the following Java program in the class Sample, we have a main method which is public, returns nothing (void), and accepts a String array as an argument. But, not static. Live Demo import java.util.Scanner; public class Sample{ public void main(String[] args){ System.out.println("This is a sample program"); } } On executing, this program generates the following error − Error: Main method is not static in class Sample, please define the main method as:public static void main(String[] args)
[ { "code": null, "e": 1169, "s": 1062, "text": "Static − If you declare a method, subclass, block, or a variable static it is loaded along with the class." }, { "code": null, "e": 1429, "s": 1169, "text": "In Java whenever we need to call an (instance) method we should instantiate the class (containing it) and call it. If we need to call a method without instantiation it should be static. Moreover, static methods are loaded into the memory along with the class." }, { "code": null, "e": 1696, "s": 1429, "text": "In the case of the main method, it is invoked by the JVM directly, so it is not possible to call it by instantiating its class. And, it should be loaded into the memory along with the class and be available for execution. Therefore, the main method should be static." }, { "code": null, "e": 1894, "s": 1696, "text": "The public static void main(String ar[]) method is the entry point of the execution in Java. When we run a .class file JVM searches for the main method and executes the contents of it line by line." }, { "code": null, "e": 2143, "s": 1894, "text": "You can write the main method in your program without the static modifier, the program gets compiled without compilation errors. But, at the time of execution JVM does not consider this new method (without static) as the entry point of the program." }, { "code": null, "e": 2258, "s": 2143, "text": "It searches for the main method which is public, static, with return type void, and a String array as an argument." }, { "code": null, "e": 2299, "s": 2258, "text": "public static int main(String[] args){\n}" }, { "code": null, "e": 2361, "s": 2299, "text": "If such a method is not found, a run time error is generated." }, { "code": null, "e": 2535, "s": 2361, "text": "In the following Java program in the class Sample, we have a main method which is public, returns nothing (void), and accepts a String array as an argument. But, not static." }, { "code": null, "e": 2546, "s": 2535, "text": " Live Demo" }, { "code": null, "e": 2690, "s": 2546, "text": "import java.util.Scanner;\npublic class Sample{\n public void main(String[] args){\n System.out.println(\"This is a sample program\");\n }\n}" }, { "code": null, "e": 2749, "s": 2690, "text": "On executing, this program generates the following error −" }, { "code": null, "e": 2871, "s": 2749, "text": "Error: Main method is not static in class Sample, please define the main method\nas:public static void main(String[] args)" } ]
Practical AI : Automatically Generate Multiple Choice Questions (MCQs) from any content with BERT Summarizer, Wordnet and Conceptnet | by Ramsri Goutham | Towards Data Science
If you want to try a live demo of MCQ generation in action, please visit https://questgen.ai/ In this post we will see how to automatically generate Multiple Choice Questions (MCQs) from any story or article. This is one step towards automatically generating those MCQs you see in Middle school/ High school. Input: The input to our program will be an article (example article provided in the github repository below) like the following — The Greek historian knew what he was talking about. The Nile River fed Egyptian civilization for hundreds of years. The Longest River the Nile is 4,160 miles long — the world’s longest river. It begins near the equator in Africa and flows north to the Mediterranean Sea .............. Output: The output will be a set of automatically generated MCQs with efficient distractors (wrong answer choices) - 1) The Nile provided so well for _______ that sometimes they had surpluses, or more goods than they needed. a ) Angolan b ) Algerian c ) Egyptians d ) BantuMore options: ['Basotho', 'Beninese', 'Berber', 'Black African', 'Burundian', 'Cameroonian', 'Carthaginian', 'Chadian', 'Chewa', 'Congolese', 'Djiboutian', 'Egyptian', 'Ethiopian', 'Eurafrican', 'Ewe', 'Fulani'] 2) As in many ancient societies, much of the knowledge of _______ came about as priests studied the world to find ways to please the gods. a ) Malawi b ) East Africa c ) Somalia d ) EgyptMore options: ['Togo', 'Zimbabwe', 'Gabon', 'Ghana', 'Lake Tanganyika', 'Ottoman Empire', 'Mozambique', 'Iran', 'Israel', 'Saudi Arabia', 'Lebanon', 'Turkey', 'Iraq', 'Levant', 'Syria', 'Jordan'] 3) The _______ provided so well for Egyptians that sometimes they had surpluses, or more goods than they needed. a ) Nyala b ) Omdurman c ) Nile d ) Port SudanMore options: ['Khartoum', 'Nubian Desert', 'Darfur', 'Libyan Desert', 'Kordofan', 'Gulu', 'Buganda', 'Entebbe', 'Jinja', 'Lake Edward', 'entebbe', 'gulu', 'kayunga', 'Upper Egypt', 'Suez Canal', 'Aswan High Dam'] Let’s get started to see how you can build your own MCQ generator leveraging state of the art NLP. If you want to try out advanced MCQ generator live, please visit https://questgen.ai/ All the code and the jupyter notebook is available at - github.com First install the necessary libraries in the jupyter notebook. If you encounter any error just play around with versions and check other incompatibilities : !pip install gensim!pip install git+https://github.com/boudinfl/pke.git!python -m spacy download en!pip install bert-extractive-summarizer --upgrade --force-reinstall!pip install spacy==2.1.3 --upgrade --force-reinstall!pip install -U nltk!pip install -U pywsdimport nltknltk.download('stopwords')nltk.download('popular') Here we use a simple library bert-extractive-summarizer that does the job for us. We load the total text from the egypt.txt file present in the Github repo and ask the library to give us summarized text. You can play with the parameters of the ratio, max and min length of sentences to be kept for summarization etc from summarizer import Summarizerf = open("egypt.txt","r")full_text = f.read()model = Summarizer()result = model(full_text, min_length=60, max_length = 500 , ratio = 0.4)summarized_text = ''.join(result)print (summarized_text) We get a summarized portion of the original text as output : The Nile River fed Egyptian civilization for hundreds of years. It begins near the equator in Africa and flows north to the Mediterranean Sea. A delta is an area near a river’s mouth where the water deposits fine soil called silt....................... We use python keyword extractor (PKE) library and extract all the important keywords from the original text. Then keep only those keywords that are present in the summarized text. Here I am only extracting nouns as they will be more suitable for MCQs. Also I am only extracting 20 keywords but you can play around with that parameter (get_n_best). The output is - Original text keywords: ['egyptians', 'nile river', 'egypt', 'nile', 'euphrates', 'tigris', 'old kingdom', 'red land', 'crown', 'upper', 'lower egypt', 'narmer', 'longest river', 'africa', 'mediterranean sea', 'hyksos', 'new kingdom', 'black land', 'ethiopia', 'middle kingdom']Keywords present in summarized text: ['egyptians', 'nile river', 'egypt', 'nile', 'old kingdom', 'red land', 'crown', 'upper', 'lower egypt', 'narmer', 'africa', 'mediterranean sea', 'new kingdom', 'middle kingdom'] For each of the keyword we will extract corresponding sentences that has the word from the summarized text. The sample output is — {'egyptians': ['The Nile provided so well for Egyptians that sometimes they had surpluses, or more goods than they needed.', 'For example, some ancient Egyptians learned to be scribes, people whose job was to write and keep records.', 'Egyptians believed that if a tomb was robbed, the person buried there could not have a happy afterlife.', 'nile river': ['The Nile River fed Egyptian civilization for hundreds of years.'], 'old kingdom': ['Historians divide ancient Egyptian dynasties into the Old Kingdom, the Middle Kingdom, and the New Kingdom.', 'The Old Kingdom started about 2575 B.C., when the Egyptian empire was gaining strength.'], } ..................... Here we get distractors (wrong answer choices) from Wordnet and Conceptnet to generate our final MCQ Questions. What are distractors (wrong answer choices) ? If let’s say “Historians divide ancient Egyptian dynasties into the Old Kingdom, the Middle Kingdom, and the New Kingdom.” is our sentence and we want to give “Egyptian” as the fill in the blank key word then the other wrong answer choices should be similar to Egyptian but not synonymous for Egyptian. Eg: Historians divide ancient __________ dynasties into the Old Kingdom, the Middle Kingdom, and the New Kingdoma)Egyptianb)Ethiopianc)Angoliand)Algerian In the above question options b) , c) and d) are distractors. How do we generate these distractors automatically ? We take two approaches one with wordnet and the other with conceptnet to get distractors. Wordnet Approach used in our code : Given input as a sentence and keyword, we get the “sense” of the word first. Let me explain with “sense” with an example. If we have a sentence “ The bat flew into the jungle and landed on a tree” and a keyword “bat”, we automatically know that here we are talking about the mammal bat that has wings not cricket bat or baseball bat. Although we humans are good at it, the algorithms are not very good at distinguishing one vs the other. This is called word sense disambiguation (WSD). In wordnet “bat” may have several senses one for cricket bat, one for flying mammal etc. So the function get_wordsense tries to get the correct sense of the word given a sentence along with it. This is not perfect all the times hence we get some errors if the algorithm narrows onto a wrong sense. Then distractors (wrong answer choices) will also be wrong. Once we identify the sense we call get_distractors_wordnet function to get distractors. What happens here is that let’s say we get a word like “cheetah” and identify its sense, we then go to its hypernym. A hypernym is a higher level category for a given word. In our example feline is hypernym for cheetah. Then we go to find all hyponyms ( sub categories) of feline which might be Leopard, Tiger, Lion all belonging to the feline group. So we can use Leopard, Tiger, Lion as distractors (wrong answer choices) for the given MCQ. Conceptnet Approach used in our code : Not all words are available in wordnet and not all have hypernyms. Hence if we fail with wordnet we look in conceptnet as well for distractors. get_distractors_conceptnet is the main function used to get distractors from conceptnet. Conceptnet doesn’t have provision to disambiguate between different word senses as we discussed above with the example of bat. Hence we need to go ahead with whatever sense conceptnet gives us when we query with a given word. Let’s see how we use conceptnet in our use case. We don’t install anything because we use the conceptnet API directly. Note that there is an hourly API rate limit so beware of it. Given a word like “California” we query conceptnet with it and retrieve the “Partof” relationship. In our example “california” is partof “United States”. Now we go to “United States” and see what other things does it share a “partof” relationship with. That would be other states like “Texas”, “Arizona”, “Seattle’ etc. Hence for our query word “California” we fetched the distractors “Texas”, “Arizona” etc Finally we generate output as follows : #############################################################################NOTE:::::::: Since the algorithm might have errors along the way, wrong answer choices generated might not be correct for some questions. #############################################################################1) The Nile provided so well for _______ that sometimes they had surpluses, or more goods than they needed. a ) Angolan b ) Algerian c ) Egyptians d ) BantuMore options: ['Basotho', 'Beninese', 'Berber', 'Black African', 'Burundian', 'Cameroonian', 'Carthaginian', 'Chadian', 'Chewa', 'Congolese', 'Djiboutian', 'Egyptian', 'Ethiopian', 'Eurafrican', 'Ewe', 'Fulani'] 2) As in many ancient societies, much of the knowledge of _______ came about as priests studied the world to find ways to please the gods. a ) Malawi b ) East Africa c ) Somalia d ) EgyptMore options: ['Togo', 'Zimbabwe', 'Gabon', 'Ghana', 'Lake Tanganyika', 'Ottoman Empire', 'Mozambique', 'Iran', 'Israel', 'Saudi Arabia', 'Lebanon', 'Turkey', 'Iraq', 'Levant', 'Syria', 'Jordan'] 3) The _______ provided so well for Egyptians that sometimes they had surpluses, or more goods than they needed. a ) Nyala b ) Omdurman c ) Nile d ) Port SudanMore options: ['Khartoum', 'Nubian Desert', 'Darfur', 'Libyan Desert', 'Kordofan', 'Gulu', 'Buganda', 'Entebbe', 'Jinja', 'Lake Edward', 'entebbe', 'gulu', 'kayunga', 'Upper Egypt', 'Suez Canal', 'Aswan High Dam'] 4) It combined the red _______ of Lower Egypt with the white _______ of Upper Egypt. a ) Capital b ) Crown c ) Masthead d ) HeadMore options: [] 5) It combined the red Crown of Lower Egypt with the white Crown of _______ Egypt. a ) Upper Berth b ) Lower Berth c ) UpperMore options: [] Note that there could be many errors either due to wrong sense of the word that is extracted from Wordnet word sense disambiguation (WSD) algorithm or conceptnet identifying it with a different sense due to its limitation. Just like “partof” relationship, there is “IsA” relationship in Conceptnet that could be further explored to get distractors. Just like “partof” relationship, there is “IsA” relationship in Conceptnet that could be further explored to get distractors. You could use these for IsA relationship - QueryUrl = “http://api.conceptnet.io/query?node=%s&rel=/r/IsA&end=%s&limit=10"%(link,link) Retrieval URL = “http://api.conceptnet.io/query?node=/c/en/%s/n&rel=/r/IsA&start=/c/en/%s&limit=5"%(word,word) 2. Since we have multiple sentences for each keyword use all of them to do word sense disambiguation (WSD) and choose the sense with the highest count. 3. Can alternatively use word vectors (word2vec, glove) as a way of distractors for a given word. 4. You can use pronoun resolution (neural coreference resolution) on the full text before passing it to BERT summarizer. Then any sentences with pronouns shall be resolved so that when presented as MCQ it looks complete and independent. I am running a 4-week cohort-based course on “Practical Introduction to NLP” with Maven, the world’s best platform for cohort-based learning. If you wish to transform yourself from a Python developer to a junior NLP developer with practical project experience in 4 weeks, grab your spot now! I launched a very interesting Udemy course titled “Question generation using NLP” expanding on some of the techniques discussed in this blog post. If you would like to take a look at it, here is the link.
[ { "code": null, "e": 141, "s": 47, "text": "If you want to try a live demo of MCQ generation in action, please visit https://questgen.ai/" }, { "code": null, "e": 356, "s": 141, "text": "In this post we will see how to automatically generate Multiple Choice Questions (MCQs) from any story or article. This is one step towards automatically generating those MCQs you see in Middle school/ High school." }, { "code": null, "e": 486, "s": 356, "text": "Input: The input to our program will be an article (example article provided in the github repository below) like the following —" }, { "code": null, "e": 771, "s": 486, "text": "The Greek historian knew what he was talking about. The Nile River fed Egyptian civilization for hundreds of years. The Longest River the Nile is 4,160 miles long — the world’s longest river. It begins near the equator in Africa and flows north to the Mediterranean Sea .............." }, { "code": null, "e": 888, "s": 771, "text": "Output: The output will be a set of automatically generated MCQs with efficient distractors (wrong answer choices) -" }, { "code": null, "e": 2057, "s": 888, "text": "1) The Nile provided so well for _______ that sometimes they had surpluses, or more goods than they needed.\t a ) Angolan\t b ) Algerian\t c ) Egyptians\t d ) BantuMore options: ['Basotho', 'Beninese', 'Berber', 'Black African', 'Burundian', 'Cameroonian', 'Carthaginian', 'Chadian', 'Chewa', 'Congolese', 'Djiboutian', 'Egyptian', 'Ethiopian', 'Eurafrican', 'Ewe', 'Fulani'] 2) As in many ancient societies, much of the knowledge of _______ came about as priests studied the world to find ways to please the gods.\t a ) Malawi\t b ) East Africa\t c ) Somalia\t d ) EgyptMore options: ['Togo', 'Zimbabwe', 'Gabon', 'Ghana', 'Lake Tanganyika', 'Ottoman Empire', 'Mozambique', 'Iran', 'Israel', 'Saudi Arabia', 'Lebanon', 'Turkey', 'Iraq', 'Levant', 'Syria', 'Jordan'] 3) The _______ provided so well for Egyptians that sometimes they had surpluses, or more goods than they needed.\t a ) Nyala\t b ) Omdurman\t c ) Nile\t d ) Port SudanMore options: ['Khartoum', 'Nubian Desert', 'Darfur', 'Libyan Desert', 'Kordofan', 'Gulu', 'Buganda', 'Entebbe', 'Jinja', 'Lake Edward', 'entebbe', 'gulu', 'kayunga', 'Upper Egypt', 'Suez Canal', 'Aswan High Dam']" }, { "code": null, "e": 2156, "s": 2057, "text": "Let’s get started to see how you can build your own MCQ generator leveraging state of the art NLP." }, { "code": null, "e": 2242, "s": 2156, "text": "If you want to try out advanced MCQ generator live, please visit https://questgen.ai/" }, { "code": null, "e": 2298, "s": 2242, "text": "All the code and the jupyter notebook is available at -" }, { "code": null, "e": 2309, "s": 2298, "text": "github.com" }, { "code": null, "e": 2466, "s": 2309, "text": "First install the necessary libraries in the jupyter notebook. If you encounter any error just play around with versions and check other incompatibilities :" }, { "code": null, "e": 2788, "s": 2466, "text": "!pip install gensim!pip install git+https://github.com/boudinfl/pke.git!python -m spacy download en!pip install bert-extractive-summarizer --upgrade --force-reinstall!pip install spacy==2.1.3 --upgrade --force-reinstall!pip install -U nltk!pip install -U pywsdimport nltknltk.download('stopwords')nltk.download('popular')" }, { "code": null, "e": 3104, "s": 2788, "text": "Here we use a simple library bert-extractive-summarizer that does the job for us. We load the total text from the egypt.txt file present in the Github repo and ask the library to give us summarized text. You can play with the parameters of the ratio, max and min length of sentences to be kept for summarization etc" }, { "code": null, "e": 3331, "s": 3104, "text": "from summarizer import Summarizerf = open(\"egypt.txt\",\"r\")full_text = f.read()model = Summarizer()result = model(full_text, min_length=60, max_length = 500 , ratio = 0.4)summarized_text = ''.join(result)print (summarized_text)" }, { "code": null, "e": 3392, "s": 3331, "text": "We get a summarized portion of the original text as output :" }, { "code": null, "e": 3645, "s": 3392, "text": "The Nile River fed Egyptian civilization for hundreds of years. It begins near the equator in Africa and flows north to the Mediterranean Sea. A delta is an area near a river’s mouth where the water deposits fine soil called silt......................." }, { "code": null, "e": 3993, "s": 3645, "text": "We use python keyword extractor (PKE) library and extract all the important keywords from the original text. Then keep only those keywords that are present in the summarized text. Here I am only extracting nouns as they will be more suitable for MCQs. Also I am only extracting 20 keywords but you can play around with that parameter (get_n_best)." }, { "code": null, "e": 4009, "s": 3993, "text": "The output is -" }, { "code": null, "e": 4503, "s": 4009, "text": "Original text keywords: ['egyptians', 'nile river', 'egypt', 'nile', 'euphrates', 'tigris', 'old kingdom', 'red land', 'crown', 'upper', 'lower egypt', 'narmer', 'longest river', 'africa', 'mediterranean sea', 'hyksos', 'new kingdom', 'black land', 'ethiopia', 'middle kingdom']Keywords present in summarized text: ['egyptians', 'nile river', 'egypt', 'nile', 'old kingdom', 'red land', 'crown', 'upper', 'lower egypt', 'narmer', 'africa', 'mediterranean sea', 'new kingdom', 'middle kingdom']" }, { "code": null, "e": 4611, "s": 4503, "text": "For each of the keyword we will extract corresponding sentences that has the word from the summarized text." }, { "code": null, "e": 4634, "s": 4611, "text": "The sample output is —" }, { "code": null, "e": 5310, "s": 4634, "text": "{'egyptians': ['The Nile provided so well for Egyptians that sometimes they had surpluses, or more goods than they needed.', 'For example, some ancient Egyptians learned to be scribes, people whose job was to write and keep records.', 'Egyptians believed that if a tomb was robbed, the person buried there could not have a happy afterlife.', 'nile river': ['The Nile River fed Egyptian civilization for hundreds of years.'], 'old kingdom': ['Historians divide ancient Egyptian dynasties into the Old Kingdom, the Middle Kingdom, and the New Kingdom.', 'The Old Kingdom started about 2575 B.C., when the Egyptian empire was gaining strength.'], } ....................." }, { "code": null, "e": 5422, "s": 5310, "text": "Here we get distractors (wrong answer choices) from Wordnet and Conceptnet to generate our final MCQ Questions." }, { "code": null, "e": 5468, "s": 5422, "text": "What are distractors (wrong answer choices) ?" }, { "code": null, "e": 5771, "s": 5468, "text": "If let’s say “Historians divide ancient Egyptian dynasties into the Old Kingdom, the Middle Kingdom, and the New Kingdom.” is our sentence and we want to give “Egyptian” as the fill in the blank key word then the other wrong answer choices should be similar to Egyptian but not synonymous for Egyptian." }, { "code": null, "e": 5926, "s": 5771, "text": "Eg: Historians divide ancient __________ dynasties into the Old Kingdom, the Middle Kingdom, and the New Kingdoma)Egyptianb)Ethiopianc)Angoliand)Algerian" }, { "code": null, "e": 5988, "s": 5926, "text": "In the above question options b) , c) and d) are distractors." }, { "code": null, "e": 6041, "s": 5988, "text": "How do we generate these distractors automatically ?" }, { "code": null, "e": 6131, "s": 6041, "text": "We take two approaches one with wordnet and the other with conceptnet to get distractors." }, { "code": null, "e": 6167, "s": 6131, "text": "Wordnet Approach used in our code :" }, { "code": null, "e": 6244, "s": 6167, "text": "Given input as a sentence and keyword, we get the “sense” of the word first." }, { "code": null, "e": 7011, "s": 6244, "text": "Let me explain with “sense” with an example. If we have a sentence “ The bat flew into the jungle and landed on a tree” and a keyword “bat”, we automatically know that here we are talking about the mammal bat that has wings not cricket bat or baseball bat. Although we humans are good at it, the algorithms are not very good at distinguishing one vs the other. This is called word sense disambiguation (WSD). In wordnet “bat” may have several senses one for cricket bat, one for flying mammal etc. So the function get_wordsense tries to get the correct sense of the word given a sentence along with it. This is not perfect all the times hence we get some errors if the algorithm narrows onto a wrong sense. Then distractors (wrong answer choices) will also be wrong." }, { "code": null, "e": 7319, "s": 7011, "text": "Once we identify the sense we call get_distractors_wordnet function to get distractors. What happens here is that let’s say we get a word like “cheetah” and identify its sense, we then go to its hypernym. A hypernym is a higher level category for a given word. In our example feline is hypernym for cheetah." }, { "code": null, "e": 7542, "s": 7319, "text": "Then we go to find all hyponyms ( sub categories) of feline which might be Leopard, Tiger, Lion all belonging to the feline group. So we can use Leopard, Tiger, Lion as distractors (wrong answer choices) for the given MCQ." }, { "code": null, "e": 7581, "s": 7542, "text": "Conceptnet Approach used in our code :" }, { "code": null, "e": 8040, "s": 7581, "text": "Not all words are available in wordnet and not all have hypernyms. Hence if we fail with wordnet we look in conceptnet as well for distractors. get_distractors_conceptnet is the main function used to get distractors from conceptnet. Conceptnet doesn’t have provision to disambiguate between different word senses as we discussed above with the example of bat. Hence we need to go ahead with whatever sense conceptnet gives us when we query with a given word." }, { "code": null, "e": 8220, "s": 8040, "text": "Let’s see how we use conceptnet in our use case. We don’t install anything because we use the conceptnet API directly. Note that there is an hourly API rate limit so beware of it." }, { "code": null, "e": 8374, "s": 8220, "text": "Given a word like “California” we query conceptnet with it and retrieve the “Partof” relationship. In our example “california” is partof “United States”." }, { "code": null, "e": 8628, "s": 8374, "text": "Now we go to “United States” and see what other things does it share a “partof” relationship with. That would be other states like “Texas”, “Arizona”, “Seattle’ etc. Hence for our query word “California” we fetched the distractors “Texas”, “Arizona” etc" }, { "code": null, "e": 8668, "s": 8628, "text": "Finally we generate output as follows :" }, { "code": null, "e": 10445, "s": 8668, "text": "#############################################################################NOTE:::::::: Since the algorithm might have errors along the way, wrong answer choices generated might not be correct for some questions. #############################################################################1) The Nile provided so well for _______ that sometimes they had surpluses, or more goods than they needed.\t a ) Angolan\t b ) Algerian\t c ) Egyptians\t d ) BantuMore options: ['Basotho', 'Beninese', 'Berber', 'Black African', 'Burundian', 'Cameroonian', 'Carthaginian', 'Chadian', 'Chewa', 'Congolese', 'Djiboutian', 'Egyptian', 'Ethiopian', 'Eurafrican', 'Ewe', 'Fulani'] 2) As in many ancient societies, much of the knowledge of _______ came about as priests studied the world to find ways to please the gods.\t a ) Malawi\t b ) East Africa\t c ) Somalia\t d ) EgyptMore options: ['Togo', 'Zimbabwe', 'Gabon', 'Ghana', 'Lake Tanganyika', 'Ottoman Empire', 'Mozambique', 'Iran', 'Israel', 'Saudi Arabia', 'Lebanon', 'Turkey', 'Iraq', 'Levant', 'Syria', 'Jordan'] 3) The _______ provided so well for Egyptians that sometimes they had surpluses, or more goods than they needed.\t a ) Nyala\t b ) Omdurman\t c ) Nile\t d ) Port SudanMore options: ['Khartoum', 'Nubian Desert', 'Darfur', 'Libyan Desert', 'Kordofan', 'Gulu', 'Buganda', 'Entebbe', 'Jinja', 'Lake Edward', 'entebbe', 'gulu', 'kayunga', 'Upper Egypt', 'Suez Canal', 'Aswan High Dam'] 4) It combined the red _______ of Lower Egypt with the white _______ of Upper Egypt.\t a ) Capital\t b ) Crown\t c ) Masthead\t d ) HeadMore options: [] 5) It combined the red Crown of Lower Egypt with the white Crown of _______ Egypt.\t a ) Upper Berth\t b ) Lower Berth\t c ) UpperMore options: []" }, { "code": null, "e": 10668, "s": 10445, "text": "Note that there could be many errors either due to wrong sense of the word that is extracted from Wordnet word sense disambiguation (WSD) algorithm or conceptnet identifying it with a different sense due to its limitation." }, { "code": null, "e": 10794, "s": 10668, "text": "Just like “partof” relationship, there is “IsA” relationship in Conceptnet that could be further explored to get distractors." }, { "code": null, "e": 10920, "s": 10794, "text": "Just like “partof” relationship, there is “IsA” relationship in Conceptnet that could be further explored to get distractors." }, { "code": null, "e": 10963, "s": 10920, "text": "You could use these for IsA relationship -" }, { "code": null, "e": 11054, "s": 10963, "text": "QueryUrl = “http://api.conceptnet.io/query?node=%s&rel=/r/IsA&end=%s&limit=10\"%(link,link)" }, { "code": null, "e": 11165, "s": 11054, "text": "Retrieval URL = “http://api.conceptnet.io/query?node=/c/en/%s/n&rel=/r/IsA&start=/c/en/%s&limit=5\"%(word,word)" }, { "code": null, "e": 11317, "s": 11165, "text": "2. Since we have multiple sentences for each keyword use all of them to do word sense disambiguation (WSD) and choose the sense with the highest count." }, { "code": null, "e": 11415, "s": 11317, "text": "3. Can alternatively use word vectors (word2vec, glove) as a way of distractors for a given word." }, { "code": null, "e": 11652, "s": 11415, "text": "4. You can use pronoun resolution (neural coreference resolution) on the full text before passing it to BERT summarizer. Then any sentences with pronouns shall be resolved so that when presented as MCQ it looks complete and independent." }, { "code": null, "e": 11944, "s": 11652, "text": "I am running a 4-week cohort-based course on “Practical Introduction to NLP” with Maven, the world’s best platform for cohort-based learning. If you wish to transform yourself from a Python developer to a junior NLP developer with practical project experience in 4 weeks, grab your spot now!" } ]
Adding elements in a vector in R programming - append() method - GeeksforGeeks
10 May, 2020 append() method in R programming is used to append the different types of integer values into a vector in the last. Syntax: append(x, value, index(optional)) Return: Returns the new vector after appending given value. Example 1: x <- rep(1:5) # Using rep() methodgfg <- append(x, 10) print(gfg) Output: [1] 1 2 3 4 5 10 Example 2: x <- rep(10:15) # Using rep() methodgfg <- append(x, 1, 1) print(gfg) Output: [1] 10 1 11 12 13 14 15 R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to change Row Names of DataFrame in R ? Filter data by multiple conditions in R using Dplyr 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? K-Means Clustering in R Programming Remove rows with NA in one column of R DataFrame How to filter R DataFrame by values in a column? Replace Specific Characters in String in R
[ { "code": null, "e": 24231, "s": 24203, "text": "\n10 May, 2020" }, { "code": null, "e": 24347, "s": 24231, "text": "append() method in R programming is used to append the different types of integer values into a vector in the last." }, { "code": null, "e": 24389, "s": 24347, "text": "Syntax: append(x, value, index(optional))" }, { "code": null, "e": 24449, "s": 24389, "text": "Return: Returns the new vector after appending given value." }, { "code": null, "e": 24460, "s": 24449, "text": "Example 1:" }, { "code": "x <- rep(1:5) # Using rep() methodgfg <- append(x, 10) print(gfg)", "e": 24528, "s": 24460, "text": null }, { "code": null, "e": 24536, "s": 24528, "text": "Output:" }, { "code": null, "e": 24559, "s": 24536, "text": "[1] 1 2 3 4 5 10\n" }, { "code": null, "e": 24570, "s": 24559, "text": "Example 2:" }, { "code": "x <- rep(10:15) # Using rep() methodgfg <- append(x, 1, 1) print(gfg)", "e": 24642, "s": 24570, "text": null }, { "code": null, "e": 24650, "s": 24642, "text": "Output:" }, { "code": null, "e": 24676, "s": 24650, "text": "[1] 10 1 11 12 13 14 15\n" }, { "code": null, "e": 24687, "s": 24676, "text": "R Language" }, { "code": null, "e": 24785, "s": 24687, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24794, "s": 24785, "text": "Comments" }, { "code": null, "e": 24807, "s": 24794, "text": "Old Comments" }, { "code": null, "e": 24851, "s": 24807, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 24903, "s": 24851, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 24955, "s": 24903, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 24993, "s": 24955, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 25028, "s": 24993, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 25086, "s": 25028, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 25122, "s": 25086, "text": "K-Means Clustering in R Programming" }, { "code": null, "e": 25171, "s": 25122, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 25220, "s": 25171, "text": "How to filter R DataFrame by values in a column?" } ]
Enumerated Types or Enums in C++
In this tutorial, we will be discussing a program to understand Enumerated types or Enums in C++. Enumerated types are user-defined data types in which the user can specify a limited number of values that can be allocated to the variable. Live Demo #include <bits/stdc++.h> using namespace std; int main(){ //defining enum variable enum Gender { Male, Female }; Gender gender = Male; switch (gender) { case Male: cout << "Gender is Male"; break; case Female: cout << "Gender is Female"; break; default: cout << "Value can be Male or Female"; } return 0; } Gender is Male
[ { "code": null, "e": 1160, "s": 1062, "text": "In this tutorial, we will be discussing a program to understand Enumerated types or Enums in C++." }, { "code": null, "e": 1301, "s": 1160, "text": "Enumerated types are user-defined data types in which the user can specify a limited number of values that can be allocated to the variable." }, { "code": null, "e": 1312, "s": 1301, "text": " Live Demo" }, { "code": null, "e": 1715, "s": 1312, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n //defining enum variable\n enum Gender {\n Male,\n Female\n };\n Gender gender = Male;\n switch (gender) {\n case Male:\n cout << \"Gender is Male\";\n break;\n case Female:\n cout << \"Gender is Female\";\n break;\n default:\n cout << \"Value can be Male or Female\";\n }\n return 0;\n}" }, { "code": null, "e": 1730, "s": 1715, "text": "Gender is Male" } ]
Binary array to corresponding decimal in JavaScript
We are required to write a JavaScript function that takes in a binary array (consisting of only 0 and 1). Our function should first join all the bits in the array and then return the decimal number corresponding to that binary. Following is the code − Live Demo const arr = [1, 0, 1, 1]; const binaryArrayToNumber = arr => { let num = 0; for (let i = 0, exponent = 3; i < arr.length; i++) { if (arr[i]) { num += Math.pow(2, exponent); }; exponent--; }; return num; }; console.log(binaryArrayToNumber(arr)); 11
[ { "code": null, "e": 1168, "s": 1062, "text": "We are required to write a JavaScript function that takes in a binary array (consisting of only 0 and 1)." }, { "code": null, "e": 1290, "s": 1168, "text": "Our function should first join all the bits in the array and then return the decimal number corresponding to that binary." }, { "code": null, "e": 1314, "s": 1290, "text": "Following is the code −" }, { "code": null, "e": 1325, "s": 1314, "text": " Live Demo" }, { "code": null, "e": 1609, "s": 1325, "text": "const arr = [1, 0, 1, 1];\nconst binaryArrayToNumber = arr => {\n let num = 0;\n for (let i = 0, exponent = 3; i < arr.length; i++) {\n if (arr[i]) {\n num += Math.pow(2, exponent);\n };\n exponent--;\n };\n return num;\n};\nconsole.log(binaryArrayToNumber(arr));" }, { "code": null, "e": 1612, "s": 1609, "text": "11" } ]
Adding a column that doesn't exist in a query?
Add a column that does not exist in a query, with the help of AS keyword. The syntax is as follows − SELECT yourColumnName1,yourColumnName2,....N,yourValue AS yourColumnName,....N' FROM yourTableName; To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table ColumnDoesNotExists -> ( -> UserId int, -> UserName varchar(20) -> ); Query OK, 0 rows affected (0.67 sec) Insert some records in the table using insert command. The query is as follows − mysql> insert into ColumnDoesNotExists(UserId,UserName) values(100,'Larry'); Query OK, 1 row affected (0.14 sec) mysql> insert into ColumnDoesNotExists(UserId,UserName) values(101,'Sam'); Query OK, 1 row affected (0.22 sec) mysql> insert into ColumnDoesNotExists(UserId,UserName) values(102,'Mike'); Query OK, 1 row affected (0.15 sec) mysql> insert into ColumnDoesNotExists(UserId,UserName) values(103,'David'); Query OK, 1 row affected (0.15 sec) mysql> insert into ColumnDoesNotExists(UserId,UserName) values(104,'Robert'); Query OK, 1 row affected (0.10 sec) mysql> insert into ColumnDoesNotExists(UserId,UserName) values(105,'Maxwell'); Query OK, 1 row affected (0.20 sec) mysql> insert into ColumnDoesNotExists(UserId,UserName) values(106,'Bob'); Query OK, 1 row affected (0.17 sec) mysql> insert into ColumnDoesNotExists(UserId,UserName) values(107,'John'); Query OK, 1 row affected (0.17 sec) mysql> insert into ColumnDoesNotExists(UserId,UserName) values(108,'James'); Query OK, 1 row affected (0.18 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from ColumnDoesNotExists; +--------+----------+ | UserId | UserName | +--------+----------+ | 100 | Larry | | 101 | Sam | | 102 | Mike | | 103 | David | | 104 | Robert | | 105 | Maxwell | | 106 | Bob | | 107 | John | | 108 | James | +--------+----------+ 9 rows in set (0.00 sec) Here is the query to add a column name that does not exist in a query − mysql> select UserId,UserName,23 AS Age from ColumnDoesNotExists; +--------+----------+-----+ | UserId | UserName | Age | +--------+----------+-----+ | 100 | Larry | 23 | | 101 | Sam | 23 | | 102 | Mike | 23 | | 103 | David | 23 | | 104 | Robert | 23 | | 105 | Maxwell | 23 | | 106 | Bob | 23 | | 107 | John | 23 | | 108 | James | 23 | +--------+----------+-----+ 9 rows in set (0.00 sec)
[ { "code": null, "e": 1163, "s": 1062, "text": "Add a column that does not exist in a query, with the help of AS keyword. The syntax is as follows −" }, { "code": null, "e": 1263, "s": 1163, "text": "SELECT yourColumnName1,yourColumnName2,....N,yourValue AS yourColumnName,....N' FROM yourTableName;" }, { "code": null, "e": 1362, "s": 1263, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1505, "s": 1362, "text": "mysql> create table ColumnDoesNotExists\n -> (\n -> UserId int,\n -> UserName varchar(20)\n -> );\nQuery OK, 0 rows affected (0.67 sec)" }, { "code": null, "e": 1586, "s": 1505, "text": "Insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2600, "s": 1586, "text": "mysql> insert into ColumnDoesNotExists(UserId,UserName) values(100,'Larry');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into ColumnDoesNotExists(UserId,UserName) values(101,'Sam');\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into ColumnDoesNotExists(UserId,UserName) values(102,'Mike');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into ColumnDoesNotExists(UserId,UserName) values(103,'David');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into ColumnDoesNotExists(UserId,UserName) values(104,'Robert');\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into ColumnDoesNotExists(UserId,UserName) values(105,'Maxwell');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into ColumnDoesNotExists(UserId,UserName) values(106,'Bob');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into ColumnDoesNotExists(UserId,UserName) values(107,'John');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into ColumnDoesNotExists(UserId,UserName) values(108,'James');\nQuery OK, 1 row affected (0.18 sec)" }, { "code": null, "e": 2685, "s": 2600, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2726, "s": 2685, "text": "mysql> select *from ColumnDoesNotExists;" }, { "code": null, "e": 3037, "s": 2726, "text": "+--------+----------+\n| UserId | UserName |\n+--------+----------+\n| 100 | Larry |\n| 101 | Sam |\n| 102 | Mike |\n| 103 | David |\n| 104 | Robert |\n| 105 | Maxwell |\n| 106 | Bob |\n| 107 | John |\n| 108 | James |\n+--------+----------+\n9 rows in set (0.00 sec)" }, { "code": null, "e": 3109, "s": 3037, "text": "Here is the query to add a column name that does not exist in a query −" }, { "code": null, "e": 3175, "s": 3109, "text": "mysql> select UserId,UserName,23 AS Age from ColumnDoesNotExists;" }, { "code": null, "e": 3564, "s": 3175, "text": "+--------+----------+-----+\n| UserId | UserName | Age |\n+--------+----------+-----+\n| 100 | Larry | 23 |\n| 101 | Sam | 23 |\n| 102 | Mike | 23 |\n| 103 | David | 23 |\n| 104 | Robert | 23 |\n| 105 | Maxwell | 23 |\n| 106 | Bob | 23 |\n| 107 | John | 23 |\n| 108 | James | 23 |\n+--------+----------+-----+\n9 rows in set (0.00 sec)" } ]
How to run an external application through a C# application?
An external application can be run from a C# application using Process. A process is a program that is running on your computer. This can be anything from a small background task, such as a spell-checker or system events handler to a full-blown application like Notepad etc. Each process provides the resources needed to execute a program. Each process is started with a single thread, known as the primary thread. A process can have multiple threads in addition to the primary thread. Processes are heavily dependent on system resources available while threads require minimal amounts of resource, so a process is considered as heavyweight while a thread is termed as a lightweight process. Process is present in System.Diagnostics namespace. Example to run notepad from C# application using System; using System.Diagnostics; namespace DemoApplication{ class Program{ static void Main(){ Process notepad = new Process(); notepad.StartInfo.FileName = "notepad.exe"; notepad.StartInfo.Arguments = "DemoText"; notepad.Start(); Console.ReadLine(); } } } The above output shows the console application opened Notepad with the name DemoText provided in the arguments. using System; using System.Diagnostics; namespace DemoApplication{ class Program{ static void Main(){ Process.Start("https://www.google.com/"); Console.ReadLine(); } } } The above code will open the browser and redirect to www.google.com.
[ { "code": null, "e": 1337, "s": 1062, "text": "An external application can be run from a C# application using Process. A process is a program that is running on your computer. This can be anything from a small background task, such as a spell-checker or system events handler to a full-blown application like Notepad etc." }, { "code": null, "e": 1806, "s": 1337, "text": "Each process provides the resources needed to execute a program. Each process is started with a single thread, known as the primary thread. A process can have multiple threads in addition to the primary thread. Processes are heavily dependent on system resources available while threads require minimal amounts of resource, so a process is considered as heavyweight while a thread is termed as a lightweight process. Process is present in System.Diagnostics namespace." }, { "code": null, "e": 1849, "s": 1806, "text": "Example to run notepad from C# application" }, { "code": null, "e": 2176, "s": 1849, "text": "using System;\nusing System.Diagnostics;\nnamespace DemoApplication{\n class Program{\n static void Main(){\n Process notepad = new Process();\n notepad.StartInfo.FileName = \"notepad.exe\";\n notepad.StartInfo.Arguments = \"DemoText\";\n notepad.Start();\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2288, "s": 2176, "text": "The above output shows the console application opened Notepad with the name DemoText provided in the arguments." }, { "code": null, "e": 2494, "s": 2288, "text": "using System;\nusing System.Diagnostics;\nnamespace DemoApplication{\n class Program{\n static void Main(){\n Process.Start(\"https://www.google.com/\");\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2563, "s": 2494, "text": "The above code will open the browser and redirect to www.google.com." } ]
JavaFX Effects - Shadow
This effect creates a duplicate of the specified node with blurry edges. The class named Shadow of the package javafx.scene.effect represents the sepia tone effect. This class contains six properties, which are − color − This property is of Color type represents the color of the shadow. color − This property is of Color type represents the color of the shadow. blur type − This property is of the BlurType and it represents the type of the blur effect used to blur the shadow. blur type − This property is of the BlurType and it represents the type of the blur effect used to blur the shadow. radius − This property is of the type double and it represents the radius of the shadow blur kernel. radius − This property is of the type double and it represents the radius of the shadow blur kernel. width − This property is of the type double and it represents the width of the shadow blur kernel. width − This property is of the type double and it represents the width of the shadow blur kernel. height − This property is of the type double and it represents the height of the shadow blur kernel. height − This property is of the type double and it represents the height of the shadow blur kernel. input − This property is of the type Effect and it represents an input to the shadow effect. input − This property is of the type Effect and it represents an input to the shadow effect. The following program is an example demonstrating the shadow effect of JavaFX. In here, we are drawing the text “Welcome to Tutorialspoint”, and a circle in a scene. We are applying the shadow effect with the Blur Type Gaussian with the Color Rosy Brown and Height, Width, Radius as 5. Save this code in a file with the name ShadowEffectExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.effect.BlurType; import javafx.scene.effect.Shadow; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.stage.Stage; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; public class ShadowEffectExample extends Application { @Override public void start(Stage stage) { //Creating a Text object Text text = new Text(); //Setting font to the text text.setFont(Font.font(null, FontWeight.BOLD, 40)); //setting the position of the text text.setX(60); text.setY(50); //Setting the text to be embedded. text.setText("Welcome to Tutorialspoint"); //Setting the color of the text text.setFill(Color.DARKSEAGREEN); //Drawing a Circle Circle circle = new Circle(); //Setting the center of the circle circle.setCenterX(300.0f); circle.setCenterY(160.0f); //Setting the radius of the circle circle.setRadius(100.0f); //Instantiating the Shadow class Shadow shadow = new Shadow(); //setting the type of blur for the shadow shadow.setBlurType(BlurType.GAUSSIAN); //Setting color of the shadow shadow.setColor(Color.ROSYBROWN); //Setting the height of the shadow shadow.setHeight(5); //Setting the width of the shadow shadow.setWidth(5); //Setting the radius of the shadow shadow.setRadius(5); //Applying shadow effect to the text text.setEffect(shadow); //Applying shadow effect to the circle circle.setEffect(shadow); //Creating a Group object Group root = new Group(circle, text); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle("Bloom effect example"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac ShadowEffectExample.java java ShadowEffectExample On executing, the above program generates a JavaFX window as shown below. 33 Lectures 7.5 hours Syed Raza 64 Lectures 12.5 hours Emenwa Global, Ejike IfeanyiChukwu 20 Lectures 4 hours Emenwa Global, Ejike IfeanyiChukwu Print Add Notes Bookmark this page
[ { "code": null, "e": 1973, "s": 1900, "text": "This effect creates a duplicate of the specified node with blurry edges." }, { "code": null, "e": 2113, "s": 1973, "text": "The class named Shadow of the package javafx.scene.effect represents the sepia tone effect. This class contains six properties, which are −" }, { "code": null, "e": 2188, "s": 2113, "text": "color − This property is of Color type represents the color of the shadow." }, { "code": null, "e": 2263, "s": 2188, "text": "color − This property is of Color type represents the color of the shadow." }, { "code": null, "e": 2379, "s": 2263, "text": "blur type − This property is of the BlurType and it represents the type of the blur effect used to blur the shadow." }, { "code": null, "e": 2495, "s": 2379, "text": "blur type − This property is of the BlurType and it represents the type of the blur effect used to blur the shadow." }, { "code": null, "e": 2596, "s": 2495, "text": "radius − This property is of the type double and it represents the radius of the shadow blur kernel." }, { "code": null, "e": 2697, "s": 2596, "text": "radius − This property is of the type double and it represents the radius of the shadow blur kernel." }, { "code": null, "e": 2796, "s": 2697, "text": "width − This property is of the type double and it represents the width of the shadow blur kernel." }, { "code": null, "e": 2895, "s": 2796, "text": "width − This property is of the type double and it represents the width of the shadow blur kernel." }, { "code": null, "e": 2996, "s": 2895, "text": "height − This property is of the type double and it represents the height of the shadow blur kernel." }, { "code": null, "e": 3097, "s": 2996, "text": "height − This property is of the type double and it represents the height of the shadow blur kernel." }, { "code": null, "e": 3190, "s": 3097, "text": "input − This property is of the type Effect and it represents an input to the shadow effect." }, { "code": null, "e": 3283, "s": 3190, "text": "input − This property is of the type Effect and it represents an input to the shadow effect." }, { "code": null, "e": 3449, "s": 3283, "text": "The following program is an example demonstrating the shadow effect of JavaFX. In here, we are drawing the text “Welcome to Tutorialspoint”, and a circle in a scene." }, { "code": null, "e": 3569, "s": 3449, "text": "We are applying the shadow effect with the Blur Type Gaussian with the Color Rosy Brown and Height, Width, Radius as 5." }, { "code": null, "e": 3634, "s": 3569, "text": "Save this code in a file with the name ShadowEffectExample.java." }, { "code": null, "e": 6061, "s": 3634, "text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.scene.effect.BlurType; \nimport javafx.scene.effect.Shadow; \nimport javafx.scene.paint.Color; \nimport javafx.scene.shape.Circle; \nimport javafx.stage.Stage; \nimport javafx.scene.text.Font; \nimport javafx.scene.text.FontWeight; \nimport javafx.scene.text.Text; \n \npublic class ShadowEffectExample extends Application { \n @Override \n public void start(Stage stage) { \n //Creating a Text object \n Text text = new Text(); \n \n //Setting font to the text \n text.setFont(Font.font(null, FontWeight.BOLD, 40)); \n \n //setting the position of the text \n text.setX(60); \n text.setY(50); \n \n //Setting the text to be embedded. \n text.setText(\"Welcome to Tutorialspoint\"); \n \n //Setting the color of the text \n text.setFill(Color.DARKSEAGREEN);\n \n //Drawing a Circle \n Circle circle = new Circle(); \n \n //Setting the center of the circle \n circle.setCenterX(300.0f); \n circle.setCenterY(160.0f); \n \n //Setting the radius of the circle \n circle.setRadius(100.0f); \n \n //Instantiating the Shadow class \n Shadow shadow = new Shadow(); \n \n //setting the type of blur for the shadow \n shadow.setBlurType(BlurType.GAUSSIAN); \n \n //Setting color of the shadow \n shadow.setColor(Color.ROSYBROWN); \n \n //Setting the height of the shadow \n shadow.setHeight(5); \n \n //Setting the width of the shadow \n shadow.setWidth(5); \n \n //Setting the radius of the shadow \n shadow.setRadius(5); \n \n //Applying shadow effect to the text \n text.setEffect(shadow); \n \n //Applying shadow effect to the circle \n circle.setEffect(shadow); \n \n //Creating a Group object \n Group root = new Group(circle, text); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the Stage \n stage.setTitle(\"Bloom effect example\");\n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n} " }, { "code": null, "e": 6155, "s": 6061, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 6217, "s": 6155, "text": "javac ShadowEffectExample.java \njava ShadowEffectExample \n" }, { "code": null, "e": 6291, "s": 6217, "text": "On executing, the above program generates a JavaFX window as shown below." }, { "code": null, "e": 6326, "s": 6291, "text": "\n 33 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6337, "s": 6326, "text": " Syed Raza" }, { "code": null, "e": 6373, "s": 6337, "text": "\n 64 Lectures \n 12.5 hours \n" }, { "code": null, "e": 6409, "s": 6373, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 6442, "s": 6409, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 6478, "s": 6442, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 6485, "s": 6478, "text": " Print" }, { "code": null, "e": 6496, "s": 6485, "text": " Add Notes" } ]
How to use a pipe with Linux find command?
Linux find statement is one of the most widely used statements that allows us to walk a file hierarchy. It is used to mostly find a specific file or directories and we can also append different other Linux statements or flags along with it to enhance or do a complex operation. Let’s explore an example of a find statement to understand it better. In the Linux code shown below, I am trying to search for a file inside my Downloads folder, and for that I am making use of the find statement find sample.sh sample.sh Notice that if the find command is able to locate the file then it will simply print the name of the file, if not then it will not return anything the terminal process will terminate. Now we know how the find statement works, let’s explore the case where we want to use the find command along with a pipe. A pipe in Linux is just a vertical bar on your keyboard. It is used to consider the command that is on the left side of it as an input to the command on the right side of it. Now that we know about both the find command the pipe in Linux, let’s consider an example where we will make use of both of these in a Linux command. find . -name '*.txt' | xargs cat In the above command, just before the pipe, I am considering all the files that has a name that ends with a .txt extension and then after the pipe, I am simply printing those with the help of the cat command. immukul@192 directory1 % find . -name '*.txt' | xargs cat this is a test file and it is used for testing and is not available for anything else so please stop asking, lionel messi orange orange blabla blabla foofoo here is the text to keep between the 2 patterns bar blabla blabla
[ { "code": null, "e": 1340, "s": 1062, "text": "Linux find statement is one of the most widely used statements that allows us to walk a file hierarchy. It is used to mostly find a specific file or directories and we can also append different other Linux statements or flags along with it to enhance or do a complex operation." }, { "code": null, "e": 1410, "s": 1340, "text": "Let’s explore an example of a find statement to understand it better." }, { "code": null, "e": 1553, "s": 1410, "text": "In the Linux code shown below, I am trying to search for a file inside my Downloads folder, and for that I am making use of the find statement" }, { "code": null, "e": 1568, "s": 1553, "text": "find sample.sh" }, { "code": null, "e": 1578, "s": 1568, "text": "sample.sh" }, { "code": null, "e": 1762, "s": 1578, "text": "Notice that if the find command is able to locate the file then it will simply print the name of the file, if not then it will not return anything the terminal process will terminate." }, { "code": null, "e": 1884, "s": 1762, "text": "Now we know how the find statement works, let’s explore the case where we want to use the find command along with a pipe." }, { "code": null, "e": 2059, "s": 1884, "text": "A pipe in Linux is just a vertical bar on your keyboard. It is used to consider the command that is on the left side of it as an input to the command on the right side of it." }, { "code": null, "e": 2209, "s": 2059, "text": "Now that we know about both the find command the pipe in Linux, let’s consider an example where we will make use of both of these in a Linux command." }, { "code": null, "e": 2242, "s": 2209, "text": "find . -name '*.txt' | xargs cat" }, { "code": null, "e": 2451, "s": 2242, "text": "In the above command, just before the pipe, I am considering all the files that has a name that ends with a .txt extension and then after the pipe, I am simply printing those with the help of the cat command." }, { "code": null, "e": 2732, "s": 2451, "text": "immukul@192 directory1 % find . -name '*.txt' | xargs cat\nthis is a test file and it is used for testing and is not available for anything else so\nplease stop asking, lionel messi\norange\norange\nblabla\nblabla\nfoofoo\nhere\nis the\ntext\nto keep between the 2 patterns\nbar\nblabla\nblabla" } ]
HTML | <li> type Attribute
08 Mar, 2022 The <li> type attribute in HTML is used to specify the type of a list items. This attribute also defines the style of the bullet point of the list items. Syntax: <li type="1|a|A|i|I|disc|circle|square"> Attribute Values: For ordered list items: 1: It is the default value. It is used to specify the numerical ordered list. a: It arranged the list items in lower case letters. A: It arrange the list items in the form of upper case. i: It arrange the list items in the roman numbers in the form of lower case letters. I: It arranged the list in roman numerals in the form of uppercase letters. For unordered list items: disc: It is the default value. It creates a filled circle. circle: It creates an unfilled circle. square: It creates a filled square. Note: The <li> type attribute is not supported by HTML 5 Instead of using this attribute we can use CSS list-style-type property. Example 1: HTML <!DOCTYPE html><html> <head> <title> HTML li type Attribute </title></head> <body> <h1 style = "color: green;"> GeeksforGeeks </h1> <h2> HTML list item type Attribute </h2> <p>Sorting Algorithms</p> <ol> <li type="a">Merge sort</li> <li>Quick sort</li> <li type="I">Insertion sort</li> </ol></body> </html> Output: Example 2: HTML <!DOCTYPE html><html> <head> <title> HTML li type Attribute </title></head> <body> <h1 style = "color: green;"> GeeksforGeeks </h1> <h2> HTML li type Attribute </h2> <p>Sorting Algorithms</p> <ul> <li>Merge sort</li> <li>Quick sort</li> <li type="square">Insertion sort</li> </ul></body> </html> Output: Supported Browsers: The browser supported by HTML <li> type attribute are listed below: Google Chrome Internet Explorer Firefox Safari Opera anikaseth98 hritikbhatnagar2182 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Angular File Upload Form validation using jQuery Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Mar, 2022" }, { "code": null, "e": 183, "s": 28, "text": "The <li> type attribute in HTML is used to specify the type of a list items. This attribute also defines the style of the bullet point of the list items. " }, { "code": null, "e": 192, "s": 183, "text": "Syntax: " }, { "code": null, "e": 233, "s": 192, "text": "<li type=\"1|a|A|i|I|disc|circle|square\">" }, { "code": null, "e": 277, "s": 233, "text": "Attribute Values: For ordered list items: " }, { "code": null, "e": 355, "s": 277, "text": "1: It is the default value. It is used to specify the numerical ordered list." }, { "code": null, "e": 408, "s": 355, "text": "a: It arranged the list items in lower case letters." }, { "code": null, "e": 464, "s": 408, "text": "A: It arrange the list items in the form of upper case." }, { "code": null, "e": 549, "s": 464, "text": "i: It arrange the list items in the roman numbers in the form of lower case letters." }, { "code": null, "e": 625, "s": 549, "text": "I: It arranged the list in roman numerals in the form of uppercase letters." }, { "code": null, "e": 653, "s": 625, "text": "For unordered list items: " }, { "code": null, "e": 712, "s": 653, "text": "disc: It is the default value. It creates a filled circle." }, { "code": null, "e": 751, "s": 712, "text": "circle: It creates an unfilled circle." }, { "code": null, "e": 787, "s": 751, "text": "square: It creates a filled square." }, { "code": null, "e": 917, "s": 787, "text": "Note: The <li> type attribute is not supported by HTML 5 Instead of using this attribute we can use CSS list-style-type property." }, { "code": null, "e": 930, "s": 917, "text": "Example 1: " }, { "code": null, "e": 935, "s": 930, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML li type Attribute </title></head> <body> <h1 style = \"color: green;\"> GeeksforGeeks </h1> <h2> HTML list item type Attribute </h2> <p>Sorting Algorithms</p> <ol> <li type=\"a\">Merge sort</li> <li>Quick sort</li> <li type=\"I\">Insertion sort</li> </ol></body> </html> ", "e": 1379, "s": 935, "text": null }, { "code": null, "e": 1388, "s": 1379, "text": "Output: " }, { "code": null, "e": 1401, "s": 1388, "text": "Example 2: " }, { "code": null, "e": 1406, "s": 1401, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML li type Attribute </title></head> <body> <h1 style = \"color: green;\"> GeeksforGeeks </h1> <h2> HTML li type Attribute </h2> <p>Sorting Algorithms</p> <ul> <li>Merge sort</li> <li>Quick sort</li> <li type=\"square\">Insertion sort</li> </ul></body> </html> ", "e": 1839, "s": 1406, "text": null }, { "code": null, "e": 1848, "s": 1839, "text": "Output: " }, { "code": null, "e": 1938, "s": 1848, "text": "Supported Browsers: The browser supported by HTML <li> type attribute are listed below: " }, { "code": null, "e": 1952, "s": 1938, "text": "Google Chrome" }, { "code": null, "e": 1970, "s": 1952, "text": "Internet Explorer" }, { "code": null, "e": 1978, "s": 1970, "text": "Firefox" }, { "code": null, "e": 1985, "s": 1978, "text": "Safari" }, { "code": null, "e": 1991, "s": 1985, "text": "Opera" }, { "code": null, "e": 2005, "s": 1993, "text": "anikaseth98" }, { "code": null, "e": 2025, "s": 2005, "text": "hritikbhatnagar2182" }, { "code": null, "e": 2041, "s": 2025, "text": "HTML-Attributes" }, { "code": null, "e": 2046, "s": 2041, "text": "HTML" }, { "code": null, "e": 2063, "s": 2046, "text": "Web Technologies" }, { "code": null, "e": 2068, "s": 2063, "text": "HTML" }, { "code": null, "e": 2166, "s": 2068, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2190, "s": 2166, "text": "REST API (Introduction)" }, { "code": null, "e": 2229, "s": 2190, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2268, "s": 2229, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 2288, "s": 2268, "text": "Angular File Upload" }, { "code": null, "e": 2317, "s": 2288, "text": "Form validation using jQuery" }, { "code": null, "e": 2350, "s": 2317, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2411, "s": 2350, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2454, "s": 2411, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2526, "s": 2454, "text": "Differences between Functional Components and Class Components in React" } ]
How to set the Alignment of the Text in the TextBox in C#?
29 Nov, 2019 In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to set the alignment of the text present in the TextBox by using the TextAlign Property of the TextBox. The default value of this property is HorizontalAlignment Left. In Windows form, you can set this property in two different ways: 1. Design-Time: It is the simplest way to set the TextAlign property of the TextBox as shown in the following steps: Step 1: Create a windows form.Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the TextBox control from the ToolBox and drop it on the windows form. You can place TextBox anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the TextBox control to set the TextAlign property of the TextBox.Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the TextAlign property of the TextBox programmatically with the help of given syntax: public System.Windows.Forms.HorizontalAlignment TextAlign { get; set; } Here, the HorizontalAlignment is used to represent the HorizontalAlignment enumeration values that specify how text is aligned in the TextBox control. Following steps are used to set the TextAlign property of the TextBox: Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox TextBox Mytextbox = new TextBox(); // Creating textbox TextBox Mytextbox = new TextBox(); Step 2 : After creating TextBox, set the TextAlign property of the TextBox provided by the TextBox class.// Set TextAlign property Mytextbox.TextAlign = HorizontalAlignment.Center; // Set TextAlign property Mytextbox.TextAlign = HorizontalAlignment.Center; Step 3 : And last add this textbox control to from using Add() method.// Add this textbox to form this.Controls.Add(Mytextbox); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = "Enter City"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.AutoSize = true; Mytextbox.Name = "text_box1"; Mytextbox.TextAlign = HorizontalAlignment.Center; // Add this textbox to form this.Controls.Add(Mytextbox); }}}Output: // Add this textbox to form this.Controls.Add(Mytextbox); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = "Enter City"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.AutoSize = true; Mytextbox.Name = "text_box1"; Mytextbox.TextAlign = HorizontalAlignment.Center; // Add this textbox to form this.Controls.Add(Mytextbox); }}} Output: CSharp-Windows-Forms-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2019" }, { "code": null, "e": 460, "s": 28, "text": "In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to set the alignment of the text present in the TextBox by using the TextAlign Property of the TextBox. The default value of this property is HorizontalAlignment Left. In Windows form, you can set this property in two different ways:" }, { "code": null, "e": 577, "s": 460, "text": "1. Design-Time: It is the simplest way to set the TextAlign property of the TextBox as shown in the following steps:" }, { "code": null, "e": 665, "s": 577, "text": "Step 1: Create a windows form.Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 823, "s": 665, "text": "Step 2: Drag the TextBox control from the ToolBox and drop it on the windows form. You can place TextBox anywhere on the windows form according to your need." }, { "code": null, "e": 957, "s": 823, "text": "Step 3: After drag and drop you will go to the properties of the TextBox control to set the TextAlign property of the TextBox.Output:" }, { "code": null, "e": 965, "s": 957, "text": "Output:" }, { "code": null, "e": 1143, "s": 965, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the TextAlign property of the TextBox programmatically with the help of given syntax:" }, { "code": null, "e": 1215, "s": 1143, "text": "public System.Windows.Forms.HorizontalAlignment TextAlign { get; set; }" }, { "code": null, "e": 1437, "s": 1215, "text": "Here, the HorizontalAlignment is used to represent the HorizontalAlignment enumeration values that specify how text is aligned in the TextBox control. Following steps are used to set the TextAlign property of the TextBox:" }, { "code": null, "e": 1581, "s": 1437, "text": "Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox\nTextBox Mytextbox = new TextBox();\n" }, { "code": null, "e": 1637, "s": 1581, "text": "// Creating textbox\nTextBox Mytextbox = new TextBox();\n" }, { "code": null, "e": 1819, "s": 1637, "text": "Step 2 : After creating TextBox, set the TextAlign property of the TextBox provided by the TextBox class.// Set TextAlign property\nMytextbox.TextAlign = HorizontalAlignment.Center;\n" }, { "code": null, "e": 1896, "s": 1819, "text": "// Set TextAlign property\nMytextbox.TextAlign = HorizontalAlignment.Center;\n" }, { "code": null, "e": 3203, "s": 1896, "text": "Step 3 : And last add this textbox control to from using Add() method.// Add this textbox to form\nthis.Controls.Add(Mytextbox);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = \"Enter City\"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.AutoSize = true; Mytextbox.Name = \"text_box1\"; Mytextbox.TextAlign = HorizontalAlignment.Center; // Add this textbox to form this.Controls.Add(Mytextbox); }}}Output:" }, { "code": null, "e": 3262, "s": 3203, "text": "// Add this textbox to form\nthis.Controls.Add(Mytextbox);\n" }, { "code": null, "e": 3271, "s": 3262, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = \"Enter City\"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.AutoSize = true; Mytextbox.Name = \"text_box1\"; Mytextbox.TextAlign = HorizontalAlignment.Center; // Add this textbox to form this.Controls.Add(Mytextbox); }}}", "e": 4435, "s": 3271, "text": null }, { "code": null, "e": 4443, "s": 4435, "text": "Output:" }, { "code": null, "e": 4474, "s": 4443, "text": "CSharp-Windows-Forms-Namespace" }, { "code": null, "e": 4477, "s": 4474, "text": "C#" } ]
How to fill NAN values with mean in Pandas?
24 Jan, 2021 It is a quite compulsory process to modify the data we have as the computer will show you an error of invalid input as it is quite impossible to process the data having ‘NaN’ with it and it is not quite practically possible to manually change the ‘NaN’ to its mean. Therefore, to resolve this problem we process the data and use various functions by which the ‘NaN’ is removed from our data and is replaced with the particular mean and ready be get process by the system. Mainly there are two steps to remove ‘NaN’ from the data- Using Dataframe.fillna() from the pandas’ library.Using SimpleImputer from sklearn.impute (this is only useful if the data is present in the form of csv file) Using Dataframe.fillna() from the pandas’ library. Using SimpleImputer from sklearn.impute (this is only useful if the data is present in the form of csv file) With the help of Dataframe.fillna() from the pandas’ library, we can easily replace the ‘NaN’ in the data frame. Procedure: To calculate the mean() we use the mean function of the particular columnNow with the help of fillna() function we will change all ‘NaN’ of that particular column for which we have its mean.We will print the updated column. To calculate the mean() we use the mean function of the particular column Now with the help of fillna() function we will change all ‘NaN’ of that particular column for which we have its mean. We will print the updated column. Syntax: df.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None, **kwargs) Parameter: value : Value to use to fill holes method : Method to use for filling holes in reindexed Series pad / fill axis : {0 or ‘index’} inplace : If True, fill in place. limit : If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill downcast : dict, default is None Example 1: To calculate the mean() we use the mean function of the particular columnThen apply fillna() function, we will change all ‘NaN’ of that particular column for which we have its mean and print the updated data frame. To calculate the mean() we use the mean function of the particular column Then apply fillna() function, we will change all ‘NaN’ of that particular column for which we have its mean and print the updated data frame. Python3 import numpy as npimport pandas as pd # A dictionary with list as valuesGFG_dict = { 'G1': [10, 20,30,40], 'G2': [25, np.NaN, np.NaN, 29], 'G3': [15, 14, 17, 11], 'G4': [21, 22, 23, 25]} # Create a DataFrame from dictionarygfg = pd.DataFrame(GFG_dict) #Finding the mean of the column having NaNmean_value=gfg['G2'].mean() # Replace NaNs in column S2 with the# mean of values in the same columngfg['G2'].fillna(value=mean_value, inplace=True)print('Updated Dataframe:')print(gfg) Output: Example 2: Python3 import pandas as pdimport numpy as np df = pd.DataFrame({ 'ID': [10, np.nan, 20, 30, np.nan, 50, np.nan, 150, 200, 102, np.nan, 130], 'Sale': [10, 20, np.nan, 11, 90, np.nan, 55, 14, np.nan, 25, 75, 35], 'Date': ['2020-10-05', '2020-09-10', np.nan, '2020-08-17', '2020-09-10', '2020-07-27', '2020-09-10', '2020-10-10', '2020-10-10', '2020-06-27', '2020-08-17', '2020-04-25'],}) df['Sale'].fillna(int(df['Sale'].mean()), inplace=True)print(df) Output: This function Imputation transformer for completing missing values which provide basic strategies for imputing missing values. These values can be imputed with a provided constant value or using the statistics (mean, median, or most frequent) of each column in which the missing values are located. This class also allows for different missing value encoding. Syntax: class sklearn.impute.SimpleImputer(*, missing_values=nan, strategy=’mean’, fill_value=None, verbose=0, copy=True, add_indicator=False) Parameters: missing_values: int float, str, np.nan or None, default=np.nan strategy string: default=’mean’ fill_valuestring or numerical value: default=None verbose: integer, default=0 copy: boolean, default=True add_indicator: boolean, default=False Note : Data Used in below examples is here Example 1 : (Computation on PID column) Python3 import pandas as pdimport numpy as np Dataset= pd.read_csv("property data.csv")X = Dataset.iloc[:,0].values # To calculate mean use imputer classfrom sklearn.impute import SimpleImputerimputer = SimpleImputer(missing_values=np.nan, strategy='mean')imputer = imputer.fit(X) X = imputer.transform(X)print(X) Output: Example 2 : (Computation on ST_NUM column) Python3 from sklearn.impute import SimpleImputerimport pandas as pdimport numpy as np Dataset = pd.read_csv("property data.csv")X = Dataset.iloc[:, 1].values # To calculate mean use imputer classimputer = SimpleImputer(missing_values=np.nan, strategy='mean')imputer = imputer.fit(X)X = imputer.transform(X)print(X) Output: Picked Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Introduction To PYTHON
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Jan, 2021" }, { "code": null, "e": 524, "s": 52, "text": "It is a quite compulsory process to modify the data we have as the computer will show you an error of invalid input as it is quite impossible to process the data having ‘NaN’ with it and it is not quite practically possible to manually change the ‘NaN’ to its mean. Therefore, to resolve this problem we process the data and use various functions by which the ‘NaN’ is removed from our data and is replaced with the particular mean and ready be get process by the system." }, { "code": null, "e": 582, "s": 524, "text": "Mainly there are two steps to remove ‘NaN’ from the data-" }, { "code": null, "e": 744, "s": 582, "text": "Using Dataframe.fillna() from the pandas’ library.Using SimpleImputer from sklearn.impute (this is only useful if the data is present in the form of csv file)" }, { "code": null, "e": 797, "s": 744, "text": "Using Dataframe.fillna() from the pandas’ library." }, { "code": null, "e": 907, "s": 797, "text": "Using SimpleImputer from sklearn.impute (this is only useful if the data is present in the form of csv file)" }, { "code": null, "e": 1022, "s": 907, "text": "With the help of Dataframe.fillna() from the pandas’ library, we can easily replace the ‘NaN’ in the data frame. " }, { "code": null, "e": 1033, "s": 1022, "text": "Procedure:" }, { "code": null, "e": 1257, "s": 1033, "text": "To calculate the mean() we use the mean function of the particular columnNow with the help of fillna() function we will change all ‘NaN’ of that particular column for which we have its mean.We will print the updated column." }, { "code": null, "e": 1331, "s": 1257, "text": "To calculate the mean() we use the mean function of the particular column" }, { "code": null, "e": 1449, "s": 1331, "text": "Now with the help of fillna() function we will change all ‘NaN’ of that particular column for which we have its mean." }, { "code": null, "e": 1483, "s": 1449, "text": "We will print the updated column." }, { "code": null, "e": 1589, "s": 1483, "text": "Syntax: df.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None, **kwargs)" }, { "code": null, "e": 1600, "s": 1589, "text": "Parameter:" }, { "code": null, "e": 1635, "s": 1600, "text": "value : Value to use to fill holes" }, { "code": null, "e": 1707, "s": 1635, "text": "method : Method to use for filling holes in reindexed Series pad / fill" }, { "code": null, "e": 1729, "s": 1707, "text": "axis : {0 or ‘index’}" }, { "code": null, "e": 1763, "s": 1729, "text": "inplace : If True, fill in place." }, { "code": null, "e": 1873, "s": 1763, "text": "limit : If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill" }, { "code": null, "e": 1906, "s": 1873, "text": "downcast : dict, default is None" }, { "code": null, "e": 1917, "s": 1906, "text": "Example 1:" }, { "code": null, "e": 2132, "s": 1917, "text": "To calculate the mean() we use the mean function of the particular columnThen apply fillna() function, we will change all ‘NaN’ of that particular column for which we have its mean and print the updated data frame." }, { "code": null, "e": 2206, "s": 2132, "text": "To calculate the mean() we use the mean function of the particular column" }, { "code": null, "e": 2348, "s": 2206, "text": "Then apply fillna() function, we will change all ‘NaN’ of that particular column for which we have its mean and print the updated data frame." }, { "code": null, "e": 2356, "s": 2348, "text": "Python3" }, { "code": "import numpy as npimport pandas as pd # A dictionary with list as valuesGFG_dict = { 'G1': [10, 20,30,40], 'G2': [25, np.NaN, np.NaN, 29], 'G3': [15, 14, 17, 11], 'G4': [21, 22, 23, 25]} # Create a DataFrame from dictionarygfg = pd.DataFrame(GFG_dict) #Finding the mean of the column having NaNmean_value=gfg['G2'].mean() # Replace NaNs in column S2 with the# mean of values in the same columngfg['G2'].fillna(value=mean_value, inplace=True)print('Updated Dataframe:')print(gfg)", "e": 2884, "s": 2356, "text": null }, { "code": null, "e": 2892, "s": 2884, "text": "Output:" }, { "code": null, "e": 2903, "s": 2892, "text": "Example 2:" }, { "code": null, "e": 2911, "s": 2903, "text": "Python3" }, { "code": "import pandas as pdimport numpy as np df = pd.DataFrame({ 'ID': [10, np.nan, 20, 30, np.nan, 50, np.nan, 150, 200, 102, np.nan, 130], 'Sale': [10, 20, np.nan, 11, 90, np.nan, 55, 14, np.nan, 25, 75, 35], 'Date': ['2020-10-05', '2020-09-10', np.nan, '2020-08-17', '2020-09-10', '2020-07-27', '2020-09-10', '2020-10-10', '2020-10-10', '2020-06-27', '2020-08-17', '2020-04-25'],}) df['Sale'].fillna(int(df['Sale'].mean()), inplace=True)print(df)", "e": 3436, "s": 2911, "text": null }, { "code": null, "e": 3444, "s": 3436, "text": "Output:" }, { "code": null, "e": 3804, "s": 3444, "text": "This function Imputation transformer for completing missing values which provide basic strategies for imputing missing values. These values can be imputed with a provided constant value or using the statistics (mean, median, or most frequent) of each column in which the missing values are located. This class also allows for different missing value encoding." }, { "code": null, "e": 3947, "s": 3804, "text": "Syntax: class sklearn.impute.SimpleImputer(*, missing_values=nan, strategy=’mean’, fill_value=None, verbose=0, copy=True, add_indicator=False)" }, { "code": null, "e": 3959, "s": 3947, "text": "Parameters:" }, { "code": null, "e": 4022, "s": 3959, "text": "missing_values: int float, str, np.nan or None, default=np.nan" }, { "code": null, "e": 4054, "s": 4022, "text": "strategy string: default=’mean’" }, { "code": null, "e": 4104, "s": 4054, "text": "fill_valuestring or numerical value: default=None" }, { "code": null, "e": 4132, "s": 4104, "text": "verbose: integer, default=0" }, { "code": null, "e": 4160, "s": 4132, "text": "copy: boolean, default=True" }, { "code": null, "e": 4198, "s": 4160, "text": "add_indicator: boolean, default=False" }, { "code": null, "e": 4241, "s": 4198, "text": "Note : Data Used in below examples is here" }, { "code": null, "e": 4281, "s": 4241, "text": "Example 1 : (Computation on PID column)" }, { "code": null, "e": 4289, "s": 4281, "text": "Python3" }, { "code": "import pandas as pdimport numpy as np Dataset= pd.read_csv(\"property data.csv\")X = Dataset.iloc[:,0].values # To calculate mean use imputer classfrom sklearn.impute import SimpleImputerimputer = SimpleImputer(missing_values=np.nan, strategy='mean')imputer = imputer.fit(X) X = imputer.transform(X)print(X)", "e": 4598, "s": 4289, "text": null }, { "code": null, "e": 4606, "s": 4598, "text": "Output:" }, { "code": null, "e": 4649, "s": 4606, "text": "Example 2 : (Computation on ST_NUM column)" }, { "code": null, "e": 4657, "s": 4649, "text": "Python3" }, { "code": "from sklearn.impute import SimpleImputerimport pandas as pdimport numpy as np Dataset = pd.read_csv(\"property data.csv\")X = Dataset.iloc[:, 1].values # To calculate mean use imputer classimputer = SimpleImputer(missing_values=np.nan, strategy='mean')imputer = imputer.fit(X)X = imputer.transform(X)print(X)", "e": 4966, "s": 4657, "text": null }, { "code": null, "e": 4974, "s": 4966, "text": "Output:" }, { "code": null, "e": 4981, "s": 4974, "text": "Picked" }, { "code": null, "e": 5004, "s": 4981, "text": "Python Pandas-exercise" }, { "code": null, "e": 5018, "s": 5004, "text": "Python-pandas" }, { "code": null, "e": 5025, "s": 5018, "text": "Python" }, { "code": null, "e": 5123, "s": 5025, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5141, "s": 5123, "text": "Python Dictionary" }, { "code": null, "e": 5183, "s": 5141, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5205, "s": 5183, "text": "Enumerate() in Python" }, { "code": null, "e": 5240, "s": 5205, "text": "Read a file line by line in Python" }, { "code": null, "e": 5266, "s": 5240, "text": "Python String | replace()" }, { "code": null, "e": 5298, "s": 5266, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5327, "s": 5298, "text": "*args and **kwargs in Python" }, { "code": null, "e": 5357, "s": 5327, "text": "Iterate over a list in Python" }, { "code": null, "e": 5384, "s": 5357, "text": "Python Classes and Objects" } ]
Missing ranges of numbers | Practice | GeeksforGeeks
Given an array Arr of N positive integers, find the missing elements (if any) in the range 0 to max of Arri. Example 1: Input: N = 5 Arr[] = {62, 8, 34, 5, 332} Output: 0-4 6-7 9-33 35-61 63-331 Explanation: Elements in the range 0-4, 6-7, 9-33, 35-61 and 63-331 are not present. Example 2: Input: N = 4 Arr[] = {13, 0, 32, 500} Output: 1-12 14-31 33-499 Explanation: Elements in the range 1-12, 14-31 and 33-499 are not present. Your Task: You don't need to read input or print anything. Your task is to complete the function findMissing() which takes the array of integers arr and its size n as input parameters and returns a string denoting the missing elements. If there are more than one missing, collate them using hyphen (-) and separate each different range with a space. If there are no missing element then return "-1". Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints 1 <= N <= 107 0 <= Arri <= 107 -3 ankita12apr7 months ago String findMissing(int[] arr, int n) { // code here Arrays.sort(arr); String str =""; if(arr[0] == 0 && n == 1){ return "-1"; } if(arr[0] == 1 && n == 1){ return "0"; } if(arr[0] != 0){ int x = arr[0]-1; if(x>0){ str += "0"+"-"+x+" "; } } if(arr[0] == 1){ str += "0"+" "; } for(int i = 0 ; i< n-1 ; i++){ int start = arr[i]+1; int end = arr[i+1]-1; if(start<end){ str += start+"-"+end+" "; } if(end == start){ str += end+" "; } } if(str == ""){ return "0"; } return str; } 0 pankajkumarravi8 months ago // Tried my self working fine accept 1 case- you are Welcome for suggestion class Solution { String findMissing(int[] arr, int n) { // code here Arrays.sort(arr); String resp = ""; if (arr[0] ==1) resp =resp+"0"; else if (arr[0]>arr[1]) resp =resp+"-1"; else { for (int i = 0; i < n - 1; i++) { if (i == 0 && arr[0] != 1) { resp = resp + printValBwRange(0, arr[i] - 1); } resp = resp + printValBwRange(arr[i] + 1, arr[i + 1] - 1); } } return resp; } // print values b/w range public static String printValBwRange(int start, int end) { if (start <= end) { return " " + start + " - " + end; } return "-1"; }} We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 348, "s": 226, "text": "Given an array Arr of N positive integers, find the missing elements (if any) in the range 0 to max of Arri. \n\nExample 1:" }, { "code": null, "e": 510, "s": 348, "text": "Input:\nN = 5\nArr[] = {62, 8, 34, 5, 332}\nOutput: 0-4 6-7 9-33 35-61 63-331\nExplanation: Elements in the range 0-4, 6-7, \n9-33, 35-61 and 63-331 are not present.\n" }, { "code": null, "e": 522, "s": 510, "text": "\nExample 2:" }, { "code": null, "e": 663, "s": 522, "text": "Input:\nN = 4\nArr[] = {13, 0, 32, 500}\nOutput: 1-12 14-31 33-499\nExplanation: Elements in the range 1-12, \n14-31 and 33-499 are not present.\n" }, { "code": null, "e": 1064, "s": 663, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function findMissing() which takes the array of integers arr and its size n as input parameters and returns a string denoting the missing elements. If\nthere are more than one missing, collate them using hyphen (-) and separate each different range with a space. If there are no missing element then return \"-1\"." }, { "code": null, "e": 1127, "s": 1064, "text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1171, "s": 1127, "text": "\nConstraints\n1 <= N <= 107\n0 <= Arri <= 107" }, { "code": null, "e": 1174, "s": 1171, "text": "-3" }, { "code": null, "e": 1198, "s": 1174, "text": "ankita12apr7 months ago" }, { "code": null, "e": 1941, "s": 1198, "text": "String findMissing(int[] arr, int n) { // code here Arrays.sort(arr); String str =\"\"; if(arr[0] == 0 && n == 1){ return \"-1\"; } if(arr[0] == 1 && n == 1){ return \"0\"; } if(arr[0] != 0){ int x = arr[0]-1; if(x>0){ str += \"0\"+\"-\"+x+\" \"; } } if(arr[0] == 1){ str += \"0\"+\" \"; } for(int i = 0 ; i< n-1 ; i++){ int start = arr[i]+1; int end = arr[i+1]-1; if(start<end){ str += start+\"-\"+end+\" \"; } if(end == start){ str += end+\" \"; } } if(str == \"\"){ return \"0\"; } return str; }" }, { "code": null, "e": 1943, "s": 1941, "text": "0" }, { "code": null, "e": 1971, "s": 1943, "text": "pankajkumarravi8 months ago" }, { "code": null, "e": 2048, "s": 1971, "text": "// Tried my self working fine accept 1 case- you are Welcome for suggestion " }, { "code": null, "e": 2644, "s": 2048, "text": "class Solution { String findMissing(int[] arr, int n) { // code here Arrays.sort(arr); String resp = \"\"; if (arr[0] ==1) resp =resp+\"0\"; else if (arr[0]>arr[1]) resp =resp+\"-1\"; else { for (int i = 0; i < n - 1; i++) { if (i == 0 && arr[0] != 1) { resp = resp + printValBwRange(0, arr[i] - 1); } resp = resp + printValBwRange(arr[i] + 1, arr[i + 1] - 1); } } return resp;" }, { "code": null, "e": 2653, "s": 2644, "text": " }" }, { "code": null, "e": 2873, "s": 2653, "text": " // print values b/w range public static String printValBwRange(int start, int end) { if (start <= end) { return \" \" + start + \" - \" + end; } return \"-1\"; }}" }, { "code": null, "e": 3019, "s": 2873, "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": 3055, "s": 3019, "text": " Login to access your submissions. " }, { "code": null, "e": 3065, "s": 3055, "text": "\nProblem\n" }, { "code": null, "e": 3075, "s": 3065, "text": "\nContest\n" }, { "code": null, "e": 3138, "s": 3075, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3323, "s": 3138, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 3607, "s": 3323, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 3753, "s": 3607, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 3830, "s": 3753, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 3871, "s": 3830, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 3899, "s": 3871, "text": "Disable browser extensions." }, { "code": null, "e": 3970, "s": 3899, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 4157, "s": 3970, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
How to create customized Buttons in Android with different shapes and colors
19 Feb, 2021 A Button is a user interface that are used to perform some action when clicked or tapped. Default Shape of Button In this article, we will try to change the shape and color of Button to various designs, like: Oval Button Rectangular Button Cylindrical Button Below are the various steps to created customized Buttons:Step 1: Start a new Android Studio projectPlease refer to this article to see in detail about how to create a new Android Studio project. Step 2: Add the ButtonSince we only need to customize Buttons, we will just add Buttons in our layout. We don’t need any other widget. This can be done either by writing the code in XML or using the Design Tab. Here, we will do so by adding its XML code. Now since we need to customize the Button as per 3 shapes (as shown above), we will add 3 buttons and add the customization of each separately, lets say the buttons be – oval, rectangle and cylindrical. activity_main.xml <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical" android:background="#ffff00"> <!-- 1st Button: Oval --> <Button android:layout_width="180dp" android:layout_height="60dp" android:layout_marginLeft="180dp" android:layout_marginTop="20dp" android:text="oval" android:textColor="#388e3c"/> <!-- 2nd Button: Rectangle --> <Button android:layout_width="180dp" android:layout_height="60dp" android:layout_marginLeft="180dp" android:layout_marginTop="20dp" android:text="rectangle" android:textColor="#FFFF"/> <!-- 3rd Button: Cylindrical --> <Button android:layout_width="180dp" android:layout_height="60dp" android:layout_marginLeft="180dp" android:layout_marginTop="20dp" android:text="cylindrical" android:textColor="#3e2723"/> </LinearLayout> Initially, all three buttons have default values and will look as per the default look shown above. Step 3: Customizing the buttonIn order to customize the button, as shown above, we will be needing few attributes of Button in particular: shape: This defines the shape of the widget that is being used. For example: oval, rectangle, etc.color This attribute takes the Hexadecimal color code as parameter and sets the color as per the codecorner::radius: This attribute defines how much curved corners of the button has to be. For example, no curve will lead to rectangle and increasing the curve can result in circle as well.stroke: This attribute refers to the thickness of the outline of the button. The more the stroke, the thicker the outline will be. shape: This defines the shape of the widget that is being used. For example: oval, rectangle, etc. color This attribute takes the Hexadecimal color code as parameter and sets the color as per the code corner::radius: This attribute defines how much curved corners of the button has to be. For example, no curve will lead to rectangle and increasing the curve can result in circle as well. stroke: This attribute refers to the thickness of the outline of the button. The more the stroke, the thicker the outline will be. These attributes can be set for a widget with the help of a Drawable resource file. Creating a new drawable resource file:We will be creating a new drawable file which will contain the customizations such as shape, color, and gradient which we want to set on our button. To create a drawable file, click on: app -> res -> drawable(right click) -> New -> Drawable resource file and name it anything you want.Adding code to the resource file:Now that we have this drawable resource file, we can customize our button by adding tags like shape, color, stroke, or any other attribute which we want.custom_button.xmlcustom_button2.xmlcustom_button3.xmlcustom_button.xml<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" > <stroke android:color="#388e3c" android:width="2dp"/> <corners android:radius="5dp"/> <solid android:color="#ffff"/></shape>custom_button2.xml<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <stroke android:color="@color/colorPrimary" android:width="1dp"/> <corners android:radius="15dp"/> <gradient android:startColor="#2e7d32" android:endColor="#e0f7fa"/></shape>custom_button3.xml<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <stroke android:color="@color/colorPrimary" android:width="1dp"/> <corners android:radius="190dp"/> <solid android:color="#76ff03"/> <gradient android:startColor="#76ff03"/></shape>Adding these customizations to our original button:We can now add these customizations to the default button which we created previously. To do this, we just change the background attribute of our Button to the drawable resource file we just created.android:background=”@drawable/custom_button” Creating a new drawable resource file:We will be creating a new drawable file which will contain the customizations such as shape, color, and gradient which we want to set on our button. To create a drawable file, click on: app -> res -> drawable(right click) -> New -> Drawable resource file and name it anything you want. We will be creating a new drawable file which will contain the customizations such as shape, color, and gradient which we want to set on our button. To create a drawable file, click on: app -> res -> drawable(right click) -> New -> Drawable resource file and name it anything you want. Adding code to the resource file:Now that we have this drawable resource file, we can customize our button by adding tags like shape, color, stroke, or any other attribute which we want.custom_button.xmlcustom_button2.xmlcustom_button3.xmlcustom_button.xml<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" > <stroke android:color="#388e3c" android:width="2dp"/> <corners android:radius="5dp"/> <solid android:color="#ffff"/></shape>custom_button2.xml<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <stroke android:color="@color/colorPrimary" android:width="1dp"/> <corners android:radius="15dp"/> <gradient android:startColor="#2e7d32" android:endColor="#e0f7fa"/></shape>custom_button3.xml<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <stroke android:color="@color/colorPrimary" android:width="1dp"/> <corners android:radius="190dp"/> <solid android:color="#76ff03"/> <gradient android:startColor="#76ff03"/></shape> Adding code to the resource file: Now that we have this drawable resource file, we can customize our button by adding tags like shape, color, stroke, or any other attribute which we want. custom_button.xml custom_button2.xml custom_button3.xml <?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" > <stroke android:color="#388e3c" android:width="2dp"/> <corners android:radius="5dp"/> <solid android:color="#ffff"/></shape> <?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <stroke android:color="@color/colorPrimary" android:width="1dp"/> <corners android:radius="15dp"/> <gradient android:startColor="#2e7d32" android:endColor="#e0f7fa"/></shape> <?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <stroke android:color="@color/colorPrimary" android:width="1dp"/> <corners android:radius="190dp"/> <solid android:color="#76ff03"/> <gradient android:startColor="#76ff03"/></shape> Adding these customizations to our original button:We can now add these customizations to the default button which we created previously. To do this, we just change the background attribute of our Button to the drawable resource file we just created.android:background=”@drawable/custom_button” android:background=”@drawable/custom_button” This is how our activity_main.xml file will look now: activity_main.xml <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical" android:background="#ffff00"> <!-- 1st Button: Oval --> <Button android:layout_width="180dp" android:layout_height="60dp" android:layout_marginLeft="180dp" android:layout_marginTop="20dp" android:text="oval" android:textColor="#388e3c" android:background="@drawable/custom_button"/> <!-- 2nd Button: Rectangle --> <Button android:layout_width="180dp" android:layout_height="60dp" android:layout_marginLeft="180dp" android:layout_marginTop="20dp" android:text="rectangle" android:textColor="#FFFF" android:background="@drawable/custom_button2"/> <!-- 3rd Button: Cylindrical --> <Button android:layout_width="180dp" android:layout_height="60dp" android:layout_marginLeft="180dp" android:layout_marginTop="20dp" android:text="cylindrical" android:textColor="#3e2723" android:background="@drawable/custom_button3"/> </LinearLayout> Step 4: Running the project to see the output Output: Android-Button Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android SDK and it's Components Android RecyclerView in Kotlin Android Project folder Structure Navigation Drawer in Android Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android Content Providers in Android with Example CardView in Android With Example How to Post Data to API using Retrofit in Android? Flutter - Stack Widget
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Feb, 2021" }, { "code": null, "e": 142, "s": 52, "text": "A Button is a user interface that are used to perform some action when clicked or tapped." }, { "code": null, "e": 166, "s": 142, "text": "Default Shape of Button" }, { "code": null, "e": 261, "s": 166, "text": "In this article, we will try to change the shape and color of Button to various designs, like:" }, { "code": null, "e": 273, "s": 261, "text": "Oval Button" }, { "code": null, "e": 292, "s": 273, "text": "Rectangular Button" }, { "code": null, "e": 311, "s": 292, "text": "Cylindrical Button" }, { "code": null, "e": 507, "s": 311, "text": "Below are the various steps to created customized Buttons:Step 1: Start a new Android Studio projectPlease refer to this article to see in detail about how to create a new Android Studio project." }, { "code": null, "e": 762, "s": 507, "text": "Step 2: Add the ButtonSince we only need to customize Buttons, we will just add Buttons in our layout. We don’t need any other widget. This can be done either by writing the code in XML or using the Design Tab. Here, we will do so by adding its XML code." }, { "code": null, "e": 965, "s": 762, "text": "Now since we need to customize the Button as per 3 shapes (as shown above), we will add 3 buttons and add the customization of each separately, lets say the buttons be – oval, rectangle and cylindrical." }, { "code": null, "e": 983, "s": 965, "text": "activity_main.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" android:orientation=\"vertical\" android:background=\"#ffff00\"> <!-- 1st Button: Oval --> <Button android:layout_width=\"180dp\" android:layout_height=\"60dp\" android:layout_marginLeft=\"180dp\" android:layout_marginTop=\"20dp\" android:text=\"oval\" android:textColor=\"#388e3c\"/> <!-- 2nd Button: Rectangle --> <Button android:layout_width=\"180dp\" android:layout_height=\"60dp\" android:layout_marginLeft=\"180dp\" android:layout_marginTop=\"20dp\" android:text=\"rectangle\" android:textColor=\"#FFFF\"/> <!-- 3rd Button: Cylindrical --> <Button android:layout_width=\"180dp\" android:layout_height=\"60dp\" android:layout_marginLeft=\"180dp\" android:layout_marginTop=\"20dp\" android:text=\"cylindrical\" android:textColor=\"#3e2723\"/> </LinearLayout>", "e": 2183, "s": 983, "text": null }, { "code": null, "e": 2283, "s": 2183, "text": "Initially, all three buttons have default values and will look as per the default look shown above." }, { "code": null, "e": 2422, "s": 2283, "text": "Step 3: Customizing the buttonIn order to customize the button, as shown above, we will be needing few attributes of Button in particular:" }, { "code": null, "e": 2939, "s": 2422, "text": "shape: This defines the shape of the widget that is being used. For example: oval, rectangle, etc.color This attribute takes the Hexadecimal color code as parameter and sets the color as per the codecorner::radius: This attribute defines how much curved corners of the button has to be. For example, no curve will lead to rectangle and increasing the curve can result in circle as well.stroke: This attribute refers to the thickness of the outline of the button. The more the stroke, the thicker the outline will be." }, { "code": null, "e": 3038, "s": 2939, "text": "shape: This defines the shape of the widget that is being used. For example: oval, rectangle, etc." }, { "code": null, "e": 3140, "s": 3038, "text": "color This attribute takes the Hexadecimal color code as parameter and sets the color as per the code" }, { "code": null, "e": 3328, "s": 3140, "text": "corner::radius: This attribute defines how much curved corners of the button has to be. For example, no curve will lead to rectangle and increasing the curve can result in circle as well." }, { "code": null, "e": 3459, "s": 3328, "text": "stroke: This attribute refers to the thickness of the outline of the button. The more the stroke, the thicker the outline will be." }, { "code": null, "e": 3543, "s": 3459, "text": "These attributes can be set for a widget with the help of a Drawable resource file." }, { "code": null, "e": 5476, "s": 3543, "text": "Creating a new drawable resource file:We will be creating a new drawable file which will contain the customizations such as shape, color, and gradient which we want to set on our button. To create a drawable file, click on: app -> res -> drawable(right click) -> New -> Drawable resource file and name it anything you want.Adding code to the resource file:Now that we have this drawable resource file, we can customize our button by adding tags like shape, color, stroke, or any other attribute which we want.custom_button.xmlcustom_button2.xmlcustom_button3.xmlcustom_button.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"oval\" > <stroke android:color=\"#388e3c\" android:width=\"2dp\"/> <corners android:radius=\"5dp\"/> <solid android:color=\"#ffff\"/></shape>custom_button2.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\"> <stroke android:color=\"@color/colorPrimary\" android:width=\"1dp\"/> <corners android:radius=\"15dp\"/> <gradient android:startColor=\"#2e7d32\" android:endColor=\"#e0f7fa\"/></shape>custom_button3.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\"> <stroke android:color=\"@color/colorPrimary\" android:width=\"1dp\"/> <corners android:radius=\"190dp\"/> <solid android:color=\"#76ff03\"/> <gradient android:startColor=\"#76ff03\"/></shape>Adding these customizations to our original button:We can now add these customizations to the default button which we created previously. To do this, we just change the background attribute of our Button to the drawable resource file we just created.android:background=”@drawable/custom_button”" }, { "code": null, "e": 5800, "s": 5476, "text": "Creating a new drawable resource file:We will be creating a new drawable file which will contain the customizations such as shape, color, and gradient which we want to set on our button. To create a drawable file, click on: app -> res -> drawable(right click) -> New -> Drawable resource file and name it anything you want." }, { "code": null, "e": 6086, "s": 5800, "text": "We will be creating a new drawable file which will contain the customizations such as shape, color, and gradient which we want to set on our button. To create a drawable file, click on: app -> res -> drawable(right click) -> New -> Drawable resource file and name it anything you want." }, { "code": null, "e": 7402, "s": 6086, "text": "Adding code to the resource file:Now that we have this drawable resource file, we can customize our button by adding tags like shape, color, stroke, or any other attribute which we want.custom_button.xmlcustom_button2.xmlcustom_button3.xmlcustom_button.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"oval\" > <stroke android:color=\"#388e3c\" android:width=\"2dp\"/> <corners android:radius=\"5dp\"/> <solid android:color=\"#ffff\"/></shape>custom_button2.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\"> <stroke android:color=\"@color/colorPrimary\" android:width=\"1dp\"/> <corners android:radius=\"15dp\"/> <gradient android:startColor=\"#2e7d32\" android:endColor=\"#e0f7fa\"/></shape>custom_button3.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\"> <stroke android:color=\"@color/colorPrimary\" android:width=\"1dp\"/> <corners android:radius=\"190dp\"/> <solid android:color=\"#76ff03\"/> <gradient android:startColor=\"#76ff03\"/></shape>" }, { "code": null, "e": 7436, "s": 7402, "text": "Adding code to the resource file:" }, { "code": null, "e": 7590, "s": 7436, "text": "Now that we have this drawable resource file, we can customize our button by adding tags like shape, color, stroke, or any other attribute which we want." }, { "code": null, "e": 7608, "s": 7590, "text": "custom_button.xml" }, { "code": null, "e": 7627, "s": 7608, "text": "custom_button2.xml" }, { "code": null, "e": 7646, "s": 7627, "text": "custom_button3.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"oval\" > <stroke android:color=\"#388e3c\" android:width=\"2dp\"/> <corners android:radius=\"5dp\"/> <solid android:color=\"#ffff\"/></shape>", "e": 7943, "s": 7646, "text": null }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\"> <stroke android:color=\"@color/colorPrimary\" android:width=\"1dp\"/> <corners android:radius=\"15dp\"/> <gradient android:startColor=\"#2e7d32\" android:endColor=\"#e0f7fa\"/></shape>", "e": 8300, "s": 7943, "text": null }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\"> <stroke android:color=\"@color/colorPrimary\" android:width=\"1dp\"/> <corners android:radius=\"190dp\"/> <solid android:color=\"#76ff03\"/> <gradient android:startColor=\"#76ff03\"/></shape>", "e": 8672, "s": 8300, "text": null }, { "code": null, "e": 8967, "s": 8672, "text": "Adding these customizations to our original button:We can now add these customizations to the default button which we created previously. To do this, we just change the background attribute of our Button to the drawable resource file we just created.android:background=”@drawable/custom_button”" }, { "code": null, "e": 9012, "s": 8967, "text": "android:background=”@drawable/custom_button”" }, { "code": null, "e": 9066, "s": 9012, "text": "This is how our activity_main.xml file will look now:" }, { "code": null, "e": 9084, "s": 9066, "text": "activity_main.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" android:orientation=\"vertical\" android:background=\"#ffff00\"> <!-- 1st Button: Oval --> <Button android:layout_width=\"180dp\" android:layout_height=\"60dp\" android:layout_marginLeft=\"180dp\" android:layout_marginTop=\"20dp\" android:text=\"oval\" android:textColor=\"#388e3c\" android:background=\"@drawable/custom_button\"/> <!-- 2nd Button: Rectangle --> <Button android:layout_width=\"180dp\" android:layout_height=\"60dp\" android:layout_marginLeft=\"180dp\" android:layout_marginTop=\"20dp\" android:text=\"rectangle\" android:textColor=\"#FFFF\" android:background=\"@drawable/custom_button2\"/> <!-- 3rd Button: Cylindrical --> <Button android:layout_width=\"180dp\" android:layout_height=\"60dp\" android:layout_marginLeft=\"180dp\" android:layout_marginTop=\"20dp\" android:text=\"cylindrical\" android:textColor=\"#3e2723\" android:background=\"@drawable/custom_button3\"/> </LinearLayout>", "e": 10440, "s": 9084, "text": null }, { "code": null, "e": 10486, "s": 10440, "text": "Step 4: Running the project to see the output" }, { "code": null, "e": 10494, "s": 10486, "text": "Output:" }, { "code": null, "e": 10509, "s": 10494, "text": "Android-Button" }, { "code": null, "e": 10517, "s": 10509, "text": "Android" }, { "code": null, "e": 10525, "s": 10517, "text": "Android" }, { "code": null, "e": 10623, "s": 10525, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10655, "s": 10623, "text": "Android SDK and it's Components" }, { "code": null, "e": 10686, "s": 10655, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 10719, "s": 10686, "text": "Android Project folder Structure" }, { "code": null, "e": 10748, "s": 10719, "text": "Navigation Drawer in Android" }, { "code": null, "e": 10787, "s": 10748, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 10829, "s": 10787, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 10871, "s": 10829, "text": "Content Providers in Android with Example" }, { "code": null, "e": 10904, "s": 10871, "text": "CardView in Android With Example" }, { "code": null, "e": 10955, "s": 10904, "text": "How to Post Data to API using Retrofit in Android?" } ]
Python – String Integer Product
25 Jun, 2020 Sometimes, while working with data, we can have a problem in which we receive a series of lists with data in string format, which we wish to find the product of each string list integer. Let’s discuss certain ways in which this task can be performed. Method #1 : Using loop + int()This is the brute force method to perform this task. In this, we run a loop for the entire list, convert each string to integer and perform product listwise and store in a separate list. # Python3 code to demonstrate working of# String Integer Product# using loop + int() # getting Productdef prod(val) : res = 1 for ele in val: res *= int(ele) return res # initialize list test_list = [['1', '4'], ['5', '6'], ['7', '10']] # printing original list print("The original list : " + str(test_list)) # String Integer Product# using loop + int()res = []for sub in test_list: par_prod = prod(sub) res.append(par_prod) # printing resultprint("List after product of nested string lists : " + str(res)) The original list : [['1', '4'], ['5', '6'], ['7', '10']] List after product of nested string lists : [4, 30, 70] Method #2 : Using loop + int() + list comprehensionThis is the shorthand with the help of which this task can be performed. In this, we run a loop on lists using list comprehension and extract product using explicit product function. # Python3 code to demonstrate working of# String Integer Product# using loop + int() + list comprehension # getting Productdef prod(val) : res = 1 for ele in val: res *= int(ele) return res # initialize list test_list = [['1', '4'], ['5', '6'], ['7', '10']] # printing original list print("The original list : " + str(test_list)) # String Integer Product# using loop + int() + list comprehensionres = [prod(sub) for sub in test_list] # printing resultprint("List after product of nested string lists : " + str(res)) The original list : [['1', '4'], ['5', '6'], ['7', '10']] List after product of nested string lists : [4, 30, 70] nidhi_biet Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jun, 2020" }, { "code": null, "e": 279, "s": 28, "text": "Sometimes, while working with data, we can have a problem in which we receive a series of lists with data in string format, which we wish to find the product of each string list integer. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 496, "s": 279, "text": "Method #1 : Using loop + int()This is the brute force method to perform this task. In this, we run a loop for the entire list, convert each string to integer and perform product listwise and store in a separate list." }, { "code": "# Python3 code to demonstrate working of# String Integer Product# using loop + int() # getting Productdef prod(val) : res = 1 for ele in val: res *= int(ele) return res # initialize list test_list = [['1', '4'], ['5', '6'], ['7', '10']] # printing original list print(\"The original list : \" + str(test_list)) # String Integer Product# using loop + int()res = []for sub in test_list: par_prod = prod(sub) res.append(par_prod) # printing resultprint(\"List after product of nested string lists : \" + str(res))", "e": 1032, "s": 496, "text": null }, { "code": null, "e": 1147, "s": 1032, "text": "The original list : [['1', '4'], ['5', '6'], ['7', '10']]\nList after product of nested string lists : [4, 30, 70]\n" }, { "code": null, "e": 1383, "s": 1149, "text": "Method #2 : Using loop + int() + list comprehensionThis is the shorthand with the help of which this task can be performed. In this, we run a loop on lists using list comprehension and extract product using explicit product function." }, { "code": "# Python3 code to demonstrate working of# String Integer Product# using loop + int() + list comprehension # getting Productdef prod(val) : res = 1 for ele in val: res *= int(ele) return res # initialize list test_list = [['1', '4'], ['5', '6'], ['7', '10']] # printing original list print(\"The original list : \" + str(test_list)) # String Integer Product# using loop + int() + list comprehensionres = [prod(sub) for sub in test_list] # printing resultprint(\"List after product of nested string lists : \" + str(res))", "e": 1922, "s": 1383, "text": null }, { "code": null, "e": 2037, "s": 1922, "text": "The original list : [['1', '4'], ['5', '6'], ['7', '10']]\nList after product of nested string lists : [4, 30, 70]\n" }, { "code": null, "e": 2048, "s": 2037, "text": "nidhi_biet" }, { "code": null, "e": 2069, "s": 2048, "text": "Python list-programs" }, { "code": null, "e": 2076, "s": 2069, "text": "Python" }, { "code": null, "e": 2092, "s": 2076, "text": "Python Programs" } ]
NestedScrollView in Android with Example
18 Feb, 2021 NestedScrollView is just like ScrollView, but it supports acting as both a nested scrolling parent and child on both new and old versions of Android. It is enabled by default. NestedScrollView is used when there is a need for a scrolling view inside another scrolling view. You have seen this in many apps for example when we open a pdf file and when we reached the end of the PDF there is an Ad below the pdf file. This is where NestedScrollView comes in. Normally this would be difficult to accomplish since the system would be unable to decide which view to scroll. Let’s discuss a NestedScrollView in Android by taking an example. Step 1: Creating 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 choose Java as language though we are going to implement this project in Java language. Step 2: Before going to the coding section first do some pre-task Go to the app -> res -> values -> strings.xml and add two random text strings inside the strings.xml file to display those strings in the activity_main.xml file. XML <resources> <string name="app_name">GFG | NestedScrollView </string> <string name="random_text_1"> Hadoop is a data processing tool used to process large size data over distributed commodity hardware. The trend of Big Data Hadoop market is on the boom and it’s not showing any kind of deceleration in its growth. Today, industries are capable of storing all the data generated at their business at an affordable price just because of Hadoop. Hadoop helps the industry to know their customer’s behavior, customers buying priorities i.e. what they loved the most, and click patterns, etc. Hadoop provides personalized recommendations and personalizes ad targeting features. Companies are generating thousands of petabytes of data every day so the demand for Big Data professionals is very high. Even after a few years, Hadoop will be considered as the must-learn skill for the data-scientist and Big Data Technology. Companies are investing big in it and it will become an in-demand skill in the future. Hadoop provides personalized recommendations and personalizes ad targeting features. Companies are generating thousands of petabytes of data every day so the demand for Big Data professionals is very high. Even after a few years, Hadoop will be considered as the must-learn skill for the data-scientist and Big Data Technology. Companies are investing big in it and it will become an in-demand skill in the future. </string> <string name="random_text_2"> Humans are coming closer to the internet at a very fast rate. It means that the volume of data Industries is gathering will increase as time passes because of more users. Industry’s are gradually analyzing the need for this useful information they are getting from their users. It is for sure that the data always tends to an increasing pattern so the company’s are eventually acquiring professionals skilled with Big Data Technologies. According to NASSCOM, India’s Big Data Market will reach 16 billion USD by 2025 from 2 billion USD. The growth of smart devices in India is growing at a very huge rate that will cause growth in the Big Data Market. Since Big Data is growing the demand for Big Data professionals will be high. Hadoop provides personalized recommendations and personalizes ad targeting features. Companies are generating thousands of petabytes of data every day so the demand for Big Data professionals is very high. Even after a few years, Hadoop will be considered as the must-learn skill for the data-scientist and Big Data Technology. Companies are investing big in it and it will become an in-demand skill in the future. </string> </resources> Step 3: Designing the UI In the activity_main.xml file add the NestedScrollView and inside NestedScrollView add a LinearLayout and inside LinearLayout add two TextView to display the strings which are created inside the strings.xml file and one Button between the TextView. Here is the code for the activity_main.xml file. One can add as many views inside the NestedScrollView’s LinearLayout XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- Nested Scroll view --> <androidx.core.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="wrap_content"> <!-- Linear layout to contain 2 text view and button --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!-- showing random text 1 from strings.xml file --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/random_text_1" /> <!-- simple button --> <Button android:layout_width="match_parent" android:layout_height="160dp" android:background="@color/colorPrimary" android:text="Nested Scroll View " android:textColor="#ffffff" android:textSize="32dp" /> <!-- showing random text 2 from strings.xml file --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/random_text_2" /> </LinearLayout> </androidx.core.widget.NestedScrollView> </RelativeLayout> Step 4: Working with MainActivity.java file There is nothing to do with the MainActivity.java file, so keep it as it is. Java import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }} Resources: Download Complete Project from Github Download the Apk file android Android-View Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Feb, 2021" }, { "code": null, "e": 687, "s": 52, "text": "NestedScrollView is just like ScrollView, but it supports acting as both a nested scrolling parent and child on both new and old versions of Android. It is enabled by default. NestedScrollView is used when there is a need for a scrolling view inside another scrolling view. You have seen this in many apps for example when we open a pdf file and when we reached the end of the PDF there is an Ad below the pdf file. This is where NestedScrollView comes in. Normally this would be difficult to accomplish since the system would be unable to decide which view to scroll. Let’s discuss a NestedScrollView in Android by taking an example." }, { "code": null, "e": 718, "s": 687, "text": "Step 1: Creating a New Project" }, { "code": null, "e": 927, "s": 718, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that choose Java as language though we are going to implement this project in Java language." }, { "code": null, "e": 993, "s": 927, "text": "Step 2: Before going to the coding section first do some pre-task" }, { "code": null, "e": 1155, "s": 993, "text": "Go to the app -> res -> values -> strings.xml and add two random text strings inside the strings.xml file to display those strings in the activity_main.xml file." }, { "code": null, "e": 1159, "s": 1155, "text": "XML" }, { "code": "<resources> <string name=\"app_name\">GFG | NestedScrollView </string> <string name=\"random_text_1\"> Hadoop is a data processing tool used to process large size data over distributed commodity hardware. The trend of Big Data Hadoop market is on the boom and it’s not showing any kind of deceleration in its growth. Today, industries are capable of storing all the data generated at their business at an affordable price just because of Hadoop. Hadoop helps the industry to know their customer’s behavior, customers buying priorities i.e. what they loved the most, and click patterns, etc. Hadoop provides personalized recommendations and personalizes ad targeting features. Companies are generating thousands of petabytes of data every day so the demand for Big Data professionals is very high. Even after a few years, Hadoop will be considered as the must-learn skill for the data-scientist and Big Data Technology. Companies are investing big in it and it will become an in-demand skill in the future. Hadoop provides personalized recommendations and personalizes ad targeting features. Companies are generating thousands of petabytes of data every day so the demand for Big Data professionals is very high. Even after a few years, Hadoop will be considered as the must-learn skill for the data-scientist and Big Data Technology. Companies are investing big in it and it will become an in-demand skill in the future. </string> <string name=\"random_text_2\"> Humans are coming closer to the internet at a very fast rate. It means that the volume of data Industries is gathering will increase as time passes because of more users. Industry’s are gradually analyzing the need for this useful information they are getting from their users. It is for sure that the data always tends to an increasing pattern so the company’s are eventually acquiring professionals skilled with Big Data Technologies. According to NASSCOM, India’s Big Data Market will reach 16 billion USD by 2025 from 2 billion USD. The growth of smart devices in India is growing at a very huge rate that will cause growth in the Big Data Market. Since Big Data is growing the demand for Big Data professionals will be high. Hadoop provides personalized recommendations and personalizes ad targeting features. Companies are generating thousands of petabytes of data every day so the demand for Big Data professionals is very high. Even after a few years, Hadoop will be considered as the must-learn skill for the data-scientist and Big Data Technology. Companies are investing big in it and it will become an in-demand skill in the future. </string> </resources>", "e": 4092, "s": 1159, "text": null }, { "code": null, "e": 4118, "s": 4092, "text": "Step 3: Designing the UI " }, { "code": null, "e": 4485, "s": 4118, "text": "In the activity_main.xml file add the NestedScrollView and inside NestedScrollView add a LinearLayout and inside LinearLayout add two TextView to display the strings which are created inside the strings.xml file and one Button between the TextView. Here is the code for the activity_main.xml file. One can add as many views inside the NestedScrollView’s LinearLayout" }, { "code": null, "e": 4489, "s": 4485, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- Nested Scroll view --> <androidx.core.widget.NestedScrollView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <!-- Linear layout to contain 2 text view and button --> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <!-- showing random text 1 from strings.xml file --> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"@string/random_text_1\" /> <!-- simple button --> <Button android:layout_width=\"match_parent\" android:layout_height=\"160dp\" android:background=\"@color/colorPrimary\" android:text=\"Nested Scroll View \" android:textColor=\"#ffffff\" android:textSize=\"32dp\" /> <!-- showing random text 2 from strings.xml file --> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"@string/random_text_2\" /> </LinearLayout> </androidx.core.widget.NestedScrollView> </RelativeLayout>", "e": 6099, "s": 4489, "text": null }, { "code": null, "e": 6143, "s": 6099, "text": "Step 4: Working with MainActivity.java file" }, { "code": null, "e": 6220, "s": 6143, "text": "There is nothing to do with the MainActivity.java file, so keep it as it is." }, { "code": null, "e": 6225, "s": 6220, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }}", "e": 6521, "s": 6225, "text": null }, { "code": null, "e": 6532, "s": 6521, "text": "Resources:" }, { "code": null, "e": 6570, "s": 6532, "text": "Download Complete Project from Github" }, { "code": null, "e": 6592, "s": 6570, "text": "Download the Apk file" }, { "code": null, "e": 6600, "s": 6592, "text": "android" }, { "code": null, "e": 6613, "s": 6600, "text": "Android-View" }, { "code": null, "e": 6621, "s": 6613, "text": "Android" }, { "code": null, "e": 6626, "s": 6621, "text": "Java" }, { "code": null, "e": 6631, "s": 6626, "text": "Java" }, { "code": null, "e": 6639, "s": 6631, "text": "Android" } ]
Integer.valueOf() vs Integer.parseInt() with Examples
26 Nov, 2019 Integer.parseInt(): While operating upon strings, there are times when we need to convert a number represented as a string into an integer type. The method generally used to convert String to Integer in Java is parseInt(). This method belongs to Integer class in java.lang package. It takes a valid string as a parameter and parses it into primitive data type int. It only accepts String as a parameter and on passing values of any other data type, it produces an error due to incompatible types. There are two variants of this method: Syntax: public static int parseInt(String s) throws NumberFormatException public static int parseInt(String s, int radix) throws NumberFormatException Example: // Java program to demonstrate working parseInt() public class GFG { public static void main(String args[]) { int decimalExample = Integer.parseInt("20"); int signedPositiveExample = Integer.parseInt("+20"); int signedNegativeExample = Integer.parseInt("-20"); int radixExample = Integer.parseInt("20", 16); int stringExample = Integer.parseInt("geeks", 29); System.out.println(decimalExample); System.out.println(signedPositiveExample); System.out.println(signedNegativeExample); System.out.println(radixExample); System.out.println(stringExample); }} 20 20 -20 32 11670324 Integer.valueOf(): This method is a static method belonging to the java.lang package which returns the relevant Integer Object holding the value of the argument passed. This method can take an integer or a String as a parameter. But when the given String is invalid, it provides an error. This method can also take in a character as a parameter but the output will be its corresponding Unicode value. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range. Syntax: public static Integer valueOf(int a) public static Integer valueOf(String str) public static Integer valueOf(String str, int base) Example: // Java program to illustrate the// java.lang.Integer.valueOf(int a)import java.lang.*; public class Geeks { public static void main(String[] args) { Integer obj = new Integer(10); // Returns an Integer instance // representing the specified int value System.out.println("Output Value = " + obj.valueOf(85)); }} Output Value = 85 Differences between Integer.parseInt() and Integer.valueOf() Integer.valueOf() returns an Integer object while Integer.parseInt() returns a primitive int.// Program to show the use// of Integer.parseInt() method class Test1 { public static void main(String args[]) { String s = "77"; // Primitive int is returned int str = Integer.parseInt(s); System.out.print(str); // Integer object is returned int str1 = Integer.valueOf(s); System.out.print(str1); }}Output:7777 Both String and integer can be passed a parameter to Integer.valueOf() whereas only a String can be passed as parameter to Integer.parseInt().// Program to show that Integer.parseInt()// cannot take integer as parameter class Test3 { public static void main(String args[]) { int val = 99; try { // It can take int as a parameter int str1 = Integer.valueOf(val); System.out.print(str1); // It cannot take an int as a parameter // Hence will throw an exception int str = Integer.parseInt(val); System.out.print(str); } catch (Exception e) { System.out.print(e); } }}Compilation Error:prog.java:18: error: incompatible types: int cannot be converted to String int str = Integer.parseInt(val); ^ 1 error Integer.valueOf() can take a character as parameter and will return its corresponding unicode value whereas Integer.parseInt() will produce an error on passing a character as parameter.// Program to test the method// when a character is passed as a parameter class Test3 { public static void main(String args[]) { char val = 'A'; try { // It can take char as a parameter int str1 = Integer.valueOf(val); System.out.print(str1); // It cannot take char as a parameter // Hence will throw an exception int str = Integer.parseInt(val); System.out.print(str); } catch (Exception e) { System.out.print(e); } }}Compilation Error:prog.java:18: error: incompatible types: char cannot be converted to String int str = Integer.parseInt(val); ^ 1 error Integer.valueOf() returns an Integer object while Integer.parseInt() returns a primitive int.// Program to show the use// of Integer.parseInt() method class Test1 { public static void main(String args[]) { String s = "77"; // Primitive int is returned int str = Integer.parseInt(s); System.out.print(str); // Integer object is returned int str1 = Integer.valueOf(s); System.out.print(str1); }}Output:7777 // Program to show the use// of Integer.parseInt() method class Test1 { public static void main(String args[]) { String s = "77"; // Primitive int is returned int str = Integer.parseInt(s); System.out.print(str); // Integer object is returned int str1 = Integer.valueOf(s); System.out.print(str1); }} 7777 Both String and integer can be passed a parameter to Integer.valueOf() whereas only a String can be passed as parameter to Integer.parseInt().// Program to show that Integer.parseInt()// cannot take integer as parameter class Test3 { public static void main(String args[]) { int val = 99; try { // It can take int as a parameter int str1 = Integer.valueOf(val); System.out.print(str1); // It cannot take an int as a parameter // Hence will throw an exception int str = Integer.parseInt(val); System.out.print(str); } catch (Exception e) { System.out.print(e); } }}Compilation Error:prog.java:18: error: incompatible types: int cannot be converted to String int str = Integer.parseInt(val); ^ 1 error // Program to show that Integer.parseInt()// cannot take integer as parameter class Test3 { public static void main(String args[]) { int val = 99; try { // It can take int as a parameter int str1 = Integer.valueOf(val); System.out.print(str1); // It cannot take an int as a parameter // Hence will throw an exception int str = Integer.parseInt(val); System.out.print(str); } catch (Exception e) { System.out.print(e); } }} Compilation Error: prog.java:18: error: incompatible types: int cannot be converted to String int str = Integer.parseInt(val); ^ 1 error Integer.valueOf() can take a character as parameter and will return its corresponding unicode value whereas Integer.parseInt() will produce an error on passing a character as parameter.// Program to test the method// when a character is passed as a parameter class Test3 { public static void main(String args[]) { char val = 'A'; try { // It can take char as a parameter int str1 = Integer.valueOf(val); System.out.print(str1); // It cannot take char as a parameter // Hence will throw an exception int str = Integer.parseInt(val); System.out.print(str); } catch (Exception e) { System.out.print(e); } }}Compilation Error:prog.java:18: error: incompatible types: char cannot be converted to String int str = Integer.parseInt(val); ^ 1 error // Program to test the method// when a character is passed as a parameter class Test3 { public static void main(String args[]) { char val = 'A'; try { // It can take char as a parameter int str1 = Integer.valueOf(val); System.out.print(str1); // It cannot take char as a parameter // Hence will throw an exception int str = Integer.parseInt(val); System.out.print(str); } catch (Exception e) { System.out.print(e); } }} Compilation Error: prog.java:18: error: incompatible types: char cannot be converted to String int str = Integer.parseInt(val); ^ 1 error Table of difference deepthisenthil Java-Functions Java-Integer Java-lang package Difference Between Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Nov, 2019" }, { "code": null, "e": 72, "s": 52, "text": "Integer.parseInt():" }, { "code": null, "e": 549, "s": 72, "text": "While operating upon strings, there are times when we need to convert a number represented as a string into an integer type. The method generally used to convert String to Integer in Java is parseInt(). This method belongs to Integer class in java.lang package. It takes a valid string as a parameter and parses it into primitive data type int. It only accepts String as a parameter and on passing values of any other data type, it produces an error due to incompatible types." }, { "code": null, "e": 588, "s": 549, "text": "There are two variants of this method:" }, { "code": null, "e": 596, "s": 588, "text": "Syntax:" }, { "code": null, "e": 662, "s": 596, "text": "public static int parseInt(String s) throws NumberFormatException" }, { "code": null, "e": 739, "s": 662, "text": "public static int parseInt(String s, int radix) throws NumberFormatException" }, { "code": null, "e": 748, "s": 739, "text": "Example:" }, { "code": "// Java program to demonstrate working parseInt() public class GFG { public static void main(String args[]) { int decimalExample = Integer.parseInt(\"20\"); int signedPositiveExample = Integer.parseInt(\"+20\"); int signedNegativeExample = Integer.parseInt(\"-20\"); int radixExample = Integer.parseInt(\"20\", 16); int stringExample = Integer.parseInt(\"geeks\", 29); System.out.println(decimalExample); System.out.println(signedPositiveExample); System.out.println(signedNegativeExample); System.out.println(radixExample); System.out.println(stringExample); }}", "e": 1383, "s": 748, "text": null }, { "code": null, "e": 1406, "s": 1383, "text": "20\n20\n-20\n32\n11670324\n" }, { "code": null, "e": 1425, "s": 1406, "text": "Integer.valueOf():" }, { "code": null, "e": 1931, "s": 1425, "text": "This method is a static method belonging to the java.lang package which returns the relevant Integer Object holding the value of the argument passed. This method can take an integer or a String as a parameter. But when the given String is invalid, it provides an error. This method can also take in a character as a parameter but the output will be its corresponding Unicode value. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range." }, { "code": null, "e": 1939, "s": 1931, "text": "Syntax:" }, { "code": null, "e": 1976, "s": 1939, "text": "public static Integer valueOf(int a)" }, { "code": null, "e": 2018, "s": 1976, "text": "public static Integer valueOf(String str)" }, { "code": null, "e": 2070, "s": 2018, "text": "public static Integer valueOf(String str, int base)" }, { "code": null, "e": 2079, "s": 2070, "text": "Example:" }, { "code": "// Java program to illustrate the// java.lang.Integer.valueOf(int a)import java.lang.*; public class Geeks { public static void main(String[] args) { Integer obj = new Integer(10); // Returns an Integer instance // representing the specified int value System.out.println(\"Output Value = \" + obj.valueOf(85)); }}", "e": 2461, "s": 2079, "text": null }, { "code": null, "e": 2480, "s": 2461, "text": "Output Value = 85\n" }, { "code": null, "e": 2541, "s": 2480, "text": "Differences between Integer.parseInt() and Integer.valueOf()" }, { "code": null, "e": 4832, "s": 2541, "text": "Integer.valueOf() returns an Integer object while Integer.parseInt() returns a primitive int.// Program to show the use// of Integer.parseInt() method class Test1 { public static void main(String args[]) { String s = \"77\"; // Primitive int is returned int str = Integer.parseInt(s); System.out.print(str); // Integer object is returned int str1 = Integer.valueOf(s); System.out.print(str1); }}Output:7777\nBoth String and integer can be passed a parameter to Integer.valueOf() whereas only a String can be passed as parameter to Integer.parseInt().// Program to show that Integer.parseInt()// cannot take integer as parameter class Test3 { public static void main(String args[]) { int val = 99; try { // It can take int as a parameter int str1 = Integer.valueOf(val); System.out.print(str1); // It cannot take an int as a parameter // Hence will throw an exception int str = Integer.parseInt(val); System.out.print(str); } catch (Exception e) { System.out.print(e); } }}Compilation Error:prog.java:18: error: incompatible types:\nint cannot be converted to String\n int str = Integer.parseInt(val);\n ^\n1 error\nInteger.valueOf() can take a character as parameter and will return its corresponding unicode value whereas Integer.parseInt() will produce an error on passing a character as parameter.// Program to test the method// when a character is passed as a parameter class Test3 { public static void main(String args[]) { char val = 'A'; try { // It can take char as a parameter int str1 = Integer.valueOf(val); System.out.print(str1); // It cannot take char as a parameter // Hence will throw an exception int str = Integer.parseInt(val); System.out.print(str); } catch (Exception e) { System.out.print(e); } }}Compilation Error:prog.java:18: error: incompatible types:\nchar cannot be converted to String\n int str = Integer.parseInt(val);\n ^\n1 error\n\n" }, { "code": null, "e": 5301, "s": 4832, "text": "Integer.valueOf() returns an Integer object while Integer.parseInt() returns a primitive int.// Program to show the use// of Integer.parseInt() method class Test1 { public static void main(String args[]) { String s = \"77\"; // Primitive int is returned int str = Integer.parseInt(s); System.out.print(str); // Integer object is returned int str1 = Integer.valueOf(s); System.out.print(str1); }}Output:7777\n" }, { "code": "// Program to show the use// of Integer.parseInt() method class Test1 { public static void main(String args[]) { String s = \"77\"; // Primitive int is returned int str = Integer.parseInt(s); System.out.print(str); // Integer object is returned int str1 = Integer.valueOf(s); System.out.print(str1); }}", "e": 5665, "s": 5301, "text": null }, { "code": null, "e": 5671, "s": 5665, "text": "7777\n" }, { "code": null, "e": 6562, "s": 5671, "text": "Both String and integer can be passed a parameter to Integer.valueOf() whereas only a String can be passed as parameter to Integer.parseInt().// Program to show that Integer.parseInt()// cannot take integer as parameter class Test3 { public static void main(String args[]) { int val = 99; try { // It can take int as a parameter int str1 = Integer.valueOf(val); System.out.print(str1); // It cannot take an int as a parameter // Hence will throw an exception int str = Integer.parseInt(val); System.out.print(str); } catch (Exception e) { System.out.print(e); } }}Compilation Error:prog.java:18: error: incompatible types:\nint cannot be converted to String\n int str = Integer.parseInt(val);\n ^\n1 error\n" }, { "code": "// Program to show that Integer.parseInt()// cannot take integer as parameter class Test3 { public static void main(String args[]) { int val = 99; try { // It can take int as a parameter int str1 = Integer.valueOf(val); System.out.print(str1); // It cannot take an int as a parameter // Hence will throw an exception int str = Integer.parseInt(val); System.out.print(str); } catch (Exception e) { System.out.print(e); } }}", "e": 7124, "s": 6562, "text": null }, { "code": null, "e": 7143, "s": 7124, "text": "Compilation Error:" }, { "code": null, "e": 7313, "s": 7143, "text": "prog.java:18: error: incompatible types:\nint cannot be converted to String\n int str = Integer.parseInt(val);\n ^\n1 error\n" }, { "code": null, "e": 8246, "s": 7313, "text": "Integer.valueOf() can take a character as parameter and will return its corresponding unicode value whereas Integer.parseInt() will produce an error on passing a character as parameter.// Program to test the method// when a character is passed as a parameter class Test3 { public static void main(String args[]) { char val = 'A'; try { // It can take char as a parameter int str1 = Integer.valueOf(val); System.out.print(str1); // It cannot take char as a parameter // Hence will throw an exception int str = Integer.parseInt(val); System.out.print(str); } catch (Exception e) { System.out.print(e); } }}Compilation Error:prog.java:18: error: incompatible types:\nchar cannot be converted to String\n int str = Integer.parseInt(val);\n ^\n1 error\n\n" }, { "code": "// Program to test the method// when a character is passed as a parameter class Test3 { public static void main(String args[]) { char val = 'A'; try { // It can take char as a parameter int str1 = Integer.valueOf(val); System.out.print(str1); // It cannot take char as a parameter // Hence will throw an exception int str = Integer.parseInt(val); System.out.print(str); } catch (Exception e) { System.out.print(e); } }}", "e": 8805, "s": 8246, "text": null }, { "code": null, "e": 8824, "s": 8805, "text": "Compilation Error:" }, { "code": null, "e": 8996, "s": 8824, "text": "prog.java:18: error: incompatible types:\nchar cannot be converted to String\n int str = Integer.parseInt(val);\n ^\n1 error\n\n" }, { "code": null, "e": 9016, "s": 8996, "text": "Table of difference" }, { "code": null, "e": 9031, "s": 9016, "text": "deepthisenthil" }, { "code": null, "e": 9046, "s": 9031, "text": "Java-Functions" }, { "code": null, "e": 9059, "s": 9046, "text": "Java-Integer" }, { "code": null, "e": 9077, "s": 9059, "text": "Java-lang package" }, { "code": null, "e": 9096, "s": 9077, "text": "Difference Between" }, { "code": null, "e": 9101, "s": 9096, "text": "Java" }, { "code": null, "e": 9106, "s": 9101, "text": "Java" } ]
PHP | strip_tags() Function
02 Nov, 2020 The strip_tags() function is an inbuilt function in PHP which is used to strips a string from HTML, and PHP tags. This function returns a string with all NULL bytes, HTML, and PHP tags stripped from a given $str. Syntax: string strip_tags( $str, $allowable_tags ) Parameters: This function accepts two parameters as mentioned above and described below: $string: It is a required parameter that specifies the string to be check. $allow: It is an optional parameter that specifies allowable tags. These tags will not be removed. Return Value: This function Returns the stripped string. Exceptions: This function strip HTML comments and PHP tags. It can not be used this in $allow tags because this is already hardcoded. PHP 5.3.4 and later versions, ignored the self-closing XHTML tags strip_tags() does not validate the HTML. Below programs illustrate the strip_tags() function in PHP: Program 1: PHP <?php // PHP programme to illustrate// strip_tags function without $allow parameterecho strip_tags("Hello <b>GeeksforGeeks!</b>");?> Hello GeeksforGeeks! Program 2: PHP <?php // PHP programme to illustrate// strip_tags function with $allow parameter echo strip_tags("Hello <b><i>GeeksorGeeks!</i></b>", "<b>");?> Hello <b>GeeksorGeeks!</b> Related Articles: PHP | str_split() Function PHP | chop() Function Reference: http://php.net/manual/en/function.strip-tags.php arorakashish0911 PHP-function PHP-string PHP Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Nov, 2020" }, { "code": null, "e": 241, "s": 28, "text": "The strip_tags() function is an inbuilt function in PHP which is used to strips a string from HTML, and PHP tags. This function returns a string with all NULL bytes, HTML, and PHP tags stripped from a given $str." }, { "code": null, "e": 250, "s": 241, "text": "Syntax: " }, { "code": null, "e": 298, "s": 250, "text": "string strip_tags( $str, $allowable_tags ) \n\n\n\n" }, { "code": null, "e": 388, "s": 298, "text": "Parameters: This function accepts two parameters as mentioned above and described below: " }, { "code": null, "e": 463, "s": 388, "text": "$string: It is a required parameter that specifies the string to be check." }, { "code": null, "e": 562, "s": 463, "text": "$allow: It is an optional parameter that specifies allowable tags. These tags will not be removed." }, { "code": null, "e": 619, "s": 562, "text": "Return Value: This function Returns the stripped string." }, { "code": null, "e": 633, "s": 619, "text": "Exceptions: " }, { "code": null, "e": 755, "s": 633, "text": "This function strip HTML comments and PHP tags. It can not be used this in $allow tags because this is already hardcoded." }, { "code": null, "e": 821, "s": 755, "text": "PHP 5.3.4 and later versions, ignored the self-closing XHTML tags" }, { "code": null, "e": 862, "s": 821, "text": "strip_tags() does not validate the HTML." }, { "code": null, "e": 923, "s": 862, "text": "Below programs illustrate the strip_tags() function in PHP: " }, { "code": null, "e": 936, "s": 923, "text": "Program 1: " }, { "code": null, "e": 940, "s": 936, "text": "PHP" }, { "code": "<?php // PHP programme to illustrate// strip_tags function without $allow parameterecho strip_tags(\"Hello <b>GeeksforGeeks!</b>\");?>", "e": 1073, "s": 940, "text": null }, { "code": null, "e": 1099, "s": 1073, "text": "Hello GeeksforGeeks!\n\n\n\n\n" }, { "code": null, "e": 1113, "s": 1101, "text": "Program 2: " }, { "code": null, "e": 1117, "s": 1113, "text": "PHP" }, { "code": "<?php // PHP programme to illustrate// strip_tags function with $allow parameter echo strip_tags(\"Hello <b><i>GeeksorGeeks!</i></b>\", \"<b>\");?>", "e": 1261, "s": 1117, "text": null }, { "code": null, "e": 1293, "s": 1261, "text": "Hello <b>GeeksorGeeks!</b>\n\n\n\n\n" }, { "code": null, "e": 1314, "s": 1295, "text": "Related Articles: " }, { "code": null, "e": 1341, "s": 1314, "text": "PHP | str_split() Function" }, { "code": null, "e": 1363, "s": 1341, "text": "PHP | chop() Function" }, { "code": null, "e": 1424, "s": 1363, "text": "Reference: http://php.net/manual/en/function.strip-tags.php " }, { "code": null, "e": 1441, "s": 1424, "text": "arorakashish0911" }, { "code": null, "e": 1454, "s": 1441, "text": "PHP-function" }, { "code": null, "e": 1465, "s": 1454, "text": "PHP-string" }, { "code": null, "e": 1469, "s": 1465, "text": "PHP" }, { "code": null, "e": 1496, "s": 1469, "text": "Web technologies Questions" }, { "code": null, "e": 1500, "s": 1496, "text": "PHP" } ]
How to delete columns by their name in data.table in R?
We can do this by setting the column to NULL > library(data.table) > df <- data.frame(numbers = 1:10, x = runif(10,25,75)) > data_table <- data.table(df) To delete one column x > data_table[, x:=NULL] > data_table numbers 1: 1 2: 2 3: 3 4: 4 5: 5 6: 6 7: 7 8: 8 9: 9 10: 10 To delete two columns > df <- data.frame(numbers = 0:9, x = runif(10,25,75), y=rnorm(10)) > Data_table <- data.table(df) Data_table[, c("x","y"):=NULL] > Data_table numbers 1: 0 2: 1 3: 2 4: 3 5: 4 6: 5 7: 6 8: 7 9: 8 10: 9
[ { "code": null, "e": 1107, "s": 1062, "text": "We can do this by setting the column to NULL" }, { "code": null, "e": 1216, "s": 1107, "text": "> library(data.table)\n> df <- data.frame(numbers = 1:10, x = runif(10,25,75))\n> data_table <- data.table(df)" }, { "code": null, "e": 1239, "s": 1216, "text": "To delete one column x" }, { "code": null, "e": 1336, "s": 1239, "text": "> data_table[, x:=NULL]\n> data_table\nnumbers\n1: 1\n2: 2\n3: 3\n4: 4\n5: 5\n6: 6\n7: 7\n8: 8\n9: 9\n10: 10" }, { "code": null, "e": 1358, "s": 1336, "text": "To delete two columns" }, { "code": null, "e": 1560, "s": 1358, "text": "> df <- data.frame(numbers = 0:9, x = runif(10,25,75), y=rnorm(10))\n> Data_table <- data.table(df)\nData_table[, c(\"x\",\"y\"):=NULL]\n> Data_table\nnumbers\n1: 0\n2: 1\n3: 2\n4: 3\n5: 4\n6: 5\n7: 6\n8: 7\n9: 8\n10: 9" } ]
Time Series Forecasting with Splunk. Part I. Intro & Kalman Filter. | by Nikolay Ryabykh | Towards Data Science
Time series forecasting is a quite typical task in data analysis. Splunk ML Toolkit provides a couple of well-known methods for this task: Kalman filter and ARIMA. Unfortunately, these methods sometimes fail when encountering a real-world problems. So, let’s take a closer look on them and then consider a couple of other techniques of time series forecasting in Splunk. OK, let’s define a goal. Let we use Splunk to monitor some metrics, such as number of logins to a system, number of transactions in DB, etc. We want to analyse growth of our business (for example, in purposes of capacity planning and resources management). As part of this analysis, we want to predict number of logins for a year based on data of the last several years. Quite a common task, as you can see. But let’s make it more complex with the requirement of flexibility. Because of monitoring not the only metric, our method or algorithm must be quite universal to predict almost any metric without lots of tuning by user. After all, we need to construct a dashboard with such functionality: user selects a metric, specifies few tuning parameters, and gets an appropriate forecast of selected metric for a year. Let’s refresh some basic concepts about time series. In general, time series can be decomposed into several components: trend component, seasonal component, and residual component. Trend is a general direction of changing time series value. Increasing trend, for example, means that the values of time series are, in average, larger than previous ones. Seasonal component stands for some periodic fluctuations in data. For example, number of logins in night hours is constantly smaller than in day hours, as well as number of logins in weekdays is larger than on weekends. Residual component is the difference between time series values and determinate components (trend, seasonality) and often stands for some kind of noise. There are two main models to deal with these components. In additive model initial time series represents as the sum of components, in multiplicative model — as the product of them. Sometimes it might be a tough choice what model to prefer. Generally, multiplicative model is more preferable if amplitude of seasonal fluctuations increases over time. For each time series one can calculate mean, variance, and autocorrelation. Time series is stationary if these parameters are constant over time. In the picture below you find some examples of stationary (blue) and non-stationary (yellow, red, violet) time series. Mean and variance of ‘blue’ series are equal to 0 and 1 respectively, so this series is stationary. ‘Yellow’ series shows an increasing trend, that is mean is not constant. ‘Red’ series shows an obvious daily seasonality, that is autocorrelation function has a local maximum at the lags of 24, 48, ... hours — and it’s not constant, too. ‘Violet’ series shows an increasing trend and disturbance, that is mean and variance are not constant as well. Real-word time series are seldom stationary. But there are a lot of techniques and transformations for turning them into stationary ones. Let’s turn ML Toolkit on and try to predict our series. Kalman filtering is an algorithm that produces estimates of unknown variables that tend to be more accurate than those based on a single measurement alone (sorry, I copypasted definition from wiki article). In other words, Kalman filter takes time series as input and performs some kind of smoothing and denoising. After this, smoothed series might be predicted. But one should take into account that Kalman filter is firstly for denoising, rather than forecasting. That’s why the results of forecasting might be a bit inappropriate. Go to Assistants > Forecast Time Series and select Kalman filter as algorithm. ML Toolkit provides several methods for prediction: LL (Local Level) to predict only local level of time series (without any trend or seasonality); LLT (Local Level Trend) to predict only trend; LLP (Seasonal Local Level) to predict only seasonal component; LLP5 (combines LLT and LLP) to account for both trend and seasonality. First of all, let’s try to apply Kalman filter to one of non-stationary time series from example above just to check smoothing capabilities. Let’s select “yellow” series — it’s just a sum of constant trend and normally distributed noise. I got it by this SPL query (normal is a custom external command that returns a normally distributed value with mean and variance from fields specified in loc and scale parameters respectively): | gentimes start=”01/01/2018" increment=1h| eval _time=starttime, loc=0, scale=20| normal loc=loc scale=scale | streamstats count as cnt| eval gen_normal = gen_normal + cnt| table _time, gen_normal| rename gen_normal as “Non-stationary time series (trend)” Ok, let’s apply Kalman filter with algorithm “LLT”, future timespan = 200, confidence interval = 95. Looks nice. Filter really removes normally distributed noise and predicts actual trend. Now let’s try to predict our number of logins. Our time series includes apparently both trend and seasonal components, so let’s select prediction algorithm = LLP5, future timespan = 365 (predict for a year), period = 365 (as we expect this seasonal period to be the biggest one). Well... It’s pretty obvious that the result is slightly not as expected. It seems that filter considers our fluctuations in data as a noise. Thereby, filter eliminates this noise and keeps only the trend component. But it’s a bit confused that “LLP” part of algorithm, which is responsible for seasonal component, doesn’t work at all. Anyway, this forecast is unacceptable. There is, however, a silver lining. First of all, upper and lower bounds of confidence interval are very useful for outliers detection. Secondly, it cannot be denied that the forecast of trend component is rather well. So, let’s try to filter out all outliers and remove trend component from initial data. Notice that variance of initial time series increases over time. That’s why it seems multiplicative model to be more appropriate in our case. So, let’s divide initial values by the values of trend component. | inputlookup daylogins.csv| timechart span=1d fixedrange=f max(daylogins) as daylogins| predict “daylogins” as prediction algorithm=”LLT” future_timespan=365 period=365 lower”95"=lower”95" upper”95"=upper”95"| eval daylogins = case(daylogins < ‘lower95(prediction)’, ‘lower95(prediction)’, daylogins > ‘upper95(prediction)’, ‘upper95(prediction)’, 1=1, daylogins)| eval season = daylogins / prediction| table _time, season| where _time<strptime(“2018–01–01”, “%F”) Here I use a predict command in SPL. This is a command for Kalman filtering, you can check it by clicking the “Show SPL” button on the “Forecast Time Series” dashboard. Change method to LLP and click “Forecast”. Well, not bad. Main seasonal profiles (like a big recession after the New Year) are captured and predicted almost perfectly. There is an extended New Year holiday in Russia. It starts on the January, 1 and lasts about 8–10 days (actual duration varies from one year to the next). It figures that user activity in many areas in those days is much less than in other days. But, as always, the devil is in the detail. Look at the predicted spike right after New Year holiday. It seems it is the same as a year ago. Actually, they seems to be too identical. Notice that in 2015 and 2016 there wasn’t anything similar to this peak. Similarity becomes even more obvious if turning off outliers removal. Outlier from Feb, 2017 is repeated in prediction, but outlier from May, 2016 is not. So, it seems that Kalman filter with LLP algorithm overrates values of the last period (last 365 days in our case) and not pays any mind to corresponding values of previous periods. The same situation is with the high season in New Year’s Eve. However, such feature of Kalman filtering does not make this forecast totally inadequate. It might be useful if we really want to rely only on the last period of data. For example, we’re going to predict number of logins for a week based on data of previous weeks just for real-time detection of critical problems. If number of logins decreases remarkably, it likely stands for some issues with availability of authentication server or something like that. For that monitoring we can create a simple and clean forecast and just compare new data to the bounds of confidence interval. OK, let’s get back to initial forecast for a year. Despite its apparent shortcomings, forecast of seasonal component of our time series is rather reasonable. So, let’s multiply predicted trend component by predicted seasonal component for reverting to desired number of logins. | inputlookup daylogins.csv | timechart span=1d fixedrange=f max(daylogins) as daylogins | predict "daylogins" as prediction algorithm="LLT" future_timespan=365 lower"95"=lower"95" upper"95"=upper"95" | eval daylogins = case(daylogins < 'lower95(prediction)', 'lower95(prediction)', daylogins > 'upper95(prediction)', 'upper95(prediction)', 1=1, daylogins) | eval season = daylogins / prediction | predict "season" as season_prediction algorithm="LLP" future_timespan=365 period=365 lower"0"=lower"0" upper"0"=upper"0"| eval prediction = prediction * season_prediction| table _time, daylogins, prediction| eval prediction = if(isnull(daylogins), prediction, null)| where _time<strptime("2019-01-01", "%F") Looks pretty nice. Notice that I’ve finally implemented this forecast in pure SPL without ML Toolkit Assistant GUI. So, I can insert this search into any dashboard of any application (just take care of permissions to knowledge objects). The only parameter I need to specify is the period of seasonal component (i.e. maximum seasonal period in case of multiple seasonality). You can allow user to specify this parameter on a dashboard via a simple input text box with default value of 365. Also it’s possible to calculate the maximum seasonal period automatically using Fourier transform or analyzing autocorrelation function (we’ll talk about it a bit later, I think). Let’s make a brief review of Kalman filter in Splunk. It is a simple and useful tool for time series forecasting. One can create a forecast easily with only one SPL command without tuning tons of parameters. Filter (following its name) is good in smoothing of noisy time series. But this simplicity means the lack of flexibility. You cannot control seasonal periods at all. In case of multiple seasonality you can rely only on internal algorithms of filter. Seasonal forecast takes too little account of the values outside of the last period. There is no any parameter like a “smoothing coefficient” for the tuning of “denoising sensitivity”. Therefore, filter sometimes performs very aggressive smoothing, and it causes to the loss of valuable information. Well, let’s call it a night. In the next part let’s look more closely at ARIMA in Splunk. Stay tuned!
[ { "code": null, "e": 543, "s": 172, "text": "Time series forecasting is a quite typical task in data analysis. Splunk ML Toolkit provides a couple of well-known methods for this task: Kalman filter and ARIMA. Unfortunately, these methods sometimes fail when encountering a real-world problems. So, let’s take a closer look on them and then consider a couple of other techniques of time series forecasting in Splunk." }, { "code": null, "e": 914, "s": 543, "text": "OK, let’s define a goal. Let we use Splunk to monitor some metrics, such as number of logins to a system, number of transactions in DB, etc. We want to analyse growth of our business (for example, in purposes of capacity planning and resources management). As part of this analysis, we want to predict number of logins for a year based on data of the last several years." }, { "code": null, "e": 1360, "s": 914, "text": "Quite a common task, as you can see. But let’s make it more complex with the requirement of flexibility. Because of monitoring not the only metric, our method or algorithm must be quite universal to predict almost any metric without lots of tuning by user. After all, we need to construct a dashboard with such functionality: user selects a metric, specifies few tuning parameters, and gets an appropriate forecast of selected metric for a year." }, { "code": null, "e": 2086, "s": 1360, "text": "Let’s refresh some basic concepts about time series. In general, time series can be decomposed into several components: trend component, seasonal component, and residual component. Trend is a general direction of changing time series value. Increasing trend, for example, means that the values of time series are, in average, larger than previous ones. Seasonal component stands for some periodic fluctuations in data. For example, number of logins in night hours is constantly smaller than in day hours, as well as number of logins in weekdays is larger than on weekends. Residual component is the difference between time series values and determinate components (trend, seasonality) and often stands for some kind of noise." }, { "code": null, "e": 2437, "s": 2086, "text": "There are two main models to deal with these components. In additive model initial time series represents as the sum of components, in multiplicative model — as the product of them. Sometimes it might be a tough choice what model to prefer. Generally, multiplicative model is more preferable if amplitude of seasonal fluctuations increases over time." }, { "code": null, "e": 2702, "s": 2437, "text": "For each time series one can calculate mean, variance, and autocorrelation. Time series is stationary if these parameters are constant over time. In the picture below you find some examples of stationary (blue) and non-stationary (yellow, red, violet) time series." }, { "code": null, "e": 3151, "s": 2702, "text": "Mean and variance of ‘blue’ series are equal to 0 and 1 respectively, so this series is stationary. ‘Yellow’ series shows an increasing trend, that is mean is not constant. ‘Red’ series shows an obvious daily seasonality, that is autocorrelation function has a local maximum at the lags of 24, 48, ... hours — and it’s not constant, too. ‘Violet’ series shows an increasing trend and disturbance, that is mean and variance are not constant as well." }, { "code": null, "e": 3289, "s": 3151, "text": "Real-word time series are seldom stationary. But there are a lot of techniques and transformations for turning them into stationary ones." }, { "code": null, "e": 3345, "s": 3289, "text": "Let’s turn ML Toolkit on and try to predict our series." }, { "code": null, "e": 3879, "s": 3345, "text": "Kalman filtering is an algorithm that produces estimates of unknown variables that tend to be more accurate than those based on a single measurement alone (sorry, I copypasted definition from wiki article). In other words, Kalman filter takes time series as input and performs some kind of smoothing and denoising. After this, smoothed series might be predicted. But one should take into account that Kalman filter is firstly for denoising, rather than forecasting. That’s why the results of forecasting might be a bit inappropriate." }, { "code": null, "e": 3958, "s": 3879, "text": "Go to Assistants > Forecast Time Series and select Kalman filter as algorithm." }, { "code": null, "e": 4010, "s": 3958, "text": "ML Toolkit provides several methods for prediction:" }, { "code": null, "e": 4106, "s": 4010, "text": "LL (Local Level) to predict only local level of time series (without any trend or seasonality);" }, { "code": null, "e": 4153, "s": 4106, "text": "LLT (Local Level Trend) to predict only trend;" }, { "code": null, "e": 4216, "s": 4153, "text": "LLP (Seasonal Local Level) to predict only seasonal component;" }, { "code": null, "e": 4287, "s": 4216, "text": "LLP5 (combines LLT and LLP) to account for both trend and seasonality." }, { "code": null, "e": 4719, "s": 4287, "text": "First of all, let’s try to apply Kalman filter to one of non-stationary time series from example above just to check smoothing capabilities. Let’s select “yellow” series — it’s just a sum of constant trend and normally distributed noise. I got it by this SPL query (normal is a custom external command that returns a normally distributed value with mean and variance from fields specified in loc and scale parameters respectively):" }, { "code": null, "e": 4976, "s": 4719, "text": "| gentimes start=”01/01/2018\" increment=1h| eval _time=starttime, loc=0, scale=20| normal loc=loc scale=scale | streamstats count as cnt| eval gen_normal = gen_normal + cnt| table _time, gen_normal| rename gen_normal as “Non-stationary time series (trend)”" }, { "code": null, "e": 5077, "s": 4976, "text": "Ok, let’s apply Kalman filter with algorithm “LLT”, future timespan = 200, confidence interval = 95." }, { "code": null, "e": 5165, "s": 5077, "text": "Looks nice. Filter really removes normally distributed noise and predicts actual trend." }, { "code": null, "e": 5445, "s": 5165, "text": "Now let’s try to predict our number of logins. Our time series includes apparently both trend and seasonal components, so let’s select prediction algorithm = LLP5, future timespan = 365 (predict for a year), period = 365 (as we expect this seasonal period to be the biggest one)." }, { "code": null, "e": 5819, "s": 5445, "text": "Well... It’s pretty obvious that the result is slightly not as expected. It seems that filter considers our fluctuations in data as a noise. Thereby, filter eliminates this noise and keeps only the trend component. But it’s a bit confused that “LLP” part of algorithm, which is responsible for seasonal component, doesn’t work at all. Anyway, this forecast is unacceptable." }, { "code": null, "e": 6333, "s": 5819, "text": "There is, however, a silver lining. First of all, upper and lower bounds of confidence interval are very useful for outliers detection. Secondly, it cannot be denied that the forecast of trend component is rather well. So, let’s try to filter out all outliers and remove trend component from initial data. Notice that variance of initial time series increases over time. That’s why it seems multiplicative model to be more appropriate in our case. So, let’s divide initial values by the values of trend component." }, { "code": null, "e": 6799, "s": 6333, "text": "| inputlookup daylogins.csv| timechart span=1d fixedrange=f max(daylogins) as daylogins| predict “daylogins” as prediction algorithm=”LLT” future_timespan=365 period=365 lower”95\"=lower”95\" upper”95\"=upper”95\"| eval daylogins = case(daylogins < ‘lower95(prediction)’, ‘lower95(prediction)’, daylogins > ‘upper95(prediction)’, ‘upper95(prediction)’, 1=1, daylogins)| eval season = daylogins / prediction| table _time, season| where _time<strptime(“2018–01–01”, “%F”)" }, { "code": null, "e": 6968, "s": 6799, "text": "Here I use a predict command in SPL. This is a command for Kalman filtering, you can check it by clicking the “Show SPL” button on the “Forecast Time Series” dashboard." }, { "code": null, "e": 7011, "s": 6968, "text": "Change method to LLP and click “Forecast”." }, { "code": null, "e": 7136, "s": 7011, "text": "Well, not bad. Main seasonal profiles (like a big recession after the New Year) are captured and predicted almost perfectly." }, { "code": null, "e": 7382, "s": 7136, "text": "There is an extended New Year holiday in Russia. It starts on the January, 1 and lasts about 8–10 days (actual duration varies from one year to the next). It figures that user activity in many areas in those days is much less than in other days." }, { "code": null, "e": 7708, "s": 7382, "text": "But, as always, the devil is in the detail. Look at the predicted spike right after New Year holiday. It seems it is the same as a year ago. Actually, they seems to be too identical. Notice that in 2015 and 2016 there wasn’t anything similar to this peak. Similarity becomes even more obvious if turning off outliers removal." }, { "code": null, "e": 7975, "s": 7708, "text": "Outlier from Feb, 2017 is repeated in prediction, but outlier from May, 2016 is not. So, it seems that Kalman filter with LLP algorithm overrates values of the last period (last 365 days in our case) and not pays any mind to corresponding values of previous periods." }, { "code": null, "e": 8037, "s": 7975, "text": "The same situation is with the high season in New Year’s Eve." }, { "code": null, "e": 8620, "s": 8037, "text": "However, such feature of Kalman filtering does not make this forecast totally inadequate. It might be useful if we really want to rely only on the last period of data. For example, we’re going to predict number of logins for a week based on data of previous weeks just for real-time detection of critical problems. If number of logins decreases remarkably, it likely stands for some issues with availability of authentication server or something like that. For that monitoring we can create a simple and clean forecast and just compare new data to the bounds of confidence interval." }, { "code": null, "e": 8898, "s": 8620, "text": "OK, let’s get back to initial forecast for a year. Despite its apparent shortcomings, forecast of seasonal component of our time series is rather reasonable. So, let’s multiply predicted trend component by predicted seasonal component for reverting to desired number of logins." }, { "code": null, "e": 9604, "s": 8898, "text": "| inputlookup daylogins.csv | timechart span=1d fixedrange=f max(daylogins) as daylogins | predict \"daylogins\" as prediction algorithm=\"LLT\" future_timespan=365 lower\"95\"=lower\"95\" upper\"95\"=upper\"95\" | eval daylogins = case(daylogins < 'lower95(prediction)', 'lower95(prediction)', daylogins > 'upper95(prediction)', 'upper95(prediction)', 1=1, daylogins) | eval season = daylogins / prediction | predict \"season\" as season_prediction algorithm=\"LLP\" future_timespan=365 period=365 lower\"0\"=lower\"0\" upper\"0\"=upper\"0\"| eval prediction = prediction * season_prediction| table _time, daylogins, prediction| eval prediction = if(isnull(daylogins), prediction, null)| where _time<strptime(\"2019-01-01\", \"%F\")" }, { "code": null, "e": 10273, "s": 9604, "text": "Looks pretty nice. Notice that I’ve finally implemented this forecast in pure SPL without ML Toolkit Assistant GUI. So, I can insert this search into any dashboard of any application (just take care of permissions to knowledge objects). The only parameter I need to specify is the period of seasonal component (i.e. maximum seasonal period in case of multiple seasonality). You can allow user to specify this parameter on a dashboard via a simple input text box with default value of 365. Also it’s possible to calculate the maximum seasonal period automatically using Fourier transform or analyzing autocorrelation function (we’ll talk about it a bit later, I think)." }, { "code": null, "e": 10327, "s": 10273, "text": "Let’s make a brief review of Kalman filter in Splunk." }, { "code": null, "e": 10387, "s": 10327, "text": "It is a simple and useful tool for time series forecasting." }, { "code": null, "e": 10481, "s": 10387, "text": "One can create a forecast easily with only one SPL command without tuning tons of parameters." }, { "code": null, "e": 10552, "s": 10481, "text": "Filter (following its name) is good in smoothing of noisy time series." }, { "code": null, "e": 10603, "s": 10552, "text": "But this simplicity means the lack of flexibility." }, { "code": null, "e": 10731, "s": 10603, "text": "You cannot control seasonal periods at all. In case of multiple seasonality you can rely only on internal algorithms of filter." }, { "code": null, "e": 10816, "s": 10731, "text": "Seasonal forecast takes too little account of the values outside of the last period." }, { "code": null, "e": 11031, "s": 10816, "text": "There is no any parameter like a “smoothing coefficient” for the tuning of “denoising sensitivity”. Therefore, filter sometimes performs very aggressive smoothing, and it causes to the loss of valuable information." } ]
Spring - Quick Guide
Spring is the most popular application development framework for enterprise Java. Millions of developers around the world use Spring Framework to create high performing, easily testable, and reusable code. Spring framework is an open source Java platform. It was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003. Spring is lightweight when it comes to size and transparency. The basic version of Spring framework is around 2MB. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make J2EE development easier to use and promotes good programming practices by enabling a POJO-based programming model. Following is the list of few of the great benefits of using Spring Framework − Spring enables developers to develop enterprise-class applications using POJOs. The benefit of using only POJOs is that you do not need an EJB container product such as an application server but you have the option of using only a robust servlet container such as Tomcat or some commercial product. Spring enables developers to develop enterprise-class applications using POJOs. The benefit of using only POJOs is that you do not need an EJB container product such as an application server but you have the option of using only a robust servlet container such as Tomcat or some commercial product. Spring is organized in a modular fashion. Even though the number of packages and classes are substantial, you have to worry only about the ones you need and ignore the rest. Spring is organized in a modular fashion. Even though the number of packages and classes are substantial, you have to worry only about the ones you need and ignore the rest. Spring does not reinvent the wheel, instead it truly makes use of some of the existing technologies like several ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, and other view technologies. Spring does not reinvent the wheel, instead it truly makes use of some of the existing technologies like several ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, and other view technologies. Testing an application written with Spring is simple because environment-dependent code is moved into this framework. Furthermore, by using JavaBeanstyle POJOs, it becomes easier to use dependency injection for injecting test data. Testing an application written with Spring is simple because environment-dependent code is moved into this framework. Furthermore, by using JavaBeanstyle POJOs, it becomes easier to use dependency injection for injecting test data. Spring's web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over-engineered or less popular web frameworks. Spring's web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over-engineered or less popular web frameworks. Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions. Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions. Lightweight IoC containers tend to be lightweight, especially when compared to EJB containers, for example. This is beneficial for developing and deploying applications on computers with limited memory and CPU resources. Lightweight IoC containers tend to be lightweight, especially when compared to EJB containers, for example. This is beneficial for developing and deploying applications on computers with limited memory and CPU resources. Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example). Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example). The technology that Spring is most identified with is the Dependency Injection (DI) flavor of Inversion of Control. The Inversion of Control (IoC) is a general concept, and it can be expressed in many different ways. Dependency Injection is merely one concrete example of Inversion of Control. When writing a complex Java application, application classes should be as independent as possible of other Java classes to increase the possibility to reuse these classes and to test them independently of other classes while unit testing. Dependency Injection helps in gluing these classes together and at the same time keeping them independent. What is dependency injection exactly? Let's look at these two words separately. Here the dependency part translates into an association between two classes. For example, class A is dependent of class B. Now, let's look at the second part, injection. All this means is, class B will get injected into class A by the IoC. Dependency injection can happen in the way of passing parameters to the constructor or by post-construction using setter methods. As Dependency Injection is the heart of Spring Framework, we will explain this concept in a separate chapter with relevant example. One of the key components of Spring is the Aspect Oriented Programming (AOP) framework. The functions that span multiple points of an application are called cross-cutting concerns and these cross-cutting concerns are conceptually separate from the application's business logic. There are various common good examples of aspects including logging, declarative transactions, security, caching, etc. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. DI helps you decouple your application objects from each other, while AOP helps you decouple cross-cutting concerns from the objects that they affect. The AOP module of Spring Framework provides an aspect-oriented programming implementation allowing you to define method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated. We will discuss more about Spring AOP concepts in a separate chapter. Spring could potentially be a one-stop shop for all your enterprise applications. However, Spring is modular, allowing you to pick and choose which modules are applicable to you, without having to bring in the rest. The following section provides details about all the modules available in Spring Framework. The Spring Framework provides about 20 modules which can be used based on an application requirement. The Core Container consists of the Core, Beans, Context, and Expression Language modules the details of which are as follows − The Core module provides the fundamental parts of the framework, including the IoC and Dependency Injection features. The Core module provides the fundamental parts of the framework, including the IoC and Dependency Injection features. The Bean module provides BeanFactory, which is a sophisticated implementation of the factory pattern. The Bean module provides BeanFactory, which is a sophisticated implementation of the factory pattern. The Context module builds on the solid base provided by the Core and Beans modules and it is a medium to access any objects defined and configured. The ApplicationContext interface is the focal point of the Context module. The Context module builds on the solid base provided by the Core and Beans modules and it is a medium to access any objects defined and configured. The ApplicationContext interface is the focal point of the Context module. The SpEL module provides a powerful expression language for querying and manipulating an object graph at runtime. The SpEL module provides a powerful expression language for querying and manipulating an object graph at runtime. The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction modules whose detail is as follows − The JDBC module provides a JDBC-abstraction layer that removes the need for tedious JDBC related coding. The JDBC module provides a JDBC-abstraction layer that removes the need for tedious JDBC related coding. The ORM module provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis. The ORM module provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis. The OXM module provides an abstraction layer that supports Object/XML mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream. The OXM module provides an abstraction layer that supports Object/XML mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream. The Java Messaging Service JMS module contains features for producing and consuming messages. The Java Messaging Service JMS module contains features for producing and consuming messages. The Transaction module supports programmatic and declarative transaction management for classes that implement special interfaces and for all your POJOs. The Transaction module supports programmatic and declarative transaction management for classes that implement special interfaces and for all your POJOs. The Web layer consists of the Web, Web-MVC, Web-Socket, and Web-Portlet modules the details of which are as follows − The Web module provides basic web-oriented integration features such as multipart file-upload functionality and the initialization of the IoC container using servlet listeners and a web-oriented application context. The Web module provides basic web-oriented integration features such as multipart file-upload functionality and the initialization of the IoC container using servlet listeners and a web-oriented application context. The Web-MVC module contains Spring's Model-View-Controller (MVC) implementation for web applications. The Web-MVC module contains Spring's Model-View-Controller (MVC) implementation for web applications. The Web-Socket module provides support for WebSocket-based, two-way communication between the client and the server in web applications. The Web-Socket module provides support for WebSocket-based, two-way communication between the client and the server in web applications. The Web-Portlet module provides the MVC implementation to be used in a portlet environment and mirrors the functionality of Web-Servlet module. The Web-Portlet module provides the MVC implementation to be used in a portlet environment and mirrors the functionality of Web-Servlet module. There are few other important modules like AOP, Aspects, Instrumentation, Web and Test modules the details of which are as follows − The AOP module provides an aspect-oriented programming implementation allowing you to define method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated. The AOP module provides an aspect-oriented programming implementation allowing you to define method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated. The Aspects module provides integration with AspectJ, which is again a powerful and mature AOP framework. The Aspects module provides integration with AspectJ, which is again a powerful and mature AOP framework. The Instrumentation module provides class instrumentation support and class loader implementations to be used in certain application servers. The Instrumentation module provides class instrumentation support and class loader implementations to be used in certain application servers. The Messaging module provides support for STOMP as the WebSocket sub-protocol to use in applications. It also supports an annotation programming model for routing and processing STOMP messages from WebSocket clients. The Messaging module provides support for STOMP as the WebSocket sub-protocol to use in applications. It also supports an annotation programming model for routing and processing STOMP messages from WebSocket clients. The Test module supports the testing of Spring components with JUnit or TestNG frameworks. The Test module supports the testing of Spring components with JUnit or TestNG frameworks. This chapter will guide you on how to prepare a development environment to start your work with Spring Framework. It will also teach you how to set up JDK, Tomcat and Eclipse on your machine before you set up Spring Framework − You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and have installed the JDK in C:\jdk1.6.0_15, you would have to put the following line in your C:\autoexec.bat file. set PATH=C:\jdk1.6.0_15\bin;%PATH% set JAVA_HOME=C:\jdk1.6.0_15 Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.6.0_15 and you use the C shell, you will have to put the following into your .cshrc file. setenv PATH /usr/local/jdk1.6.0_15/bin:$PATH setenv JAVA_HOME /usr/local/jdk1.6.0_15 Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE. You can download the latest version of Apache Commons Logging API from https://commons.apache.org/logging/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\commons-logging-1.1.1 on Windows, or /usr/local/commons-logging-1.1.1 on Linux/Unix. This directory will have the following jar files and other supporting documents, etc. Make sure you set your CLASSPATH variable on this directory properly otherwise you will face a problem while running your application. All the examples in this tutorial have been written using Eclipse IDE. So we would suggest you should have the latest version of Eclipse installed on your machine. To install Eclipse IDE, download the latest Eclipse binaries from https://www.eclipse.org/downloads/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately. Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe %C:\eclipse\eclipse.exe Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine − $/usr/local/eclipse/eclipse After a successful startup, if everything is fine then it should display the following result − Now if everything is fine, then you can proceed to set up your Spring framework. Following are the simple steps to download and install the framework on your machine. Make a choice whether you want to install Spring on Windows or Unix, and then proceed to the next step to download .zip file for Windows and .tz file for Unix. Make a choice whether you want to install Spring on Windows or Unix, and then proceed to the next step to download .zip file for Windows and .tz file for Unix. Download the latest version of Spring framework binaries from https://repo.spring.io/release/org/springframework/spring. Download the latest version of Spring framework binaries from https://repo.spring.io/release/org/springframework/spring. At the time of developing this tutorial, spring-framework-4.1.6.RELEASE-dist.zip was downloaded on Windows machine. After the downloaded file was unzipped, it gives the following directory structure inside E:\spring. At the time of developing this tutorial, spring-framework-4.1.6.RELEASE-dist.zip was downloaded on Windows machine. After the downloaded file was unzipped, it gives the following directory structure inside E:\spring. You will find all the Spring libraries in the directory E:\spring\libs. Make sure you set your CLASSPATH variable on this directory properly otherwise you will face a problem while running your application. If you are using Eclipse, then it is not required to set CLASSPATH because all the setting will be done through Eclipse. Once you are done with this last step, you are ready to proceed to your first Spring Example in the next chapter. Let us start actual programming with Spring Framework. Before you start writing your first example using Spring framework, you have to make sure that you have set up your Spring environment properly as explained in Spring - Environment Setup Chapter. We also assume that you have a bit of working knowledge on Eclipse IDE. Now let us proceed to write a simple Spring Application, which will print "Hello World!" or any other message based on the configuration done in Spring Beans Configuration file. The first step is to create a simple Java Project using Eclipse IDE. Follow the option File → New → Project and finally select Java Project wizard from the wizard list. Now name your project as HelloSpring using the wizard window as follows − Once your project is created successfully, you will have the following content in your Project Explorer − As a second step let us add Spring Framework and common logging API libraries in our project. To do this, right-click on your project name HelloSpring and then follow the following option available in the context menu − Build Path → Configure Build Path to display the Java Build Path window as follows − Now use Add External JARs button available under the Libraries tab to add the following core JARs from Spring Framework and Common Logging installation directories − commons-logging-1.1.1 commons-logging-1.1.1 spring-aop-4.1.6.RELEASE spring-aop-4.1.6.RELEASE spring-aspects-4.1.6.RELEASE spring-aspects-4.1.6.RELEASE spring-beans-4.1.6.RELEASE spring-beans-4.1.6.RELEASE spring-context-4.1.6.RELEASE spring-context-4.1.6.RELEASE spring-context-support-4.1.6.RELEASE spring-context-support-4.1.6.RELEASE spring-core-4.1.6.RELEASE spring-core-4.1.6.RELEASE spring-expression-4.1.6.RELEASE spring-expression-4.1.6.RELEASE spring-instrument-4.1.6.RELEASE spring-instrument-4.1.6.RELEASE spring-instrument-tomcat-4.1.6.RELEASE spring-instrument-tomcat-4.1.6.RELEASE spring-jdbc-4.1.6.RELEASE spring-jdbc-4.1.6.RELEASE spring-jms-4.1.6.RELEASE spring-jms-4.1.6.RELEASE spring-messaging-4.1.6.RELEASE spring-messaging-4.1.6.RELEASE spring-orm-4.1.6.RELEASE spring-orm-4.1.6.RELEASE spring-oxm-4.1.6.RELEASE spring-oxm-4.1.6.RELEASE spring-test-4.1.6.RELEASE spring-test-4.1.6.RELEASE spring-tx-4.1.6.RELEASE spring-tx-4.1.6.RELEASE spring-web-4.1.6.RELEASE spring-web-4.1.6.RELEASE spring-webmvc-4.1.6.RELEASE spring-webmvc-4.1.6.RELEASE spring-webmvc-portlet-4.1.6.RELEASE spring-webmvc-portlet-4.1.6.RELEASE spring-websocket-4.1.6.RELEASE spring-websocket-4.1.6.RELEASE Now let us create actual source files under the HelloSpring project. First we need to create a package called com.tutorialspoint. To do this, right click on src in package explorer section and follow the option − New → Package. Next we will create HelloWorld.java and MainApp.java files under the com.tutorialspoint package. Here is the content of HelloWorld.java file − package com.tutorialspoint; public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println("Your Message : " + message); } } Following is the content of the second file MainApp.java − package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); obj.getMessage(); } } Following two important points are to be noted about the main program − The first step is to create an application context where we used framework API ClassPathXmlApplicationContext(). This API loads beans configuration file and eventually based on the provided API, it takes care of creating and initializing all the objects, i.e. beans mentioned in the configuration file. The first step is to create an application context where we used framework API ClassPathXmlApplicationContext(). This API loads beans configuration file and eventually based on the provided API, it takes care of creating and initializing all the objects, i.e. beans mentioned in the configuration file. The second step is used to get the required bean using getBean() method of the created context. This method uses bean ID to return a generic object, which finally can be casted to the actual object. Once you have an object, you can use this object to call any class method. The second step is used to get the required bean using getBean() method of the created context. This method uses bean ID to return a generic object, which finally can be casted to the actual object. Once you have an object, you can use this object to call any class method. You need to create a Bean Configuration file which is an XML file and acts as a cement that glues the beans, i.e. the classes together. This file needs to be created under the src directory as shown in the following screenshot − Usually developers name this file as Beans.xml, but you are independent to choose any name you like. You have to make sure that this file is available in CLASSPATH and use the same name in the main application while creating an application context as shown in MainApp.java file. The Beans.xml is used to assign unique IDs to different beans and to control the creation of objects with different values without impacting any of the Spring source files. For example, using the following file you can pass any value for "message" variable and you can print different values of message without impacting HelloWorld.java and MainApp.java files. Let us see how it works − <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld"> <property name = "message" value = "Hello World!"/> </bean> </beans> When Spring application gets loaded into the memory, Framework makes use of the above configuration file to create all the beans defined and assigns them a unique ID as defined in <bean> tag. You can use <property> tag to pass the values of different variables used at the time of object creation. Once you are done with creating the source and beans configuration files, you are ready for this step, which is compiling and running your program. To do this, keep MainApp.Java file tab active and use either Run option available in the Eclipse IDE or use Ctrl + F11 to compile and run your MainApp application. If everything is fine with your application, this will print the following message in Eclipse IDE's console − Your Message : Hello World! Congratulations, you have successfully created your first Spring Application. You can see the flexibility of the above Spring application by changing the value of "message" property and keeping both the source files unchanged. The Spring container is at the core of the Spring Framework. The container will create the objects, wire them together, configure them, and manage their complete life cycle from creation till destruction. The Spring container uses DI to manage the components that make up an application. These objects are called Spring Beans, which we will discuss in the next chapter. The container gets its instructions on what objects to instantiate, configure, and assemble by reading the configuration metadata provided. The configuration metadata can be represented either by XML, Java annotations, or Java code. The following diagram represents a high-level view of how Spring works. The Spring IoC container makes use of Java POJO classes and configuration metadata to produce a fully configured and executable system or application. Spring provides the following two distinct types of containers. This is the simplest container providing the basic support for DI and is defined by the org.springframework.beans.factory.BeanFactory interface. The BeanFactory and related interfaces, such as BeanFactoryAware, InitializingBean, DisposableBean, are still present in Spring for the purpose of backward compatibility with a large number of third-party frameworks that integrate with Spring. This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners. This container is defined by the org.springframework.context.ApplicationContext interface. The ApplicationContext container includes all functionality of the BeanFactorycontainer, so it is generally recommended over BeanFactory. BeanFactory can still be used for lightweight applications like mobile devices or applet-based applications where data volume and speed is significant. The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container. For example, in the form of XML <bean/> definitions which you have already seen in the previous chapters. Bean definition contains the information called configuration metadata, which is needed for the container to know the following − How to create a bean Bean's lifecycle details Bean's dependencies All the above configuration metadata translates into a set of the following properties that make up each bean definition. class This attribute is mandatory and specifies the bean class to be used to create the bean. name This attribute specifies the bean identifier uniquely. In XMLbased configuration metadata, you use the id and/or name attributes to specify the bean identifier(s). scope This attribute specifies the scope of the objects created from a particular bean definition and it will be discussed in bean scopes chapter. constructor-arg This is used to inject the dependencies and will be discussed in subsequent chapters. properties This is used to inject the dependencies and will be discussed in subsequent chapters. autowiring mode This is used to inject the dependencies and will be discussed in subsequent chapters. lazy-initialization mode A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at the startup. initialization method A callback to be called just after all necessary properties on the bean have been set by the container. It will be discussed in bean life cycle chapter. destruction method A callback to be used when the container containing the bean is destroyed. It will be discussed in bean life cycle chapter. Spring IoC container is totally decoupled from the format in which this configuration metadata is actually written. Following are the three important methods to provide configuration metadata to the Spring Container − XML based configuration file. Annotation-based configuration Java-based configuration You already have seen how XML-based configuration metadata is provided to the container, but let us see another sample of XML-based configuration file with different bean definitions including lazy initialization, initialization method, and destruction method − <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- A simple bean definition --> <bean id = "..." class = "..."> <!-- collaborators and configuration for this bean go here --> </bean> <!-- A bean definition with lazy init set on --> <bean id = "..." class = "..." lazy-init = "true"> <!-- collaborators and configuration for this bean go here --> </bean> <!-- A bean definition with initialization method --> <bean id = "..." class = "..." init-method = "..."> <!-- collaborators and configuration for this bean go here --> </bean> <!-- A bean definition with destruction method --> <bean id = "..." class = "..." destroy-method = "..."> <!-- collaborators and configuration for this bean go here --> </bean> <!-- more bean definitions go here --> </beans> You can check Spring Hello World Example to understand how to define, configure and create Spring Beans. We will discuss about Annotation Based Configuration in a separate chapter. It is intentionally discussed in a separate chapter as we want you to grasp a few other important Spring concepts, before you start programming with Spring Dependency Injection with Annotations. When defining a <bean> you have the option of declaring a scope for that bean. For example, to force Spring to produce a new bean instance each time one is needed, you should declare the bean's scope attribute to be prototype. Similarly, if you want Spring to return the same bean instance each time one is needed, you should declare the bean's scope attribute to be singleton. The Spring Framework supports the following five scopes, three of which are available only if you use a web-aware ApplicationContext. singleton This scopes the bean definition to a single instance per Spring IoC container (default). prototype This scopes a single bean definition to have any number of object instances. request This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext. session global-session This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext. In this chapter, we will discuss about the first two scopes and the remaining three will be discussed when we discuss about web-aware Spring ApplicationContext. If a scope is set to singleton, the Spring IoC container creates exactly one instance of the object defined by that bean definition. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object. The default scope is always singleton. However, when you need one and only one instance of a bean, you can set the scope property to singleton in the bean configuration file, as shown in the following code snippet − <!-- A bean definition with singleton scope --> <bean id = "..." class = "..." scope = "singleton"> <!-- collaborators and configuration for this bean go here --> </bean> Let us have a working Eclipse IDE in place and take the following steps to create a Spring application − Here is the content of HelloWorld.java file − package com.tutorialspoint; public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println("Your Message : " + message); } } Following is the content of the MainApp.java file − package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld objA = (HelloWorld) context.getBean("helloWorld"); objA.setMessage("I'm object A"); objA.getMessage(); HelloWorld objB = (HelloWorld) context.getBean("helloWorld"); objB.getMessage(); } } Following is the configuration file Beans.xml required for singleton scope − <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld" scope = "singleton"> </bean> </beans> Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − Your Message : I'm object A Your Message : I'm object A If the scope is set to prototype, the Spring IoC container creates a new bean instance of the object every time a request for that specific bean is made. As a rule, use the prototype scope for all state-full beans and the singleton scope for stateless beans. To define a prototype scope, you can set the scope property to prototype in the bean configuration file, as shown in the following code snippet − <!-- A bean definition with prototype scope --> <bean id = "..." class = "..." scope = "prototype"> <!-- collaborators and configuration for this bean go here --> </bean> Let us have working Eclipse IDE in place and follow the following steps to create a Spring application − Here is the content of HelloWorld.java file package com.tutorialspoint; public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println("Your Message : " + message); } } Following is the content of the MainApp.java file − package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld objA = (HelloWorld) context.getBean("helloWorld"); objA.setMessage("I'm object A"); objA.getMessage(); HelloWorld objB = (HelloWorld) context.getBean("helloWorld"); objB.getMessage(); } } Following is the configuration file Beans.xml required for prototype scope − <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld" scope = "prototype"> </bean> </beans> Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − Your Message : I'm object A Your Message : null The life cycle of a Spring bean is easy to understand. When a bean is instantiated, it may be required to perform some initialization to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required. Though, there are lists of the activities that take place behind the scene between the time of bean Instantiation and its destruction, this chapter will discuss only two important bean life cycle callback methods, which are required at the time of bean initialization and its destruction. To define setup and teardown for a bean, we simply declare the <bean> with initmethod and/or destroy-method parameters. The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. Similarly, destroymethod specifies a method that is called just before a bean is removed from the container. The org.springframework.beans.factory.InitializingBean interface specifies a single method − void afterPropertiesSet() throws Exception; Thus, you can simply implement the above interface and initialization work can be done inside afterPropertiesSet() method as follows − public class ExampleBean implements InitializingBean { public void afterPropertiesSet() { // do some initialization work } } In the case of XML-based configuration metadata, you can use the init-method attribute to specify the name of the method that has a void no-argument signature. For example − <bean id = "exampleBean" class = "examples.ExampleBean" init-method = "init"/> Following is the class definition − public class ExampleBean { public void init() { // do some initialization work } } The org.springframework.beans.factory.DisposableBean interface specifies a single method − void destroy() throws Exception; Thus, you can simply implement the above interface and finalization work can be done inside destroy() method as follows − public class ExampleBean implements DisposableBean { public void destroy() { // do some destruction work } } In the case of XML-based configuration metadata, you can use the destroy-method attribute to specify the name of the method that has a void no-argument signature. For example − <bean id = "exampleBean" class = "examples.ExampleBean" destroy-method = "destroy"/> Following is the class definition − public class ExampleBean { public void destroy() { // do some destruction work } } If you are using Spring's IoC container in a non-web application environment; for example, in a rich client desktop environment, you register a shutdown hook with the JVM. Doing so ensures a graceful shutdown and calls the relevant destroy methods on your singleton beans so that all resources are released. It is recommended that you do not use the InitializingBean or DisposableBean callbacks, because XML configuration gives much flexibility in terms of naming your method. Let us have a working Eclipse IDE in place and take the following steps to create a Spring application − Here is the content of HelloWorld.java file − package com.tutorialspoint; public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println("Your Message : " + message); } public void init(){ System.out.println("Bean is going through init."); } public void destroy() { System.out.println("Bean will destroy now."); } } Following is the content of the MainApp.java file. Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensure a graceful shutdown and call the relevant destroy methods. package com.tutorialspoint; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); obj.getMessage(); context.registerShutdownHook(); } } Following is the configuration file Beans.xml required for init and destroy methods − <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld" init-method = "init" destroy-method = "destroy"> <property name = "message" value = "Hello World!"/> </bean> </beans> Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − Bean is going through init. Your Message : Hello World! Bean will destroy now. If you have too many beans having initialization and/or destroy methods with the same name, you don't need to declare init-method and destroy-method on each individual bean. Instead, the framework provides the flexibility to configure such situation using default-init-method and default-destroy-method attributes on the <beans> element as follows − <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" default-init-method = "init" default-destroy-method = "destroy"> <bean id = "..." class = "..."> <!-- collaborators and configuration for this bean go here --> </bean> </beans> The BeanPostProcessor interface defines callback methods that you can implement to provide your own instantiation logic, dependency-resolution logic, etc. You can also implement some custom logic after the Spring container finishes instantiating, configuring, and initializing a bean by plugging in one or more BeanPostProcessor implementations. You can configure multiple BeanPostProcessor interfaces and you can control the order in which these BeanPostProcessor interfaces execute by setting the order property provided the BeanPostProcessor implements the Ordered interface. The BeanPostProcessors operate on bean (or object) instances, which means that the Spring IoC container instantiates a bean instance and then BeanPostProcessor interfaces do their work. An ApplicationContext automatically detects any beans that are defined with the implementation of the BeanPostProcessor interface and registers these beans as postprocessors, to be then called appropriately by the container upon bean creation. The following examples show how to write, register, and use BeanPostProcessors in the context of an ApplicationContext. Let us have a working Eclipse IDE in place and take the following steps to create a Spring application − Here is the content of HelloWorld.java file − package com.tutorialspoint; public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println("Your Message : " + message); } public void init(){ System.out.println("Bean is going through init."); } public void destroy(){ System.out.println("Bean will destroy now."); } } This is a very basic example of implementing BeanPostProcessor, which prints a bean name before and after initialization of any bean. You can implement more complex logic before and after intializing a bean because you have access on bean object inside both the post processor methods. Here is the content of InitHelloWorld.java file − package com.tutorialspoint; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.BeansException; public class InitHelloWorld implements BeanPostProcessor { public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("BeforeInitialization : " + beanName); return bean; // you can return any other object as well } public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("AfterInitialization : " + beanName); return bean; // you can return any other object as well } } Following is the content of the MainApp.java file. Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensures a graceful shutdown and calls the relevant destroy methods. package com.tutorialspoint; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); obj.getMessage(); context.registerShutdownHook(); } } Following is the configuration file Beans.xml required for init and destroy methods − <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld" init-method = "init" destroy-method = "destroy"> <property name = "message" value = "Hello World!"/> </bean> <bean class = "com.tutorialspoint.InitHelloWorld" /> </beans> Once you are done with creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − BeforeInitialization : helloWorld Bean is going through init. AfterInitialization : helloWorld Your Message : Hello World! Bean will destroy now. A bean definition can contain a lot of configuration information, including constructor arguments, property values, and container-specific information such as initialization method, static factory method name, and so on. A child bean definition inherits configuration data from a parent definition. The child definition can override some values, or add others, as needed. Spring Bean definition inheritance has nothing to do with Java class inheritance but the inheritance concept is same. You can define a parent bean definition as a template and other child beans can inherit the required configuration from the parent bean. When you use XML-based configuration metadata, you indicate a child bean definition by using the parent attribute, specifying the parent bean as the value of this attribute. Let us have a working Eclipse IDE in place and take the following steps to create a Spring application − Following is the configuration file Beans.xml where we defined "helloWorld" bean which has two properties message1 and message2. Next "helloIndia" bean has been defined as a child of "helloWorld" bean by using parent attribute. The child bean inherits message2 property as is, and overrides message1 property and introduces one more property message3. <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld"> <property name = "message1" value = "Hello World!"/> <property name = "message2" value = "Hello Second World!"/> </bean> <bean id ="helloIndia" class = "com.tutorialspoint.HelloIndia" parent = "helloWorld"> <property name = "message1" value = "Hello India!"/> <property name = "message3" value = "Namaste India!"/> </bean> </beans> Here is the content of HelloWorld.java file − package com.tutorialspoint; public class HelloWorld { private String message1; private String message2; public void setMessage1(String message){ this.message1 = message; } public void setMessage2(String message){ this.message2 = message; } public void getMessage1(){ System.out.println("World Message1 : " + message1); } public void getMessage2(){ System.out.println("World Message2 : " + message2); } } Here is the content of HelloIndia.java file − package com.tutorialspoint; public class HelloIndia { private String message1; private String message2; private String message3; public void setMessage1(String message){ this.message1 = message; } public void setMessage2(String message){ this.message2 = message; } public void setMessage3(String message){ this.message3 = message; } public void getMessage1(){ System.out.println("India Message1 : " + message1); } public void getMessage2(){ System.out.println("India Message2 : " + message2); } public void getMessage3(){ System.out.println("India Message3 : " + message3); } } Following is the content of the MainApp.java file − package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld objA = (HelloWorld) context.getBean("helloWorld"); objA.getMessage1(); objA.getMessage2(); HelloIndia objB = (HelloIndia) context.getBean("helloIndia"); objB.getMessage1(); objB.getMessage2(); objB.getMessage3(); } } Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − World Message1 : Hello World! World Message2 : Hello Second World! India Message1 : Hello India! India Message2 : Hello Second World! India Message3 : Namaste India! If you observed here, we did not pass message2 while creating "helloIndia" bean, but it got passed because of Bean Definition Inheritance. You can create a Bean definition template, which can be used by other child bean definitions without putting much effort. While defining a Bean Definition Template, you should not specify the class attribute and should specify abstract attribute and should specify the abstract attribute with a value of true as shown in the following code snippet − <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id = "beanTeamplate" abstract = "true"> <property name = "message1" value = "Hello World!"/> <property name = "message2" value = "Hello Second World!"/> <property name = "message3" value = "Namaste India!"/> </bean> <bean id = "helloIndia" class = "com.tutorialspoint.HelloIndia" parent = "beanTeamplate"> <property name = "message1" value = "Hello India!"/> <property name = "message3" value = "Namaste India!"/> </bean> </beans> The parent bean cannot be instantiated on its own because it is incomplete, and it is also explicitly marked as abstract. When a definition is abstract like this, it is usable only as a pure template bean definition that serves as a parent definition for child definitions. Every Java-based application has a few objects that work together to present what the end-user sees as a working application. When writing a complex Java application, application classes should be as independent as possible of other Java classes to increase the possibility to reuse these classes and to test them independently of other classes while unit testing. Dependency Injection (or sometime called wiring) helps in gluing these classes together and at the same time keeping them independent. Consider you have an application which has a text editor component and you want to provide a spell check. Your standard code would look something like this − public class TextEditor { private SpellChecker spellChecker; public TextEditor() { spellChecker = new SpellChecker(); } } What we've done here is, create a dependency between the TextEditor and the SpellChecker. In an inversion of control scenario, we would instead do something like this − public class TextEditor { private SpellChecker spellChecker; public TextEditor(SpellChecker spellChecker) { this.spellChecker = spellChecker; } } Here, the TextEditor should not worry about SpellChecker implementation. The SpellChecker will be implemented independently and will be provided to the TextEditor at the time of TextEditor instantiation. This entire procedure is controlled by the Spring Framework. Here, we have removed total control from the TextEditor and kept it somewhere else (i.e. XML configuration file) and the dependency (i.e. class SpellChecker) is being injected into the class TextEditor through a Class Constructor. Thus the flow of control has been "inverted" by Dependency Injection (DI) because you have effectively delegated dependances to some external system. The second method of injecting dependency is through Setter Methods of the TextEditor class where we will create a SpellChecker instance. This instance will be used to call setter methods to initialize TextEditor's properties. Thus, DI exists in two major variants and the following two sub-chapters will cover both of them with examples − Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on the other class. Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean. You can mix both, Constructor-based and Setter-based DI but it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies. The code is cleaner with the DI principle and decoupling is more effective when objects are provided with their dependencies. The object does not look up its dependencies and does not know the location or class of the dependencies, rather everything is taken care by the Spring Framework. As you know Java inner classes are defined within the scope of other classes, similarly, inner beans are beans that are defined within the scope of another bean. Thus, a <bean/> element inside the <property/> or <constructor-arg/> elements is called inner bean and it is shown below. <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id = "outerBean" class = "..."> <property name = "target"> <bean id = "innerBean" class = "..."/> </property> </bean> </beans> Let us have working Eclipse IDE in place and follow the following steps to create a Spring application − Here is the content of TextEditor.java file − package com.tutorialspoint; public class TextEditor { private SpellChecker spellChecker; // a setter method to inject the dependency. public void setSpellChecker(SpellChecker spellChecker) { System.out.println("Inside setSpellChecker." ); this.spellChecker = spellChecker; } // a getter method to return spellChecker public SpellChecker getSpellChecker() { return spellChecker; } public void spellCheck() { spellChecker.checkSpelling(); } } Following is the content of another dependent class file SpellChecker.java − package com.tutorialspoint; public class SpellChecker { public SpellChecker(){ System.out.println("Inside SpellChecker constructor." ); } public void checkSpelling(){ System.out.println("Inside checkSpelling." ); } } Following is the content of the MainApp.java file − package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); TextEditor te = (TextEditor) context.getBean("textEditor"); te.spellCheck(); } } Following is the configuration file Beans.xml which has configuration for the setter-based injection but using inner beans − <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- Definition for textEditor bean using inner bean --> <bean id = "textEditor" class = "com.tutorialspoint.TextEditor"> <property name = "spellChecker"> <bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker"/> </property> </bean> </beans> Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − Inside SpellChecker constructor. Inside setSpellChecker. Inside checkSpelling. You have seen how to configure primitive data type using value attribute and object references using ref attribute of the <property> tag in your Bean configuration file. Both the cases deal with passing singular value to a bean. Now what if you want to pass plural values like Java Collection types such as List, Set, Map, and Properties. To handle the situation, Spring offers four types of collection configuration elements which are as follows − <list> This helps in wiring ie injecting a list of values, allowing duplicates. <set> This helps in wiring a set of values but without any duplicates. <map> This can be used to inject a collection of name-value pairs where name and value can be of any type. <props> This can be used to inject a collection of name-value pairs where the name and value are both Strings. You can use either <list> or <set> to wire any implementation of java.util.Collection or an array. You will come across two situations (a) Passing direct values of the collection and (b) Passing a reference of a bean as one of the collection elements. Let us have a working Eclipse IDE in place and take the following steps to create a Spring application − Here is the content of JavaCollection.java file − package com.tutorialspoint; import java.util.*; public class JavaCollection { List addressList; Set addressSet; Map addressMap; Properties addressProp; // a setter method to set List public void setAddressList(List addressList) { this.addressList = addressList; } // prints and returns all the elements of the list. public List getAddressList() { System.out.println("List Elements :" + addressList); return addressList; } // a setter method to set Set public void setAddressSet(Set addressSet) { this.addressSet = addressSet; } // prints and returns all the elements of the Set. public Set getAddressSet() { System.out.println("Set Elements :" + addressSet); return addressSet; } // a setter method to set Map public void setAddressMap(Map addressMap) { this.addressMap = addressMap; } // prints and returns all the elements of the Map. public Map getAddressMap() { System.out.println("Map Elements :" + addressMap); return addressMap; } // a setter method to set Property public void setAddressProp(Properties addressProp) { this.addressProp = addressProp; } // prints and returns all the elements of the Property. public Properties getAddressProp() { System.out.println("Property Elements :" + addressProp); return addressProp; } } Following is the content of the MainApp.java file − package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); JavaCollection jc=(JavaCollection)context.getBean("javaCollection"); jc.getAddressList(); jc.getAddressSet(); jc.getAddressMap(); jc.getAddressProp(); } } Following is the configuration file Beans.xml which has configuration for all the type of collections − <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- Definition for javaCollection --> <bean id = "javaCollection" class = "com.tutorialspoint.JavaCollection"> <!-- results in a setAddressList(java.util.List) call --> <property name = "addressList"> <list> <value>INDIA</value> <value>Pakistan</value> <value>USA</value> <value>USA</value> </list> </property> <!-- results in a setAddressSet(java.util.Set) call --> <property name = "addressSet"> <set> <value>INDIA</value> <value>Pakistan</value> <value>USA</value> <value>USA</value> </set> </property> <!-- results in a setAddressMap(java.util.Map) call --> <property name = "addressMap"> <map> <entry key = "1" value = "INDIA"/> <entry key = "2" value = "Pakistan"/> <entry key = "3" value = "USA"/> <entry key = "4" value = "USA"/> </map> </property> <!-- results in a setAddressProp(java.util.Properties) call --> <property name = "addressProp"> <props> <prop key = "one">INDIA</prop> <prop key = "one">INDIA</prop> <prop key = "two">Pakistan</prop> <prop key = "three">USA</prop> <prop key = "four">USA</prop> </props> </property> </bean> </beans> Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − List Elements :[INDIA, Pakistan, USA, USA] Set Elements :[INDIA, Pakistan, USA] ap Elements :{1 = INDIA, 2 = Pakistan, 3 = USA, 4 = USA} Property Elements :{two = Pakistan, one = INDIA, three = USA, four = USA} The following Bean definition will help you understand how to inject bean references as one of the collection's element. Even you can mix references and values all together as shown in the following code snippet − <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- Bean Definition to handle references and values --> <bean id = "..." class = "..."> <!-- Passing bean reference for java.util.List --> <property name = "addressList"> <list> <ref bean = "address1"/> <ref bean = "address2"/> <value>Pakistan</value> </list> </property> <!-- Passing bean reference for java.util.Set --> <property name = "addressSet"> <set> <ref bean = "address1"/> <ref bean = "address2"/> <value>Pakistan</value> </set> </property> <!-- Passing bean reference for java.util.Map --> <property name = "addressMap"> <map> <entry key = "one" value = "INDIA"/> <entry key = "two" value-ref = "address1"/> <entry key = "three" value-ref = "address2"/> </map> </property> </bean> </beans> To use the above bean definition, you need to define your setter methods in such a way that they should be able to handle references as well. If you need to pass an empty string as a value, then you can pass it as follows − <bean id = "..." class = "exampleBean"> <property name = "email" value = ""/> </bean> The preceding example is equivalent to the Java code: exampleBean.setEmail("") If you need to pass a NULL value, then you can pass it as follows − <bean id = "..." class = "exampleBean"> <property name = "email"><null/></property> </bean> The preceding example is equivalent to the Java code: exampleBean.setEmail(null) You have learnt how to declare beans using the <bean> element and inject <bean> using <constructor-arg> and <property> elements in XML configuration file. The Spring container can autowire relationships between collaborating beans without using <constructor-arg> and <property> elements, which helps cut down on the amount of XML configuration you write for a big Spring-based application. Following are the autowiring modes, which can be used to instruct the Spring container to use autowiring for dependency injection. You use the autowire attribute of the <bean/> element to specify autowire mode for a bean definition. This is default setting which means no autowiring and you should use explicit bean reference for wiring. You have nothing to do special for this wiring. This is what you already have seen in Dependency Injection chapter. Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file. Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is thrown. Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised. Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType. You can use byType or constructor autowiring mode to wire arrays and other typed-collections. Autowiring works best when it is used consistently across a project. If autowiring is not used in general, it might be confusing for developers to use it to wire only one or two bean definitions. Though, autowiring can significantly reduce the need to specify properties or constructor arguments but you should consider the limitations and disadvantages of autowiring before using them. Overriding possibility You can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring. Primitive data types You cannot autowire so-called simple properties such as primitives, Strings, and Classes. Confusing nature Autowiring is less exact than explicit wiring, so if possible prefer using explict wiring. Starting from Spring 2.5 it became possible to configure the dependency injection using annotations. So instead of using XML to describe a bean wiring, you can move the bean configuration into the component class itself by using annotations on the relevant class, method, or field declaration. Annotation injection is performed before XML injection. Thus, the latter configuration will override the former for properties wired through both approaches. Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file. So consider the following configuration file in case you want to use any annotation in your Spring application. <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:context = "http://www.springframework.org/schema/context" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config/> <!-- bean definitions go here --> </beans> Once <context:annotation-config/> is configured, you can start annotating your code to indicate that Spring should automatically wire values into properties, methods, and constructors. Let us look at a few important annotations to understand how they work − The @Required annotation applies to bean property setter methods. The @Autowired annotation can apply to bean property setter methods, non-setter methods, constructor and properties. The @Qualifier annotation along with @Autowired can be used to remove the confusion by specifiying which exact bean will be wired. Spring supports JSR-250 based annotations which include @Resource, @PostConstruct and @PreDestroy annotations. So far you have seen how we configure Spring beans using XML configuration file. If you are comfortable with XML configuration, then it is really not required to learn how to proceed with Java-based configuration as you are going to achieve the same result using either of the configurations available. Java-based configuration option enables you to write most of your Spring configuration without XML but with the help of few Java-based annotations explained in this chapter. Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context. The simplest possible @Configuration class would be as follows − package com.tutorialspoint; import org.springframework.context.annotation.*; @Configuration public class HelloWorldConfig { @Bean public HelloWorld helloWorld(){ return new HelloWorld(); } } The above code will be equivalent to the following XML configuration − <beans> <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld" /> </beans> Here, the method name is annotated with @Bean works as bean ID and it creates and returns the actual bean. Your configuration class can have a declaration for more than one @Bean. Once your configuration classes are defined, you can load and provide them to Spring container using AnnotationConfigApplicationContext as follows − public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class); HelloWorld helloWorld = ctx.getBean(HelloWorld.class); helloWorld.setMessage("Hello World!"); helloWorld.getMessage(); } You can load various configuration classes as follows − public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(AppConfig.class, OtherConfig.class); ctx.register(AdditionalConfig.class); ctx.refresh(); MyService myService = ctx.getBean(MyService.class); myService.doStuff(); } Let us have a working Eclipse IDE in place and take the following steps to create a Spring application − Here is the content of HelloWorldConfig.java file package com.tutorialspoint; import org.springframework.context.annotation.*; @Configuration public class HelloWorldConfig { @Bean public HelloWorld helloWorld(){ return new HelloWorld(); } } Here is the content of HelloWorld.java file package com.tutorialspoint; public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println("Your Message : " + message); } } Following is the content of the MainApp.java file package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.*; public class MainApp { public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class); HelloWorld helloWorld = ctx.getBean(HelloWorld.class); helloWorld.setMessage("Hello World!"); helloWorld.getMessage(); } } Once you are done creating all the source files and adding the required additional libraries, let us run the application. You should note that there is no configuration file required. If everything is fine with your application, it will print the following message − Your Message : Hello World! When @Beans have dependencies on one another, expressing that the dependency is as simple as having one bean method calling another as follows − package com.tutorialspoint; import org.springframework.context.annotation.*; @Configuration public class AppConfig { @Bean public Foo foo() { return new Foo(bar()); } @Bean public Bar bar() { return new Bar(); } } Here, the foo bean receives a reference to bar via the constructor injection. Now let us look at another working example. Let us have a working Eclipse IDE in place and take the following steps to create a Spring application − Here is the content of TextEditorConfig.java file package com.tutorialspoint; import org.springframework.context.annotation.*; @Configuration public class TextEditorConfig { @Bean public TextEditor textEditor(){ return new TextEditor( spellChecker() ); } @Bean public SpellChecker spellChecker(){ return new SpellChecker( ); } } Here is the content of TextEditor.java file package com.tutorialspoint; public class TextEditor { private SpellChecker spellChecker; public TextEditor(SpellChecker spellChecker){ System.out.println("Inside TextEditor constructor." ); this.spellChecker = spellChecker; } public void spellCheck(){ spellChecker.checkSpelling(); } } Following is the content of another dependent class file SpellChecker.java package com.tutorialspoint; public class SpellChecker { public SpellChecker(){ System.out.println("Inside SpellChecker constructor." ); } public void checkSpelling(){ System.out.println("Inside checkSpelling." ); } } Following is the content of the MainApp.java file package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.*; public class MainApp { public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(TextEditorConfig.class); TextEditor te = ctx.getBean(TextEditor.class); te.spellCheck(); } } Once you are done creating all the source files and adding the required additional libraries, let us run the application. You should note that there is no configuration file required. If everything is fine with your application, it will print the following message − Inside SpellChecker constructor. Inside TextEditor constructor. Inside checkSpelling. The @Import annotation allows for loading @Bean definitions from another configuration class. Consider a ConfigA class as follows − @Configuration public class ConfigA { @Bean public A a() { return new A(); } } You can import above Bean declaration in another Bean Declaration as follows − @Configuration @Import(ConfigA.class) public class ConfigB { @Bean public B b() { return new B(); } } Now, rather than needing to specify both ConfigA.class and ConfigB.class when instantiating the context, only ConfigB needs to be supplied as follows − public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB.class); // now both beans A and B will be available... A a = ctx.getBean(A.class); B b = ctx.getBean(B.class); } The @Bean annotation supports specifying arbitrary initialization and destruction callback methods, much like Spring XML's init-method and destroy-method attributes on the bean element − public class Foo { public void init() { // initialization logic } public void cleanup() { // destruction logic } } @Configuration public class AppConfig { @Bean(initMethod = "init", destroyMethod = "cleanup" ) public Foo foo() { return new Foo(); } } The default scope is singleton, but you can override this with the @Scope annotation as follows − @Configuration public class AppConfig { @Bean @Scope("prototype") public Foo foo() { return new Foo(); } } You have seen in all the chapters that the core of Spring is the ApplicationContext, which manages the complete life cycle of the beans. The ApplicationContext publishes certain types of events when loading the beans. For example, a ContextStartedEvent is published when the context is started and ContextStoppedEvent is published when the context is stopped. Event handling in the ApplicationContext is provided through the ApplicationEvent class and ApplicationListener interface. Hence, if a bean implements the ApplicationListener, then every time an ApplicationEvent gets published to the ApplicationContext, that bean is notified. Spring provides the following standard events − ContextRefreshedEvent This event is published when the ApplicationContext is either initialized or refreshed. This can also be raised using the refresh() method on the ConfigurableApplicationContext interface. ContextStartedEvent This event is published when the ApplicationContext is started using the start() method on the ConfigurableApplicationContext interface. You can poll your database or you can restart any stopped application after receiving this event. ContextStoppedEvent This event is published when the ApplicationContext is stopped using the stop() method on the ConfigurableApplicationContext interface. You can do required housekeep work after receiving this event. ContextClosedEvent This event is published when the ApplicationContext is closed using the close() method on the ConfigurableApplicationContext interface. A closed context reaches its end of life; it cannot be refreshed or restarted. RequestHandledEvent This is a web-specific event telling all beans that an HTTP request has been serviced. Spring's event handling is single-threaded so if an event is published, until and unless all the receivers get the message, the processes are blocked and the flow will not continue. Hence, care should be taken when designing your application if the event handling is to be used. To listen to a context event, a bean should implement the ApplicationListener interface which has just one method onApplicationEvent(). So let us write an example to see how the events propagates and how you can put your code to do required task based on certain events. Let us have a working Eclipse IDE in place and take the following steps to create a Spring application − Here is the content of HelloWorld.java file package com.tutorialspoint; public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println("Your Message : " + message); } } Following is the content of the CStartEventHandler.java file package com.tutorialspoint; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextStartedEvent; public class CStartEventHandler implements ApplicationListener<ContextStartedEvent>{ public void onApplicationEvent(ContextStartedEvent event) { System.out.println("ContextStartedEvent Received"); } } Following is the content of the CStopEventHandler.java file package com.tutorialspoint; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextStoppedEvent; public class CStopEventHandler implements ApplicationListener<ContextStoppedEvent>{ public void onApplicationEvent(ContextStoppedEvent event) { System.out.println("ContextStoppedEvent Received"); } } Following is the content of the MainApp.java file package com.tutorialspoint; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); // Let us raise a start event. context.start(); HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); obj.getMessage(); // Let us raise a stop event. context.stop(); } } Following is the configuration file Beans.xml <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld"> <property name = "message" value = "Hello World!"/> </bean> <bean id = "cStartEventHandler" class = "com.tutorialspoint.CStartEventHandler"/> <bean id = "cStopEventHandler" class = "com.tutorialspoint.CStopEventHandler"/> </beans> Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − ContextStartedEvent Received Your Message : Hello World! ContextStoppedEvent Received If you like, you can publish your own custom events and later you can capture the same to take any action against those custom events. If you are interested in writing your own custom events, you can check Custom Events in Spring. There are number of steps to be taken to write and publish your own custom events. Follow the instructions given in this chapter to write, publish and handle Custom Spring Events. Here is the content of CustomEvent.java file package com.tutorialspoint; import org.springframework.context.ApplicationEvent; public class CustomEvent extends ApplicationEvent{ public CustomEvent(Object source) { super(source); } public String toString(){ return "My Custom Event"; } } Following is the content of the CustomEventPublisher.java file package com.tutorialspoint; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; public class CustomEventPublisher implements ApplicationEventPublisherAware { private ApplicationEventPublisher publisher; public void setApplicationEventPublisher (ApplicationEventPublisher publisher) { this.publisher = publisher; } public void publish() { CustomEvent ce = new CustomEvent(this); publisher.publishEvent(ce); } } Following is the content of the CustomEventHandler.java file package com.tutorialspoint; import org.springframework.context.ApplicationListener; public class CustomEventHandler implements ApplicationListener<CustomEvent> { public void onApplicationEvent(CustomEvent event) { System.out.println(event.toString()); } } Following is the content of the MainApp.java file package com.tutorialspoint; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); CustomEventPublisher cvp = (CustomEventPublisher) context.getBean("customEventPublisher"); cvp.publish(); cvp.publish(); } } Following is the configuration file Beans.xml <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id = "customEventHandler" class = "com.tutorialspoint.CustomEventHandler"/> <bean id = "customEventPublisher" class = "com.tutorialspoint.CustomEventPublisher"/> </beans> Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − y Custom Event y Custom Event One of the key components of Spring Framework is the Aspect oriented programming (AOP) framework. Aspect-Oriented Programming entails breaking down program logic into distinct parts called so-called concerns. The functions that span multiple points of an application are called cross-cutting concerns and these cross-cutting concerns are conceptually separate from the application's business logic. There are various common good examples of aspects like logging, auditing, declarative transactions, security, caching, etc. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Dependency Injection helps you decouple your application objects from each other and AOP helps you decouple cross-cutting concerns from the objects that they affect. AOP is like triggers in programming languages such as Perl, .NET, Java, and others. Spring AOP module provides interceptors to intercept an application. For example, when a method is executed, you can add extra functionality before or after the method execution. Before we start working with AOP, let us become familiar with the AOP concepts and terminology. These terms are not specific to Spring, rather they are related to AOP. Aspect This is a module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement. Join point This represents a point in your application where you can plug-in the AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework. Advice This is the actual action to be taken either before or after the method execution. This is an actual piece of code that is invoked during the program execution by Spring AOP framework. Pointcut This is a set of one or more join points where an advice should be executed. You can specify pointcuts using expressions or patterns as we will see in our AOP examples. Introduction An introduction allows you to add new methods or attributes to the existing classes. Target object The object being advised by one or more aspects. This object will always be a proxied object, also referred to as the advised object. Weaving Weaving is the process of linking aspects with other application types or objects to create an advised object. This can be done at compile time, load time, or at runtime. Spring aspects can work with five kinds of advice mentioned as follows − before Run advice before the a method execution. after Run advice after the method execution, regardless of its outcome. after-returning Run advice after the a method execution only if method completes successfully. after-throwing Run advice after the a method execution only if method exits by throwing an exception. around Run advice before and after the advised method is invoked. Spring supports the @AspectJ annotation style approach and the schema-based approach to implement custom aspects. These two approaches have been explained in detail in the following sections. Aspects are implemented using the regular classes along with XML based configuration. @AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations. While working with the database using plain old JDBC, it becomes cumbersome to write unnecessary code to handle exceptions, opening and closing database connections, etc. However, Spring JDBC Framework takes care of all the low-level details starting from opening the connection, prepare and execute the SQL statement, process exceptions, handle transactions and finally close the connection. So what you have to do is just define the connection parameters and specify the SQL statement to be executed and do the required work for each iteration while fetching data from the database. Spring JDBC provides several approaches and correspondingly different classes to interface with the database. I'm going to take classic and the most popular approach which makes use of JdbcTemplate class of the framework. This is the central framework class that manages all the database communication and exception handling. The JDBC Template class executes SQL queries, updates statements, stores procedure calls, performs iteration over ResultSets, and extracts returned parameter values. It also catches JDBC exceptions and translates them to the generic, more informative, exception hierarchy defined in the org.springframework.dao package. Instances of the JdbcTemplate class are threadsafe once configured. So you can configure a single instance of a JdbcTemplate and then safely inject this shared reference into multiple DAOs. A common practice when using the JDBC Template class is to configure a DataSource in your Spring configuration file, and then dependency-inject that shared DataSource bean into your DAO classes, and the JdbcTemplate is created in the setter for the DataSource. Let us create a database table Student in our database TEST. We assume you are working with MySQL database, if you work with any other database then you can change your DDL and SQL queries accordingly. CREATE TABLE Student( ID INT NOT NULL AUTO_INCREMENT, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, PRIMARY KEY (ID) ); Now we need to supply a DataSource to the JDBC Template so it can configure itself to get database access. You can configure the DataSource in the XML file with a piece of code as shown in the following code snippet − <bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name = "driverClassName" value = "com.mysql.jdbc.Driver"/> <property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/> <property name = "username" value = "root"/> <property name = "password" value = "password"/> </bean> DAO stands for Data Access Object, which is commonly used for database interaction. DAOs exist to provide a means to read and write data to the database and they should expose this functionality through an interface by which the rest of the application will access them. The DAO support in Spring makes it easy to work with data access technologies like JDBC, Hibernate, JPA, or JDO in a consistent way. Let us see how we can perform CRUD (Create, Read, Update and Delete) operation on database tables using SQL and JDBC Template object. Querying for an integer String SQL = "select count(*) from Student"; int rowCount = jdbcTemplateObject.queryForInt( SQL ); Querying for a long String SQL = "select count(*) from Student"; long rowCount = jdbcTemplateObject.queryForLong( SQL ); A simple query using a bind variable String SQL = "select age from Student where id = ?"; int age = jdbcTemplateObject.queryForInt(SQL, new Object[]{10}); Querying for a String String SQL = "select name from Student where id = ?"; String name = jdbcTemplateObject.queryForObject(SQL, new Object[]{10}, String.class); Querying and returning an object String SQL = "select * from Student where id = ?"; Student student = jdbcTemplateObject.queryForObject( SQL, new Object[]{10}, new StudentMapper()); public class StudentMapper implements RowMapper<Student> { public Student mapRow(ResultSet rs, int rowNum) throws SQLException { Student student = new Student(); student.setID(rs.getInt("id")); student.setName(rs.getString("name")); student.setAge(rs.getInt("age")); return student; } } Querying and returning multiple objects String SQL = "select * from Student"; List<Student> students = jdbcTemplateObject.query( SQL, new StudentMapper()); public class StudentMapper implements RowMapper<Student> { public Student mapRow(ResultSet rs, int rowNum) throws SQLException { Student student = new Student(); student.setID(rs.getInt("id")); student.setName(rs.getString("name")); student.setAge(rs.getInt("age")); return student; } } Inserting a row into the table String SQL = "insert into Student (name, age) values (?, ?)"; jdbcTemplateObject.update( SQL, new Object[]{"Zara", 11} ); Updating a row into the table String SQL = "update Student set name = ? where id = ?"; jdbcTemplateObject.update( SQL, new Object[]{"Zara", 10} ); Deleting a row from the table String SQL = "delete Student where id = ?"; jdbcTemplateObject.update( SQL, new Object[]{20} ); You can use the execute(..) method from jdbcTemplate to execute any SQL statements or DDL statements. Following is an example to use CREATE statement to create a table − String SQL = "CREATE TABLE Student( " + "ID INT NOT NULL AUTO_INCREMENT, " + "NAME VARCHAR(20) NOT NULL, " + "AGE INT NOT NULL, " + "PRIMARY KEY (ID));" jdbcTemplateObject.execute( SQL ); Based on the above concepts, let us check few important examples which will help you in understanding usage of JDBC framework in Spring − This example will explain how to write a simple JDBC-based Spring application. Learn how to call SQL stored procedure while using JDBC in Spring. A database transaction is a sequence of actions that are treated as a single unit of work. These actions should either complete entirely or take no effect at all. Transaction management is an important part of RDBMS-oriented enterprise application to ensure data integrity and consistency. The concept of transactions can be described with the following four key properties described as ACID − Atomicity − A transaction should be treated as a single unit of operation, which means either the entire sequence of operations is successful or unsuccessful. Atomicity − A transaction should be treated as a single unit of operation, which means either the entire sequence of operations is successful or unsuccessful. Consistency − This represents the consistency of the referential integrity of the database, unique primary keys in tables, etc. Consistency − This represents the consistency of the referential integrity of the database, unique primary keys in tables, etc. Isolation − There may be many transaction processing with the same data set at the same time. Each transaction should be isolated from others to prevent data corruption. Isolation − There may be many transaction processing with the same data set at the same time. Each transaction should be isolated from others to prevent data corruption. Durability − Once a transaction has completed, the results of this transaction have to be made permanent and cannot be erased from the database due to system failure. Durability − Once a transaction has completed, the results of this transaction have to be made permanent and cannot be erased from the database due to system failure. A real RDBMS database system will guarantee all four properties for each transaction. The simplistic view of a transaction issued to the database using SQL is as follows − Begin the transaction using begin transaction command. Begin the transaction using begin transaction command. Perform various deleted, update or insert operations using SQL queries. Perform various deleted, update or insert operations using SQL queries. If all the operation are successful then perform commit otherwise rollback all the operations. If all the operation are successful then perform commit otherwise rollback all the operations. Spring framework provides an abstract layer on top of different underlying transaction management APIs. Spring's transaction support aims to provide an alternative to EJB transactions by adding transaction capabilities to POJOs. Spring supports both programmatic and declarative transaction management. EJBs require an application server, but Spring transaction management can be implemented without the need of an application server. Local transactions are specific to a single transactional resource like a JDBC connection, whereas global transactions can span multiple transactional resources like transaction in a distributed system. Local transaction management can be useful in a centralized computing environment where application components and resources are located at a single site, and transaction management only involves a local data manager running on a single machine. Local transactions are easier to be implemented. Global transaction management is required in a distributed computing environment where all the resources are distributed across multiple systems. In such a case, transaction management needs to be done both at local and global levels. A distributed or a global transaction is executed across multiple systems, and its execution requires coordination between the global transaction management system and all the local data managers of all the involved systems. Spring supports two types of transaction management − Programmatic transaction management − This means that you have to manage the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain. Programmatic transaction management − This means that you have to manage the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain. Declarative transaction management − This means you separate transaction management from the business code. You only use annotations or XML-based configuration to manage the transactions. Declarative transaction management − This means you separate transaction management from the business code. You only use annotations or XML-based configuration to manage the transactions. Declarative transaction management is preferable over programmatic transaction management though it is less flexible than programmatic transaction management, which allows you to control transactions through your code. But as a kind of crosscutting concern, declarative transaction management can be modularized with the AOP approach. Spring supports declarative transaction management through the Spring AOP framework. The key to the Spring transaction abstraction is defined by the org.springframework.transaction.PlatformTransactionManager interface, which is as follows − public interface PlatformTransactionManager { TransactionStatus getTransaction(TransactionDefinition definition); throws TransactionException; void commit(TransactionStatus status) throws TransactionException; void rollback(TransactionStatus status) throws TransactionException; } TransactionStatus getTransaction(TransactionDefinition definition) This method returns a currently active transaction or creates a new one, according to the specified propagation behavior. void commit(TransactionStatus status) This method commits the given transaction, with regard to its status. void rollback(TransactionStatus status) This method performs a rollback of the given transaction. The TransactionDefinition is the core interface of the transaction support in Spring and it is defined as follows − public interface TransactionDefinition { int getPropagationBehavior(); int getIsolationLevel(); String getName(); int getTimeout(); boolean isReadOnly(); } int getPropagationBehavior() This method returns the propagation behavior. Spring offers all of the transaction propagation options familiar from EJB CMT. int getIsolationLevel() This method returns the degree to which this transaction is isolated from the work of other transactions. String getName() This method returns the name of this transaction. int getTimeout() This method returns the time in seconds in which the transaction must complete. boolean isReadOnly() This method returns whether the transaction is read-only. Following are the possible values for isolation level − TransactionDefinition.ISOLATION_DEFAULT This is the default isolation level. TransactionDefinition.ISOLATION_READ_COMMITTED Indicates that dirty reads are prevented; non-repeatable reads and phantom reads can occur. TransactionDefinition.ISOLATION_READ_UNCOMMITTED Indicates that dirty reads, non-repeatable reads, and phantom reads can occur. TransactionDefinition.ISOLATION_REPEATABLE_READ Indicates that dirty reads and non-repeatable reads are prevented; phantom reads can occur. TransactionDefinition.ISOLATION_SERIALIZABLE Indicates that dirty reads, non-repeatable reads, and phantom reads are prevented. Following are the possible values for propagation types − TransactionDefinition.PROPAGATION_MANDATORY Supports a current transaction; throws an exception if no current transaction exists. TransactionDefinition.PROPAGATION_NESTED Executes within a nested transaction if a current transaction exists. TransactionDefinition.PROPAGATION_NEVER Does not support a current transaction; throws an exception if a current transaction exists. TransactionDefinition.PROPAGATION_NOT_SUPPORTED Does not support a current transaction; rather always execute nontransactionally. TransactionDefinition.PROPAGATION_REQUIRED Supports a current transaction; creates a new one if none exists. TransactionDefinition.PROPAGATION_REQUIRES_NEW Creates a new transaction, suspending the current transaction if one exists. TransactionDefinition.PROPAGATION_SUPPORTS Supports a current transaction; executes non-transactionally if none exists. TransactionDefinition.TIMEOUT_DEFAULT Uses the default timeout of the underlying transaction system, or none if timeouts are not supported. The TransactionStatus interface provides a simple way for transactional code to control transaction execution and query transaction status. public interface TransactionStatus extends SavepointManager { boolean isNewTransaction(); boolean hasSavepoint(); void setRollbackOnly(); boolean isRollbackOnly(); boolean isCompleted(); } boolean hasSavepoint() This method returns whether this transaction internally carries a savepoint, i.e., has been created as nested transaction based on a savepoint. boolean isCompleted() This method returns whether this transaction is completed, i.e., whether it has already been committed or rolled back. boolean isNewTransaction() This method returns true in case the present transaction is new. boolean isRollbackOnly() This method returns whether the transaction has been marked as rollback-only. void setRollbackOnly() This method sets the transaction as rollback-only. The Spring Web MVC framework provides Model-View-Controller (MVC) architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. The Model encapsulates the application data and in general they will consist of POJO. The Model encapsulates the application data and in general they will consist of POJO. The View is responsible for rendering the model data and in general it generates HTML output that the client's browser can interpret. The View is responsible for rendering the model data and in general it generates HTML output that the client's browser can interpret. The Controller is responsible for processing user requests and building an appropriate model and passes it to the view for rendering. The Controller is responsible for processing user requests and building an appropriate model and passes it to the view for rendering. The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that handles all the HTTP requests and responses. The request processing workflow of the Spring Web MVC DispatcherServlet is illustrated in the following diagram − Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet − After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller. After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller. The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet. The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet. The DispatcherServlet will take help from ViewResolver to pickup the defined view for the request. The DispatcherServlet will take help from ViewResolver to pickup the defined view for the request. Once view is finalized, The DispatcherServlet passes the model data to the view which is finally rendered on the browser. Once view is finalized, The DispatcherServlet passes the model data to the view which is finally rendered on the browser. All the above-mentioned components, i.e. HandlerMapping, Controller, and ViewResolver are parts of WebApplicationContext which is an extension of the plainApplicationContext with some extra features necessary for web applications. You need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in the web.xml file. The following is an example to show declaration and mapping for HelloWeb DispatcherServlet example − <web-app id = "WebApp_ID" version = "2.4" xmlns = "http://java.sun.com/xml/ns/j2ee" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Spring MVC Application</display-name> <servlet> <servlet-name>HelloWeb</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloWeb</servlet-name> <url-pattern>*.jsp</url-pattern> </servlet-mapping> </web-app> The web.xml file will be kept in the WebContent/WEB-INF directory of your web application. Upon initialization of HelloWeb DispatcherServlet, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in the application's WebContent/WEB-INF directory. In this case, our file will be HelloWebservlet.xml. Next, <servlet-mapping> tag indicates what URLs will be handled by which DispatcherServlet. Here all the HTTP requests ending with .jsp will be handled by the HelloWeb DispatcherServlet. If you do not want to go with default filename as [servlet-name]-servlet.xml and default location as WebContent/WEB-INF, you can customize this file name and location by adding the servlet listener ContextLoaderListener in your web.xml file as follows − <web-app...> <!-------- DispatcherServlet definition goes here-----> .... <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/HelloWeb-servlet.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> </web-app> Now, let us check the required configuration for HelloWeb-servlet.xml file, placed in your web application's WebContent/WEB-INF directory − <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:context = "http://www.springframework.org/schema/context" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package = "com.tutorialspoint" /> <bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name = "prefix" value = "/WEB-INF/jsp/" /> <property name = "suffix" value = ".jsp" /> </bean> </beans> Following are the important points about HelloWeb-servlet.xml file − The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined with the same name in the global scope. The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined with the same name in the global scope. The <context:component-scan...> tag will be use to activate Spring MVC annotation scanning capability which allows to make use of annotations like @Controller and @RequestMapping etc. The <context:component-scan...> tag will be use to activate Spring MVC annotation scanning capability which allows to make use of annotations like @Controller and @RequestMapping etc. The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above defined rule, a logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp . The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above defined rule, a logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp . The following section will show you how to create your actual components, i.e., Controller, Model, and View. The DispatcherServlet delegates the request to the controllers to execute the functionality specific to it. The @Controller annotation indicates that a particular class serves the role of a controller. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method. @Controller @RequestMapping("/hello") public class HelloController { @RequestMapping(method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute("message", "Hello Spring MVC Framework!"); return "hello"; } } The @Controller annotation defines the class as a Spring MVC controller. Here, the first usage of @RequestMapping indicates that all handling methods on this controller are relative to the /hello path. Next annotation @RequestMapping(method = RequestMethod.GET) is used to declare the printHello() method as the controller's default service method to handle HTTP GET request. You can define another method to handle any POST request at the same URL. You can write the above controller in another form where you can add additional attributes in @RequestMapping as follows − @Controller public class HelloController { @RequestMapping(value = "/hello", method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute("message", "Hello Spring MVC Framework!"); return "hello"; } } The value attribute indicates the URL to which the handler method is mapped and the method attribute defines the service method to handle HTTP GET request. The following important points are to be noted about the controller defined above − You will define required business logic inside a service method. You can call another method inside this method as per requirement. You will define required business logic inside a service method. You can call another method inside this method as per requirement. Based on the business logic defined, you will create a model within this method. You can use setter different model attributes and these attributes will be accessed by the view to present the final result. This example creates a model with its attribute "message". Based on the business logic defined, you will create a model within this method. You can use setter different model attributes and these attributes will be accessed by the view to present the final result. This example creates a model with its attribute "message". A defined service method can return a String, which contains the name of the view to be used to render the model. This example returns "hello" as logical view name. A defined service method can return a String, which contains the name of the view to be used to render the model. This example returns "hello" as logical view name. Spring MVC supports many types of views for different presentation technologies. These include - JSPs, HTML, PDF, Excel worksheets, XML, Velocity templates, XSLT, JSON, Atom and RSS feeds, JasperReports, etc. But most commonly we use JSP templates written with JSTL. Let us write a simple hello view in /WEB-INF/hello/hello.jsp − <html> <head> <title>Hello Spring MVC</title> </head> <body> <h2>${message}</h2> </body> </html> Here ${message} is the attribute which we have set up inside the Controller. You can have multiple attributes to be displayed inside your view. Based on the above concepts, let us check few important examples which will help you in building your Spring Web Applications − This example will explain how to write a simple Spring Web Hello World application. This example will explain how to write a Spring Web application using HTML forms to submit the data to the controller and display a processed result. Learn how to use page redirection functionality in Spring MVC Framework. Learn how to access static pages along with dynamic pages in Spring MVC Framework. Learn how to handle exceptions in Spring MVC Framework. This is a very easy-to-use Log4J functionality inside Spring applications. The following example will take you through simple steps to explain the simple integration between Log4J and Spring. We assume you already have log4J installed on your machine. If you do not have it then you can download it from https://logging.apache.org/ and simply extract the zipped file in any folder. We will use only log4j-x.y.z.jar in our project. Next, let us have a working Eclipse IDE in place and take the following steps to develop a Dynamic Form-based Web Application using Spring Web Framework − Here is the content of HelloWorld.java file package com.tutorialspoint; public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage() { System.out.println("Your Message : " + message); } } Following is the content of the second file MainApp.java package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.apache.log4j.Logger; public class MainApp { static Logger log = Logger.getLogger(MainApp.class.getName()); public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); log.info("Going to create HelloWord Obj"); HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); obj.getMessage(); log.info("Exiting the program"); } } You can generate debug and error message in a similar way as we have generated info messages. Now let us see the content of Beans.xml file <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld"> <property name = "message" value = "Hello World!"/> </bean> </beans> Following is the content of log4j.properties which defines the standard rules required for Log4J to produce log messages # Define the root logger with appender file log4j.rootLogger = DEBUG, FILE # Define the file appender log4j.appender.FILE=org.apache.log4j.FileAppender # Set the name of the file log4j.appender.FILE.File=C:\\log.out # Set the immediate flush to true (default) log4j.appender.FILE.ImmediateFlush=true # Set the threshold to debug mode log4j.appender.FILE.Threshold=debug # Set the append to false, overwrite log4j.appender.FILE.Append=false # Define the layout for file appender log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.conversionPattern=%m%n Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message in Eclipse console − Your Message : Hello World! If you check your C:\\ drive, then you should find your log file log.out with various log messages, like something as follows − <!-- initialization log messages --> Going to create HelloWord Obj Returning cached instance of singleton bean 'helloWorld' Exiting the program Alternatively you can use Jakarta Commons Logging (JCL) API to generate a log in your Spring application. JCL can be downloaded from the https://jakarta.apache.org/commons/logging/. The only file we technically need out of this package is the commons-logging-x.y.z.jar file, which needs to be placed in your classpath in a similar way as you had put log4j-x.y.z.jar in the above example. To use the logging functionality you need a org.apache.commons.logging.Log object and then you can call one of the following methods as per your requirment − fatal(Object message) error(Object message) warn(Object message) info(Object message) debug(Object message) trace(Object message) Following is the replacement of MainApp.java, which makes use of JCL API package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.apache.commons.logging. Log; import org.apache.commons.logging. LogFactory; public class MainApp { static Log log = LogFactory.getLog(MainApp.class.getName()); public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); log.info("Going to create HelloWord Obj"); HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); obj.getMessage(); log.info("Exiting the program"); } } You have to make sure that you have included commons-logging-x.y.z.jar file in your project, before compiling and running the program. Now keeping the rest of the configuration and content unchanged in the above example, if you compile and run your application, you will get a similar result as what you got using Log4J API. 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2498, "s": 2292, "text": "Spring is the most popular application development framework for enterprise Java. Millions of developers around the world use Spring Framework to create high performing, easily testable, and reusable code." }, { "code": null, "e": 2654, "s": 2498, "text": "Spring framework is an open source Java platform. It was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003." }, { "code": null, "e": 2769, "s": 2654, "text": "Spring is lightweight when it comes to size and transparency. The basic version of Spring framework is around 2MB." }, { "code": null, "e": 3094, "s": 2769, "text": "The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make J2EE development easier to use and promotes good programming practices by enabling a POJO-based programming model." }, { "code": null, "e": 3173, "s": 3094, "text": "Following is the list of few of the great benefits of using Spring Framework −" }, { "code": null, "e": 3472, "s": 3173, "text": "Spring enables developers to develop enterprise-class applications using POJOs. The benefit of using only POJOs is that you do not need an EJB container product such as an application server but you have the option of using only a robust servlet container such as Tomcat or some commercial product." }, { "code": null, "e": 3771, "s": 3472, "text": "Spring enables developers to develop enterprise-class applications using POJOs. The benefit of using only POJOs is that you do not need an EJB container product such as an application server but you have the option of using only a robust servlet container such as Tomcat or some commercial product." }, { "code": null, "e": 3945, "s": 3771, "text": "Spring is organized in a modular fashion. Even though the number of packages and classes are substantial, you have to worry only about the ones you need and ignore the rest." }, { "code": null, "e": 4119, "s": 3945, "text": "Spring is organized in a modular fashion. Even though the number of packages and classes are substantial, you have to worry only about the ones you need and ignore the rest." }, { "code": null, "e": 4325, "s": 4119, "text": "Spring does not reinvent the wheel, instead it truly makes use of some of the existing technologies like several ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, and other view technologies." }, { "code": null, "e": 4531, "s": 4325, "text": "Spring does not reinvent the wheel, instead it truly makes use of some of the existing technologies like several ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, and other view technologies." }, { "code": null, "e": 4763, "s": 4531, "text": "Testing an application written with Spring is simple because environment-dependent code is moved into this framework. Furthermore, by using JavaBeanstyle POJOs, it becomes easier to use dependency injection for injecting test data." }, { "code": null, "e": 4995, "s": 4763, "text": "Testing an application written with Spring is simple because environment-dependent code is moved into this framework. Furthermore, by using JavaBeanstyle POJOs, it becomes easier to use dependency injection for injecting test data." }, { "code": null, "e": 5181, "s": 4995, "text": "Spring's web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over-engineered or less popular web frameworks." }, { "code": null, "e": 5367, "s": 5181, "text": "Spring's web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over-engineered or less popular web frameworks." }, { "code": null, "e": 5532, "s": 5367, "text": "Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions." }, { "code": null, "e": 5697, "s": 5532, "text": "Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions." }, { "code": null, "e": 5918, "s": 5697, "text": "Lightweight IoC containers tend to be lightweight, especially when compared to EJB containers, for example. This is beneficial for developing and deploying applications on computers with limited memory and CPU resources." }, { "code": null, "e": 6139, "s": 5918, "text": "Lightweight IoC containers tend to be lightweight, especially when compared to EJB containers, for example. This is beneficial for developing and deploying applications on computers with limited memory and CPU resources." }, { "code": null, "e": 6345, "s": 6139, "text": "Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example)." }, { "code": null, "e": 6551, "s": 6345, "text": "Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example)." }, { "code": null, "e": 6845, "s": 6551, "text": "The technology that Spring is most identified with is the Dependency Injection (DI) flavor of Inversion of Control. The Inversion of Control (IoC) is a general concept, and it can be expressed in many different ways. Dependency Injection is merely one concrete example of Inversion of Control." }, { "code": null, "e": 7191, "s": 6845, "text": "When writing a complex Java application, application classes should be as independent as possible of other Java classes to increase the possibility to reuse these classes and to test them independently of other classes while unit testing. Dependency Injection helps in gluing these classes together and at the same time keeping them independent." }, { "code": null, "e": 7511, "s": 7191, "text": "What is dependency injection exactly? Let's look at these two words separately. Here the dependency part translates into an association between two classes. For example, class A is dependent of class B. Now, let's look at the second part, injection. All this means is, class B will get injected into class A by the IoC." }, { "code": null, "e": 7773, "s": 7511, "text": "Dependency injection can happen in the way of passing parameters to the constructor or by post-construction using setter methods. As Dependency Injection is the heart of Spring Framework, we will explain this concept in a separate chapter with relevant example." }, { "code": null, "e": 8170, "s": 7773, "text": "One of the key components of Spring is the Aspect Oriented Programming (AOP) framework. The functions that span multiple points of an application are called cross-cutting concerns and these cross-cutting concerns are conceptually separate from the application's business logic. There are various common good examples of aspects including logging, declarative transactions, security, caching, etc." }, { "code": null, "e": 8422, "s": 8170, "text": "The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. DI helps you decouple your application objects from each other, while AOP helps you decouple cross-cutting concerns from the objects that they affect." }, { "code": null, "e": 8720, "s": 8422, "text": "The AOP module of Spring Framework provides an aspect-oriented programming implementation allowing you to define method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated. We will discuss more about Spring AOP concepts in a separate chapter." }, { "code": null, "e": 9028, "s": 8720, "text": "Spring could potentially be a one-stop shop for all your enterprise applications. However, Spring is modular, allowing you to pick and choose which modules are applicable to you, without having to bring in the rest. The following section provides details about all the modules available in Spring Framework." }, { "code": null, "e": 9130, "s": 9028, "text": "The Spring Framework provides about 20 modules which can be used based on an application requirement." }, { "code": null, "e": 9257, "s": 9130, "text": "The Core Container consists of the Core, Beans, Context, and Expression Language modules the details of which are as follows −" }, { "code": null, "e": 9375, "s": 9257, "text": "The Core module provides the fundamental parts of the framework, including the IoC and Dependency Injection features." }, { "code": null, "e": 9493, "s": 9375, "text": "The Core module provides the fundamental parts of the framework, including the IoC and Dependency Injection features." }, { "code": null, "e": 9595, "s": 9493, "text": "The Bean module provides BeanFactory, which is a sophisticated implementation of the factory pattern." }, { "code": null, "e": 9697, "s": 9595, "text": "The Bean module provides BeanFactory, which is a sophisticated implementation of the factory pattern." }, { "code": null, "e": 9920, "s": 9697, "text": "The Context module builds on the solid base provided by the Core and Beans modules and it is a medium to access any objects defined and configured. The ApplicationContext interface is the focal point of the Context module." }, { "code": null, "e": 10143, "s": 9920, "text": "The Context module builds on the solid base provided by the Core and Beans modules and it is a medium to access any objects defined and configured. The ApplicationContext interface is the focal point of the Context module." }, { "code": null, "e": 10257, "s": 10143, "text": "The SpEL module provides a powerful expression language for querying and manipulating an object graph at runtime." }, { "code": null, "e": 10371, "s": 10257, "text": "The SpEL module provides a powerful expression language for querying and manipulating an object graph at runtime." }, { "code": null, "e": 10494, "s": 10371, "text": "The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction modules whose detail is as follows −" }, { "code": null, "e": 10599, "s": 10494, "text": "The JDBC module provides a JDBC-abstraction layer that removes the need for tedious JDBC related coding." }, { "code": null, "e": 10704, "s": 10599, "text": "The JDBC module provides a JDBC-abstraction layer that removes the need for tedious JDBC related coding." }, { "code": null, "e": 10834, "s": 10704, "text": "The ORM module provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis." }, { "code": null, "e": 10964, "s": 10834, "text": "The ORM module provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis." }, { "code": null, "e": 11104, "s": 10964, "text": "The OXM module provides an abstraction layer that supports Object/XML mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream." }, { "code": null, "e": 11244, "s": 11104, "text": "The OXM module provides an abstraction layer that supports Object/XML mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream." }, { "code": null, "e": 11338, "s": 11244, "text": "The Java Messaging Service JMS module contains features for producing and consuming messages." }, { "code": null, "e": 11432, "s": 11338, "text": "The Java Messaging Service JMS module contains features for producing and consuming messages." }, { "code": null, "e": 11586, "s": 11432, "text": "The Transaction module supports programmatic and declarative transaction management for classes that implement special interfaces and for all your POJOs." }, { "code": null, "e": 11740, "s": 11586, "text": "The Transaction module supports programmatic and declarative transaction management for classes that implement special interfaces and for all your POJOs." }, { "code": null, "e": 11858, "s": 11740, "text": "The Web layer consists of the Web, Web-MVC, Web-Socket, and Web-Portlet modules the details of which are as follows −" }, { "code": null, "e": 12074, "s": 11858, "text": "The Web module provides basic web-oriented integration features such as multipart file-upload functionality and the initialization of the IoC container using servlet listeners and a web-oriented application context." }, { "code": null, "e": 12290, "s": 12074, "text": "The Web module provides basic web-oriented integration features such as multipart file-upload functionality and the initialization of the IoC container using servlet listeners and a web-oriented application context." }, { "code": null, "e": 12392, "s": 12290, "text": "The Web-MVC module contains Spring's Model-View-Controller (MVC) implementation for web applications." }, { "code": null, "e": 12494, "s": 12392, "text": "The Web-MVC module contains Spring's Model-View-Controller (MVC) implementation for web applications." }, { "code": null, "e": 12631, "s": 12494, "text": "The Web-Socket module provides support for WebSocket-based, two-way communication between the client and the server in web applications." }, { "code": null, "e": 12768, "s": 12631, "text": "The Web-Socket module provides support for WebSocket-based, two-way communication between the client and the server in web applications." }, { "code": null, "e": 12912, "s": 12768, "text": "The Web-Portlet module provides the MVC implementation to be used in a portlet environment and mirrors the functionality of Web-Servlet module." }, { "code": null, "e": 13056, "s": 12912, "text": "The Web-Portlet module provides the MVC implementation to be used in a portlet environment and mirrors the functionality of Web-Servlet module." }, { "code": null, "e": 13189, "s": 13056, "text": "There are few other important modules like AOP, Aspects, Instrumentation, Web and Test modules the details of which are as follows −" }, { "code": null, "e": 13397, "s": 13189, "text": "The AOP module provides an aspect-oriented programming implementation allowing you to define method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated." }, { "code": null, "e": 13605, "s": 13397, "text": "The AOP module provides an aspect-oriented programming implementation allowing you to define method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated." }, { "code": null, "e": 13711, "s": 13605, "text": "The Aspects module provides integration with AspectJ, which is again a powerful and mature AOP framework." }, { "code": null, "e": 13817, "s": 13711, "text": "The Aspects module provides integration with AspectJ, which is again a powerful and mature AOP framework." }, { "code": null, "e": 13959, "s": 13817, "text": "The Instrumentation module provides class instrumentation support and class loader implementations to be used in certain application servers." }, { "code": null, "e": 14101, "s": 13959, "text": "The Instrumentation module provides class instrumentation support and class loader implementations to be used in certain application servers." }, { "code": null, "e": 14318, "s": 14101, "text": "The Messaging module provides support for STOMP as the WebSocket sub-protocol to use in applications. It also supports an annotation programming model for routing and processing STOMP messages from WebSocket clients." }, { "code": null, "e": 14535, "s": 14318, "text": "The Messaging module provides support for STOMP as the WebSocket sub-protocol to use in applications. It also supports an annotation programming model for routing and processing STOMP messages from WebSocket clients." }, { "code": null, "e": 14626, "s": 14535, "text": "The Test module supports the testing of Spring components with JUnit or TestNG frameworks." }, { "code": null, "e": 14717, "s": 14626, "text": "The Test module supports the testing of Spring components with JUnit or TestNG frameworks." }, { "code": null, "e": 14945, "s": 14717, "text": "This chapter will guide you on how to prepare a development environment to start your work with Spring Framework. It will also teach you how to set up JDK, Tomcat and Eclipse on your machine before you set up Spring Framework −" }, { "code": null, "e": 15341, "s": 14945, "text": "You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively." }, { "code": null, "e": 15485, "s": 15341, "text": "If you are running Windows and have installed the JDK in C:\\jdk1.6.0_15, you would have to put the following line in your C:\\autoexec.bat file." }, { "code": null, "e": 15552, "s": 15485, "text": "set PATH=C:\\jdk1.6.0_15\\bin;%PATH% \nset JAVA_HOME=C:\\jdk1.6.0_15 \n" }, { "code": null, "e": 15759, "s": 15552, "text": "Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button." }, { "code": null, "e": 15924, "s": 15759, "text": "On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.6.0_15 and you use the C shell, you will have to put the following into your .cshrc file." }, { "code": null, "e": 16012, "s": 15924, "text": "setenv PATH /usr/local/jdk1.6.0_15/bin:$PATH \nsetenv JAVA_HOME /usr/local/jdk1.6.0_15 \n" }, { "code": null, "e": 16349, "s": 16012, "text": "Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE." }, { "code": null, "e": 16742, "s": 16349, "text": "You can download the latest version of Apache Commons Logging API from https://commons.apache.org/logging/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\\commons-logging-1.1.1 on Windows, or /usr/local/commons-logging-1.1.1 on Linux/Unix. This directory will have the following jar files and other supporting documents, etc." }, { "code": null, "e": 16877, "s": 16742, "text": "Make sure you set your CLASSPATH variable on this directory properly otherwise you will face a problem while running your application." }, { "code": null, "e": 17041, "s": 16877, "text": "All the examples in this tutorial have been written using Eclipse IDE. So we would suggest you should have the latest version of Eclipse installed on your machine." }, { "code": null, "e": 17358, "s": 17041, "text": "To install Eclipse IDE, download the latest Eclipse binaries from https://www.eclipse.org/downloads/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\\eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately." }, { "code": null, "e": 17483, "s": 17358, "text": "Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe" }, { "code": null, "e": 17509, "s": 17483, "text": "%C:\\eclipse\\eclipse.exe \n" }, { "code": null, "e": 17609, "s": 17509, "text": "Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −" }, { "code": null, "e": 17638, "s": 17609, "text": "$/usr/local/eclipse/eclipse\n" }, { "code": null, "e": 17734, "s": 17638, "text": "After a successful startup, if everything is fine then it should display the following result −" }, { "code": null, "e": 17901, "s": 17734, "text": "Now if everything is fine, then you can proceed to set up your Spring framework. Following are the simple steps to download and install the framework on your machine." }, { "code": null, "e": 18061, "s": 17901, "text": "Make a choice whether you want to install Spring on Windows or Unix, and then proceed to the next step to download .zip file for Windows and .tz file for Unix." }, { "code": null, "e": 18221, "s": 18061, "text": "Make a choice whether you want to install Spring on Windows or Unix, and then proceed to the next step to download .zip file for Windows and .tz file for Unix." }, { "code": null, "e": 18343, "s": 18221, "text": "Download the latest version of Spring framework binaries from https://repo.spring.io/release/org/springframework/spring." }, { "code": null, "e": 18465, "s": 18343, "text": "Download the latest version of Spring framework binaries from https://repo.spring.io/release/org/springframework/spring." }, { "code": null, "e": 18682, "s": 18465, "text": "At the time of developing this tutorial, spring-framework-4.1.6.RELEASE-dist.zip was downloaded on Windows machine. After the downloaded file was unzipped, it gives the following directory structure inside E:\\spring." }, { "code": null, "e": 18899, "s": 18682, "text": "At the time of developing this tutorial, spring-framework-4.1.6.RELEASE-dist.zip was downloaded on Windows machine. After the downloaded file was unzipped, it gives the following directory structure inside E:\\spring." }, { "code": null, "e": 19227, "s": 18899, "text": "You will find all the Spring libraries in the directory E:\\spring\\libs. Make sure you set your CLASSPATH variable on this directory properly otherwise you will face a problem while running your application. If you are using Eclipse, then it is not required to set CLASSPATH because all the setting will be done through Eclipse." }, { "code": null, "e": 19341, "s": 19227, "text": "Once you are done with this last step, you are ready to proceed to your first Spring Example in the next chapter." }, { "code": null, "e": 19664, "s": 19341, "text": "Let us start actual programming with Spring Framework. Before you start writing your first example using Spring framework, you have to make sure that you have set up your Spring environment properly as explained in Spring - Environment Setup Chapter. We also assume that you have a bit of working knowledge on Eclipse IDE." }, { "code": null, "e": 19842, "s": 19664, "text": "Now let us proceed to write a simple Spring Application, which will print \"Hello World!\" or any other message based on the configuration done in Spring Beans Configuration file." }, { "code": null, "e": 20085, "s": 19842, "text": "The first step is to create a simple Java Project using Eclipse IDE. Follow the option File → New → Project and finally select Java Project wizard from the wizard list. Now name your project as HelloSpring using the wizard window as follows −" }, { "code": null, "e": 20191, "s": 20085, "text": "Once your project is created successfully, you will have the following content in your Project Explorer −" }, { "code": null, "e": 20497, "s": 20191, "text": "As a second step let us add Spring Framework and common logging API libraries in our project. To do this, right-click on your project name HelloSpring and then follow the following option available in the context menu − Build Path → Configure Build Path to display the Java Build Path window as follows −" }, { "code": null, "e": 20663, "s": 20497, "text": "Now use Add External JARs button available under the Libraries tab to add the following core JARs from Spring Framework and Common Logging installation directories −" }, { "code": null, "e": 20685, "s": 20663, "text": "commons-logging-1.1.1" }, { "code": null, "e": 20707, "s": 20685, "text": "commons-logging-1.1.1" }, { "code": null, "e": 20732, "s": 20707, "text": "spring-aop-4.1.6.RELEASE" }, { "code": null, "e": 20757, "s": 20732, "text": "spring-aop-4.1.6.RELEASE" }, { "code": null, "e": 20786, "s": 20757, "text": "spring-aspects-4.1.6.RELEASE" }, { "code": null, "e": 20815, "s": 20786, "text": "spring-aspects-4.1.6.RELEASE" }, { "code": null, "e": 20842, "s": 20815, "text": "spring-beans-4.1.6.RELEASE" }, { "code": null, "e": 20869, "s": 20842, "text": "spring-beans-4.1.6.RELEASE" }, { "code": null, "e": 20898, "s": 20869, "text": "spring-context-4.1.6.RELEASE" }, { "code": null, "e": 20927, "s": 20898, "text": "spring-context-4.1.6.RELEASE" }, { "code": null, "e": 20964, "s": 20927, "text": "spring-context-support-4.1.6.RELEASE" }, { "code": null, "e": 21001, "s": 20964, "text": "spring-context-support-4.1.6.RELEASE" }, { "code": null, "e": 21027, "s": 21001, "text": "spring-core-4.1.6.RELEASE" }, { "code": null, "e": 21053, "s": 21027, "text": "spring-core-4.1.6.RELEASE" }, { "code": null, "e": 21085, "s": 21053, "text": "spring-expression-4.1.6.RELEASE" }, { "code": null, "e": 21117, "s": 21085, "text": "spring-expression-4.1.6.RELEASE" }, { "code": null, "e": 21149, "s": 21117, "text": "spring-instrument-4.1.6.RELEASE" }, { "code": null, "e": 21181, "s": 21149, "text": "spring-instrument-4.1.6.RELEASE" }, { "code": null, "e": 21220, "s": 21181, "text": "spring-instrument-tomcat-4.1.6.RELEASE" }, { "code": null, "e": 21259, "s": 21220, "text": "spring-instrument-tomcat-4.1.6.RELEASE" }, { "code": null, "e": 21285, "s": 21259, "text": "spring-jdbc-4.1.6.RELEASE" }, { "code": null, "e": 21311, "s": 21285, "text": "spring-jdbc-4.1.6.RELEASE" }, { "code": null, "e": 21336, "s": 21311, "text": "spring-jms-4.1.6.RELEASE" }, { "code": null, "e": 21361, "s": 21336, "text": "spring-jms-4.1.6.RELEASE" }, { "code": null, "e": 21392, "s": 21361, "text": "spring-messaging-4.1.6.RELEASE" }, { "code": null, "e": 21423, "s": 21392, "text": "spring-messaging-4.1.6.RELEASE" }, { "code": null, "e": 21448, "s": 21423, "text": "spring-orm-4.1.6.RELEASE" }, { "code": null, "e": 21473, "s": 21448, "text": "spring-orm-4.1.6.RELEASE" }, { "code": null, "e": 21498, "s": 21473, "text": "spring-oxm-4.1.6.RELEASE" }, { "code": null, "e": 21523, "s": 21498, "text": "spring-oxm-4.1.6.RELEASE" }, { "code": null, "e": 21549, "s": 21523, "text": "spring-test-4.1.6.RELEASE" }, { "code": null, "e": 21575, "s": 21549, "text": "spring-test-4.1.6.RELEASE" }, { "code": null, "e": 21599, "s": 21575, "text": "spring-tx-4.1.6.RELEASE" }, { "code": null, "e": 21623, "s": 21599, "text": "spring-tx-4.1.6.RELEASE" }, { "code": null, "e": 21648, "s": 21623, "text": "spring-web-4.1.6.RELEASE" }, { "code": null, "e": 21673, "s": 21648, "text": "spring-web-4.1.6.RELEASE" }, { "code": null, "e": 21701, "s": 21673, "text": "spring-webmvc-4.1.6.RELEASE" }, { "code": null, "e": 21729, "s": 21701, "text": "spring-webmvc-4.1.6.RELEASE" }, { "code": null, "e": 21765, "s": 21729, "text": "spring-webmvc-portlet-4.1.6.RELEASE" }, { "code": null, "e": 21801, "s": 21765, "text": "spring-webmvc-portlet-4.1.6.RELEASE" }, { "code": null, "e": 21832, "s": 21801, "text": "spring-websocket-4.1.6.RELEASE" }, { "code": null, "e": 21863, "s": 21832, "text": "spring-websocket-4.1.6.RELEASE" }, { "code": null, "e": 22091, "s": 21863, "text": "Now let us create actual source files under the HelloSpring project. First we need to create a package called com.tutorialspoint. To do this, right click on src in package explorer section and follow the option − New → Package." }, { "code": null, "e": 22188, "s": 22091, "text": "Next we will create HelloWorld.java and MainApp.java files under the com.tutorialspoint package." }, { "code": null, "e": 22234, "s": 22188, "text": "Here is the content of HelloWorld.java file −" }, { "code": null, "e": 22487, "s": 22234, "text": "package com.tutorialspoint;\n\npublic class HelloWorld {\n private String message;\n\n public void setMessage(String message){\n this.message = message;\n }\n public void getMessage(){\n System.out.println(\"Your Message : \" + message);\n }\n}" }, { "code": null, "e": 22546, "s": 22487, "text": "Following is the content of the second file MainApp.java −" }, { "code": null, "e": 22955, "s": 22546, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n HelloWorld obj = (HelloWorld) context.getBean(\"helloWorld\");\n obj.getMessage();\n }\n}" }, { "code": null, "e": 23027, "s": 22955, "text": "Following two important points are to be noted about the main program −" }, { "code": null, "e": 23330, "s": 23027, "text": "The first step is to create an application context where we used framework API ClassPathXmlApplicationContext(). This API loads beans configuration file and eventually based on the provided API, it takes care of creating and initializing all the objects, i.e. beans mentioned in the configuration file." }, { "code": null, "e": 23633, "s": 23330, "text": "The first step is to create an application context where we used framework API ClassPathXmlApplicationContext(). This API loads beans configuration file and eventually based on the provided API, it takes care of creating and initializing all the objects, i.e. beans mentioned in the configuration file." }, { "code": null, "e": 23907, "s": 23633, "text": "The second step is used to get the required bean using getBean() method of the created context. This method uses bean ID to return a generic object, which finally can be casted to the actual object. Once you have an object, you can use this object to call any class method." }, { "code": null, "e": 24181, "s": 23907, "text": "The second step is used to get the required bean using getBean() method of the created context. This method uses bean ID to return a generic object, which finally can be casted to the actual object. Once you have an object, you can use this object to call any class method." }, { "code": null, "e": 24410, "s": 24181, "text": "You need to create a Bean Configuration file which is an XML file and acts as a cement that glues the beans, i.e. the classes together. This file needs to be created under the src directory as shown in the following screenshot −" }, { "code": null, "e": 24689, "s": 24410, "text": "Usually developers name this file as Beans.xml, but you are independent to choose any name you like. You have to make sure that this file is available in CLASSPATH and use the same name in the main application while creating an application context as shown in MainApp.java file." }, { "code": null, "e": 25076, "s": 24689, "text": "The Beans.xml is used to assign unique IDs to different beans and to control the creation of objects with different values without impacting any of the Spring source files. For example, using the following file you can pass any value for \"message\" variable and you can print different values of message without impacting HelloWorld.java and MainApp.java files. Let us see how it works −" }, { "code": null, "e": 25527, "s": 25076, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <bean id = \"helloWorld\" class = \"com.tutorialspoint.HelloWorld\">\n <property name = \"message\" value = \"Hello World!\"/>\n </bean>\n\n</beans>" }, { "code": null, "e": 25825, "s": 25527, "text": "When Spring application gets loaded into the memory, Framework makes use of the above configuration file to create all the beans defined and assigns them a unique ID as defined in <bean> tag. You can use <property> tag to pass the values of different variables used at the time of object creation." }, { "code": null, "e": 26247, "s": 25825, "text": "Once you are done with creating the source and beans configuration files, you are ready for this step, which is compiling and running your program. To do this, keep MainApp.Java file tab active and use either Run option available in the Eclipse IDE or use Ctrl + F11 to compile and run your MainApp application. If everything is fine with your application, this will print the following message in Eclipse IDE's console −" }, { "code": null, "e": 26276, "s": 26247, "text": "Your Message : Hello World!\n" }, { "code": null, "e": 26503, "s": 26276, "text": "Congratulations, you have successfully created your first Spring Application. You can see the flexibility of the above Spring application by changing the value of \"message\" property and keeping both the source files unchanged." }, { "code": null, "e": 26873, "s": 26503, "text": "The Spring container is at the core of the Spring Framework. The container will create the objects, wire them together, configure them, and manage their complete life cycle from creation till destruction. The Spring container uses DI to manage the components that make up an application. These objects are called Spring Beans, which we will discuss in the next chapter." }, { "code": null, "e": 27329, "s": 26873, "text": "The container gets its instructions on what objects to instantiate, configure, and assemble by reading the configuration metadata provided. The configuration metadata can be represented either by XML, Java annotations, or Java code. The following diagram represents a high-level view of how Spring works. The Spring IoC container makes use of Java POJO classes and configuration metadata to produce a fully configured and executable system or application." }, { "code": null, "e": 27393, "s": 27329, "text": "Spring provides the following two distinct types of containers." }, { "code": null, "e": 27782, "s": 27393, "text": "This is the simplest container providing the basic support for DI and is defined by the org.springframework.beans.factory.BeanFactory interface. The BeanFactory and related interfaces, such as BeanFactoryAware, InitializingBean, DisposableBean, are still present in Spring for the purpose of backward compatibility with a large number of third-party frameworks that integrate with Spring." }, { "code": null, "e": 28080, "s": 27782, "text": "This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners. This container is defined by the org.springframework.context.ApplicationContext interface." }, { "code": null, "e": 28370, "s": 28080, "text": "The ApplicationContext container includes all functionality of the BeanFactorycontainer, so it is generally recommended over BeanFactory. BeanFactory can still be used for lightweight applications like mobile devices or applet-based applications where data volume and speed is significant." }, { "code": null, "e": 28790, "s": 28370, "text": "The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container. For example, in the form of XML <bean/> definitions which you have already seen in the previous chapters." }, { "code": null, "e": 28920, "s": 28790, "text": "Bean definition contains the information called configuration metadata, which is needed for the container to know the following −" }, { "code": null, "e": 28941, "s": 28920, "text": "How to create a bean" }, { "code": null, "e": 28966, "s": 28941, "text": "Bean's lifecycle details" }, { "code": null, "e": 28986, "s": 28966, "text": "Bean's dependencies" }, { "code": null, "e": 29108, "s": 28986, "text": "All the above configuration metadata translates into a set of the following properties that make up each bean definition." }, { "code": null, "e": 29114, "s": 29108, "text": "class" }, { "code": null, "e": 29202, "s": 29114, "text": "This attribute is mandatory and specifies the bean class to be used to create the bean." }, { "code": null, "e": 29207, "s": 29202, "text": "name" }, { "code": null, "e": 29371, "s": 29207, "text": "This attribute specifies the bean identifier uniquely. In XMLbased configuration metadata, you use the id and/or name attributes to specify the bean identifier(s)." }, { "code": null, "e": 29377, "s": 29371, "text": "scope" }, { "code": null, "e": 29518, "s": 29377, "text": "This attribute specifies the scope of the objects created from a particular bean definition and it will be discussed in bean scopes chapter." }, { "code": null, "e": 29534, "s": 29518, "text": "constructor-arg" }, { "code": null, "e": 29620, "s": 29534, "text": "This is used to inject the dependencies and will be discussed in subsequent chapters." }, { "code": null, "e": 29631, "s": 29620, "text": "properties" }, { "code": null, "e": 29717, "s": 29631, "text": "This is used to inject the dependencies and will be discussed in subsequent chapters." }, { "code": null, "e": 29733, "s": 29717, "text": "autowiring mode" }, { "code": null, "e": 29819, "s": 29733, "text": "This is used to inject the dependencies and will be discussed in subsequent chapters." }, { "code": null, "e": 29844, "s": 29819, "text": "lazy-initialization mode" }, { "code": null, "e": 29974, "s": 29844, "text": "A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at the startup." }, { "code": null, "e": 29996, "s": 29974, "text": "initialization method" }, { "code": null, "e": 30149, "s": 29996, "text": "A callback to be called just after all necessary properties on the bean have been set by the container. It will be discussed in bean life cycle chapter." }, { "code": null, "e": 30168, "s": 30149, "text": "destruction method" }, { "code": null, "e": 30292, "s": 30168, "text": "A callback to be used when the container containing the bean is destroyed. It will be discussed in bean life cycle chapter." }, { "code": null, "e": 30510, "s": 30292, "text": "Spring IoC container is totally decoupled from the format in which this configuration metadata is actually written. Following are the three important methods to provide configuration metadata to the Spring Container −" }, { "code": null, "e": 30540, "s": 30510, "text": "XML based configuration file." }, { "code": null, "e": 30571, "s": 30540, "text": "Annotation-based configuration" }, { "code": null, "e": 30596, "s": 30571, "text": "Java-based configuration" }, { "code": null, "e": 30858, "s": 30596, "text": "You already have seen how XML-based configuration metadata is provided to the container, but let us see another sample of XML-based configuration file with different bean definitions including lazy initialization, initialization method, and destruction method −" }, { "code": null, "e": 31943, "s": 30858, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <!-- A simple bean definition -->\n <bean id = \"...\" class = \"...\">\n <!-- collaborators and configuration for this bean go here -->\n </bean>\n\n <!-- A bean definition with lazy init set on -->\n <bean id = \"...\" class = \"...\" lazy-init = \"true\">\n <!-- collaborators and configuration for this bean go here -->\n </bean>\n\n <!-- A bean definition with initialization method -->\n <bean id = \"...\" class = \"...\" init-method = \"...\">\n <!-- collaborators and configuration for this bean go here -->\n </bean>\n\n <!-- A bean definition with destruction method -->\n <bean id = \"...\" class = \"...\" destroy-method = \"...\">\n <!-- collaborators and configuration for this bean go here -->\n </bean>\n\n <!-- more bean definitions go here -->\n \n</beans>" }, { "code": null, "e": 32048, "s": 31943, "text": "You can check Spring Hello World Example to understand how to define, configure and create Spring Beans." }, { "code": null, "e": 32319, "s": 32048, "text": "We will discuss about Annotation Based Configuration in a separate chapter. It is intentionally discussed in a separate chapter as we want you to grasp a few other important Spring concepts, before you start programming with Spring Dependency Injection with Annotations." }, { "code": null, "e": 32698, "s": 32319, "text": "When defining a <bean> you have the option of declaring a scope for that bean. For example, to force Spring to produce a new bean instance each time one is needed, you should declare the bean's scope attribute to be prototype. Similarly, if you want Spring to return the same bean instance each time one is needed, you should declare the bean's scope attribute to be singleton." }, { "code": null, "e": 32832, "s": 32698, "text": "The Spring Framework supports the following five scopes, three of which are available only if you use a web-aware ApplicationContext." }, { "code": null, "e": 32842, "s": 32832, "text": "singleton" }, { "code": null, "e": 32931, "s": 32842, "text": "This scopes the bean definition to a single instance per Spring IoC container (default)." }, { "code": null, "e": 32941, "s": 32931, "text": "prototype" }, { "code": null, "e": 33018, "s": 32941, "text": "This scopes a single bean definition to have any number of object instances." }, { "code": null, "e": 33026, "s": 33018, "text": "request" }, { "code": null, "e": 33144, "s": 33026, "text": "This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext." }, { "code": null, "e": 33152, "s": 33144, "text": "session" }, { "code": null, "e": 33167, "s": 33152, "text": "global-session" }, { "code": null, "e": 33291, "s": 33167, "text": "This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext." }, { "code": null, "e": 33452, "s": 33291, "text": "In this chapter, we will discuss about the first two scopes and the remaining three will be discussed when we discuss about web-aware Spring ApplicationContext." }, { "code": null, "e": 33741, "s": 33452, "text": "If a scope is set to singleton, the Spring IoC container creates exactly one instance of the object defined by that bean definition. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object." }, { "code": null, "e": 33958, "s": 33741, "text": "The default scope is always singleton. However, when you need one and only one instance of a bean, you can set the scope property to singleton in the bean configuration file, as shown in the following code snippet −" }, { "code": null, "e": 34132, "s": 33958, "text": "<!-- A bean definition with singleton scope -->\n<bean id = \"...\" class = \"...\" scope = \"singleton\">\n <!-- collaborators and configuration for this bean go here -->\n</bean>" }, { "code": null, "e": 34237, "s": 34132, "text": "Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −" }, { "code": null, "e": 34283, "s": 34237, "text": "Here is the content of HelloWorld.java file −" }, { "code": null, "e": 34536, "s": 34283, "text": "package com.tutorialspoint;\n\npublic class HelloWorld {\n private String message;\n\n public void setMessage(String message){\n this.message = message;\n }\n public void getMessage(){\n System.out.println(\"Your Message : \" + message);\n }\n}" }, { "code": null, "e": 34588, "s": 34536, "text": "Following is the content of the MainApp.java file −" }, { "code": null, "e": 35133, "s": 34588, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n HelloWorld objA = (HelloWorld) context.getBean(\"helloWorld\");\n\n objA.setMessage(\"I'm object A\");\n objA.getMessage();\n\n HelloWorld objB = (HelloWorld) context.getBean(\"helloWorld\");\n objB.getMessage();\n }\n}" }, { "code": null, "e": 35210, "s": 35133, "text": "Following is the configuration file Beans.xml required for singleton scope −" }, { "code": null, "e": 35623, "s": 35210, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <bean id = \"helloWorld\" class = \"com.tutorialspoint.HelloWorld\" scope = \"singleton\">\n </bean>\n\n</beans>" }, { "code": null, "e": 35802, "s": 35623, "text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −" }, { "code": null, "e": 35859, "s": 35802, "text": "Your Message : I'm object A\nYour Message : I'm object A\n" }, { "code": null, "e": 36118, "s": 35859, "text": "If the scope is set to prototype, the Spring IoC container creates a new bean instance of the object every time a request for that specific bean is made. As a rule, use the prototype scope for all state-full beans and the singleton scope for stateless beans." }, { "code": null, "e": 36264, "s": 36118, "text": "To define a prototype scope, you can set the scope property to prototype in the bean configuration file, as shown in the following code snippet −" }, { "code": null, "e": 36438, "s": 36264, "text": "<!-- A bean definition with prototype scope -->\n<bean id = \"...\" class = \"...\" scope = \"prototype\">\n <!-- collaborators and configuration for this bean go here -->\n</bean>" }, { "code": null, "e": 36543, "s": 36438, "text": "Let us have working Eclipse IDE in place and follow the following steps to create a Spring application −" }, { "code": null, "e": 36587, "s": 36543, "text": "Here is the content of HelloWorld.java file" }, { "code": null, "e": 36840, "s": 36587, "text": "package com.tutorialspoint;\n\npublic class HelloWorld {\n private String message;\n\n public void setMessage(String message){\n this.message = message;\n }\n public void getMessage(){\n System.out.println(\"Your Message : \" + message);\n }\n}" }, { "code": null, "e": 36892, "s": 36840, "text": "Following is the content of the MainApp.java file −" }, { "code": null, "e": 37437, "s": 36892, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n HelloWorld objA = (HelloWorld) context.getBean(\"helloWorld\");\n\n objA.setMessage(\"I'm object A\");\n objA.getMessage();\n\n HelloWorld objB = (HelloWorld) context.getBean(\"helloWorld\");\n objB.getMessage();\n }\n}" }, { "code": null, "e": 37514, "s": 37437, "text": "Following is the configuration file Beans.xml required for prototype scope −" }, { "code": null, "e": 37927, "s": 37514, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <bean id = \"helloWorld\" class = \"com.tutorialspoint.HelloWorld\" scope = \"prototype\">\n </bean>\n\n</beans>" }, { "code": null, "e": 38106, "s": 37927, "text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −" }, { "code": null, "e": 38155, "s": 38106, "text": "Your Message : I'm object A\nYour Message : null\n" }, { "code": null, "e": 38432, "s": 38155, "text": "The life cycle of a Spring bean is easy to understand. When a bean is instantiated, it may be required to perform some initialization to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required." }, { "code": null, "e": 38721, "s": 38432, "text": "Though, there are lists of the activities that take place behind the scene between the time of bean Instantiation and its destruction, this chapter will discuss only two important bean life cycle callback methods, which are required at the time of bean initialization and its destruction." }, { "code": null, "e": 39060, "s": 38721, "text": "To define setup and teardown for a bean, we simply declare the <bean> with initmethod and/or destroy-method parameters. The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. Similarly, destroymethod specifies a method that is called just before a bean is removed from the container." }, { "code": null, "e": 39153, "s": 39060, "text": "The org.springframework.beans.factory.InitializingBean interface specifies a single method −" }, { "code": null, "e": 39198, "s": 39153, "text": "void afterPropertiesSet() throws Exception;\n" }, { "code": null, "e": 39333, "s": 39198, "text": "Thus, you can simply implement the above interface and initialization work can be done inside afterPropertiesSet() method as follows −" }, { "code": null, "e": 39470, "s": 39333, "text": "public class ExampleBean implements InitializingBean {\n public void afterPropertiesSet() {\n // do some initialization work\n }\n}" }, { "code": null, "e": 39644, "s": 39470, "text": "In the case of XML-based configuration metadata, you can use the init-method attribute to specify the name of the method that has a void no-argument signature. For example −" }, { "code": null, "e": 39724, "s": 39644, "text": "<bean id = \"exampleBean\" class = \"examples.ExampleBean\" init-method = \"init\"/>\n" }, { "code": null, "e": 39760, "s": 39724, "text": "Following is the class definition −" }, { "code": null, "e": 39855, "s": 39760, "text": "public class ExampleBean {\n public void init() {\n // do some initialization work\n }\n}" }, { "code": null, "e": 39946, "s": 39855, "text": "The org.springframework.beans.factory.DisposableBean interface specifies a single method −" }, { "code": null, "e": 39980, "s": 39946, "text": "void destroy() throws Exception;\n" }, { "code": null, "e": 40102, "s": 39980, "text": "Thus, you can simply implement the above interface and finalization work can be done inside destroy() method as follows −" }, { "code": null, "e": 40223, "s": 40102, "text": "public class ExampleBean implements DisposableBean {\n public void destroy() {\n // do some destruction work\n }\n}" }, { "code": null, "e": 40400, "s": 40223, "text": "In the case of XML-based configuration metadata, you can use the destroy-method attribute to specify the name of the method that has a void no-argument signature. For example −" }, { "code": null, "e": 40486, "s": 40400, "text": "<bean id = \"exampleBean\" class = \"examples.ExampleBean\" destroy-method = \"destroy\"/>\n" }, { "code": null, "e": 40522, "s": 40486, "text": "Following is the class definition −" }, { "code": null, "e": 40617, "s": 40522, "text": "public class ExampleBean {\n public void destroy() {\n // do some destruction work\n }\n}" }, { "code": null, "e": 40925, "s": 40617, "text": "If you are using Spring's IoC container in a non-web application environment; for example, in a rich client desktop environment, you register a shutdown hook with the JVM. Doing so ensures a graceful shutdown and calls the relevant destroy methods on your singleton beans so that all resources are released." }, { "code": null, "e": 41094, "s": 40925, "text": "It is recommended that you do not use the InitializingBean or DisposableBean callbacks, because XML configuration gives much flexibility in terms of naming your method." }, { "code": null, "e": 41199, "s": 41094, "text": "Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −" }, { "code": null, "e": 41245, "s": 41199, "text": "Here is the content of HelloWorld.java file −" }, { "code": null, "e": 41666, "s": 41245, "text": "package com.tutorialspoint;\n\npublic class HelloWorld {\n private String message;\n\n public void setMessage(String message){\n this.message = message;\n }\n public void getMessage(){\n System.out.println(\"Your Message : \" + message);\n }\n public void init(){\n System.out.println(\"Bean is going through init.\");\n }\n public void destroy() {\n System.out.println(\"Bean will destroy now.\");\n }\n}" }, { "code": null, "e": 41923, "s": 41666, "text": "Following is the content of the MainApp.java file. Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensure a graceful shutdown and call the relevant destroy methods." }, { "code": null, "e": 42395, "s": 41923, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.support.AbstractApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n AbstractApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n\n HelloWorld obj = (HelloWorld) context.getBean(\"helloWorld\");\n obj.getMessage();\n context.registerShutdownHook();\n }\n}" }, { "code": null, "e": 42481, "s": 42395, "text": "Following is the configuration file Beans.xml required for init and destroy methods −" }, { "code": null, "e": 42987, "s": 42481, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <bean id = \"helloWorld\" class = \"com.tutorialspoint.HelloWorld\" init-method = \"init\" \n destroy-method = \"destroy\">\n <property name = \"message\" value = \"Hello World!\"/>\n </bean>\n\n</beans>" }, { "code": null, "e": 43166, "s": 42987, "text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −" }, { "code": null, "e": 43246, "s": 43166, "text": "Bean is going through init.\nYour Message : Hello World!\nBean will destroy now.\n" }, { "code": null, "e": 43596, "s": 43246, "text": "If you have too many beans having initialization and/or destroy methods with the same name, you don't need to declare init-method and destroy-method on each individual bean. Instead, the framework provides the flexibility to configure such situation using default-init-method and default-destroy-method attributes on the <beans> element as follows −" }, { "code": null, "e": 44055, "s": 43596, "text": "<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\"\n default-init-method = \"init\" \n default-destroy-method = \"destroy\">\n\n <bean id = \"...\" class = \"...\">\n <!-- collaborators and configuration for this bean go here -->\n </bean>\n \n</beans>" }, { "code": null, "e": 44401, "s": 44055, "text": "The BeanPostProcessor interface defines callback methods that you can implement to provide your own instantiation logic, dependency-resolution logic, etc. You can also implement some custom logic after the Spring container finishes instantiating, configuring, and initializing a bean by plugging in one or more BeanPostProcessor implementations." }, { "code": null, "e": 44634, "s": 44401, "text": "You can configure multiple BeanPostProcessor interfaces and you can control the order in which these BeanPostProcessor interfaces execute by setting the order property provided the BeanPostProcessor implements the Ordered interface." }, { "code": null, "e": 44820, "s": 44634, "text": "The BeanPostProcessors operate on bean (or object) instances, which means that the Spring IoC container instantiates a bean instance and then BeanPostProcessor interfaces do their work." }, { "code": null, "e": 45064, "s": 44820, "text": "An ApplicationContext automatically detects any beans that are defined with the implementation of the BeanPostProcessor interface and registers these beans as postprocessors, to be then called appropriately by the container upon bean creation." }, { "code": null, "e": 45184, "s": 45064, "text": "The following examples show how to write, register, and use BeanPostProcessors in the context of an ApplicationContext." }, { "code": null, "e": 45289, "s": 45184, "text": "Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −" }, { "code": null, "e": 45335, "s": 45289, "text": "Here is the content of HelloWorld.java file −" }, { "code": null, "e": 45756, "s": 45335, "text": "package com.tutorialspoint;\n\npublic class HelloWorld {\n private String message;\n\n public void setMessage(String message){\n this.message = message;\n }\n public void getMessage(){\n System.out.println(\"Your Message : \" + message);\n }\n public void init(){\n System.out.println(\"Bean is going through init.\");\n }\n public void destroy(){\n System.out.println(\"Bean will destroy now.\");\n }\n}" }, { "code": null, "e": 46042, "s": 45756, "text": "This is a very basic example of implementing BeanPostProcessor, which prints a bean name before and after initialization of any bean. You can implement more complex logic before and after intializing a bean because you have access on bean object inside both the post processor methods." }, { "code": null, "e": 46092, "s": 46042, "text": "Here is the content of InitHelloWorld.java file −" }, { "code": null, "e": 46795, "s": 46092, "text": "package com.tutorialspoint;\n\nimport org.springframework.beans.factory.config.BeanPostProcessor;\nimport org.springframework.beans.BeansException;\n\npublic class InitHelloWorld implements BeanPostProcessor {\n public Object postProcessBeforeInitialization(Object bean, String beanName) \n throws BeansException {\n \n System.out.println(\"BeforeInitialization : \" + beanName);\n return bean; // you can return any other object as well\n }\n public Object postProcessAfterInitialization(Object bean, String beanName) \n throws BeansException {\n \n System.out.println(\"AfterInitialization : \" + beanName);\n return bean; // you can return any other object as well\n }\n}" }, { "code": null, "e": 47054, "s": 46795, "text": "Following is the content of the MainApp.java file. Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensures a graceful shutdown and calls the relevant destroy methods." }, { "code": null, "e": 47526, "s": 47054, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.support.AbstractApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n AbstractApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n\n HelloWorld obj = (HelloWorld) context.getBean(\"helloWorld\");\n obj.getMessage();\n context.registerShutdownHook();\n }\n}" }, { "code": null, "e": 47612, "s": 47526, "text": "Following is the configuration file Beans.xml required for init and destroy methods −" }, { "code": null, "e": 48174, "s": 47612, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <bean id = \"helloWorld\" class = \"com.tutorialspoint.HelloWorld\"\n init-method = \"init\" destroy-method = \"destroy\">\n <property name = \"message\" value = \"Hello World!\"/>\n </bean>\n\n <bean class = \"com.tutorialspoint.InitHelloWorld\" />\n\n</beans>" }, { "code": null, "e": 48358, "s": 48174, "text": "Once you are done with creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −" }, { "code": null, "e": 48505, "s": 48358, "text": "BeforeInitialization : helloWorld\nBean is going through init.\nAfterInitialization : helloWorld\nYour Message : Hello World!\nBean will destroy now.\n" }, { "code": null, "e": 48726, "s": 48505, "text": "A bean definition can contain a lot of configuration information, including constructor arguments, property values, and container-specific information such as initialization method, static factory method name, and so on." }, { "code": null, "e": 48877, "s": 48726, "text": "A child bean definition inherits configuration data from a parent definition. The child definition can override some values, or add others, as needed." }, { "code": null, "e": 49132, "s": 48877, "text": "Spring Bean definition inheritance has nothing to do with Java class inheritance but the inheritance concept is same. You can define a parent bean definition as a template and other child beans can inherit the required configuration from the parent bean." }, { "code": null, "e": 49306, "s": 49132, "text": "When you use XML-based configuration metadata, you indicate a child bean definition by using the parent attribute, specifying the parent bean as the value of this attribute." }, { "code": null, "e": 49411, "s": 49306, "text": "Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −" }, { "code": null, "e": 49763, "s": 49411, "text": "Following is the configuration file Beans.xml where we defined \"helloWorld\" bean which has two properties message1 and message2. Next \"helloIndia\" bean has been defined as a child of \"helloWorld\" bean by using parent attribute. The child bean inherits message2 property as is, and overrides message1 property and introduces one more property message3." }, { "code": null, "e": 50501, "s": 49763, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <bean id = \"helloWorld\" class = \"com.tutorialspoint.HelloWorld\">\n <property name = \"message1\" value = \"Hello World!\"/>\n <property name = \"message2\" value = \"Hello Second World!\"/>\n </bean>\n\n <bean id =\"helloIndia\" class = \"com.tutorialspoint.HelloIndia\" parent = \"helloWorld\">\n <property name = \"message1\" value = \"Hello India!\"/>\n <property name = \"message3\" value = \"Namaste India!\"/>\n </bean>\n</beans>" }, { "code": null, "e": 50547, "s": 50501, "text": "Here is the content of HelloWorld.java file −" }, { "code": null, "e": 51007, "s": 50547, "text": "package com.tutorialspoint;\n\npublic class HelloWorld {\n private String message1;\n private String message2;\n\n public void setMessage1(String message){\n this.message1 = message;\n }\n public void setMessage2(String message){\n this.message2 = message;\n }\n public void getMessage1(){\n System.out.println(\"World Message1 : \" + message1);\n }\n public void getMessage2(){\n System.out.println(\"World Message2 : \" + message2);\n }\n}" }, { "code": null, "e": 51053, "s": 51007, "text": "Here is the content of HelloIndia.java file −" }, { "code": null, "e": 51714, "s": 51053, "text": "package com.tutorialspoint;\n\npublic class HelloIndia {\n private String message1;\n private String message2;\n private String message3;\n\n public void setMessage1(String message){\n this.message1 = message;\n }\n public void setMessage2(String message){\n this.message2 = message;\n }\n public void setMessage3(String message){\n this.message3 = message;\n }\n public void getMessage1(){\n System.out.println(\"India Message1 : \" + message1);\n }\n public void getMessage2(){\n System.out.println(\"India Message2 : \" + message2);\n }\n public void getMessage3(){\n System.out.println(\"India Message3 : \" + message3);\n }\n}" }, { "code": null, "e": 51766, "s": 51714, "text": "Following is the content of the MainApp.java file −" }, { "code": null, "e": 52358, "s": 51766, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n \n HelloWorld objA = (HelloWorld) context.getBean(\"helloWorld\");\n objA.getMessage1();\n objA.getMessage2();\n\n HelloIndia objB = (HelloIndia) context.getBean(\"helloIndia\");\n objB.getMessage1();\n objB.getMessage2();\n objB.getMessage3();\n }\n}" }, { "code": null, "e": 52537, "s": 52358, "text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −" }, { "code": null, "e": 52704, "s": 52537, "text": "World Message1 : Hello World!\nWorld Message2 : Hello Second World!\nIndia Message1 : Hello India!\nIndia Message2 : Hello Second World!\nIndia Message3 : Namaste India!\n" }, { "code": null, "e": 52843, "s": 52704, "text": "If you observed here, we did not pass message2 while creating \"helloIndia\" bean, but it got passed because of Bean Definition Inheritance." }, { "code": null, "e": 53194, "s": 52843, "text": "You can create a Bean definition template, which can be used by other child bean definitions without putting much effort. While defining a Bean Definition Template, you should not specify the class attribute and should specify abstract attribute and should specify the abstract attribute with a value of true as shown in the following code snippet −" }, { "code": null, "e": 53982, "s": 53194, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <bean id = \"beanTeamplate\" abstract = \"true\">\n <property name = \"message1\" value = \"Hello World!\"/>\n <property name = \"message2\" value = \"Hello Second World!\"/>\n <property name = \"message3\" value = \"Namaste India!\"/>\n </bean>\n\n <bean id = \"helloIndia\" class = \"com.tutorialspoint.HelloIndia\" parent = \"beanTeamplate\">\n <property name = \"message1\" value = \"Hello India!\"/>\n <property name = \"message3\" value = \"Namaste India!\"/>\n </bean>\n \n</beans>" }, { "code": null, "e": 54256, "s": 53982, "text": "The parent bean cannot be instantiated on its own because it is incomplete, and it is also explicitly marked as abstract. When a definition is abstract like this, it is usable only as a pure template bean definition that serves as a parent definition for child definitions." }, { "code": null, "e": 54756, "s": 54256, "text": "Every Java-based application has a few objects that work together to present what the end-user sees as a working application. When writing a complex Java application, application classes should be as independent as possible of other Java classes to increase the possibility to reuse these classes and to test them independently of other classes while unit testing. Dependency Injection (or sometime called wiring) helps in gluing these classes together and at the same time keeping them independent." }, { "code": null, "e": 54914, "s": 54756, "text": "Consider you have an application which has a text editor component and you want to provide a spell check. Your standard code would look something like this −" }, { "code": null, "e": 55055, "s": 54914, "text": "public class TextEditor {\n private SpellChecker spellChecker;\n \n public TextEditor() {\n spellChecker = new SpellChecker();\n }\n}" }, { "code": null, "e": 55224, "s": 55055, "text": "What we've done here is, create a dependency between the TextEditor and the SpellChecker. In an inversion of control scenario, we would instead do something like this −" }, { "code": null, "e": 55389, "s": 55224, "text": "public class TextEditor {\n private SpellChecker spellChecker;\n \n public TextEditor(SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n}" }, { "code": null, "e": 55654, "s": 55389, "text": "Here, the TextEditor should not worry about SpellChecker implementation. The SpellChecker will be implemented independently and will be provided to the TextEditor at the time of TextEditor instantiation. This entire procedure is controlled by the Spring Framework." }, { "code": null, "e": 56035, "s": 55654, "text": "Here, we have removed total control from the TextEditor and kept it somewhere else (i.e. XML configuration file) and the dependency (i.e. class SpellChecker) is being injected into the class TextEditor through a Class Constructor. Thus the flow of control has been \"inverted\" by Dependency Injection (DI) because you have effectively delegated dependances to some external system." }, { "code": null, "e": 56262, "s": 56035, "text": "The second method of injecting dependency is through Setter Methods of the TextEditor class where we will create a SpellChecker instance. This instance will be used to call setter methods to initialize TextEditor's properties." }, { "code": null, "e": 56375, "s": 56262, "text": "Thus, DI exists in two major variants and the following two sub-chapters will cover both of them with examples −" }, { "code": null, "e": 56538, "s": 56375, "text": "Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on the other class." }, { "code": null, "e": 56728, "s": 56538, "text": "Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean." }, { "code": null, "e": 56910, "s": 56728, "text": "You can mix both, Constructor-based and Setter-based DI but it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies." }, { "code": null, "e": 57199, "s": 56910, "text": "The code is cleaner with the DI principle and decoupling is more effective when objects are provided with their dependencies. The object does not look up its dependencies and does not know the location or class of the dependencies, rather everything is taken care by the Spring Framework." }, { "code": null, "e": 57483, "s": 57199, "text": "As you know Java inner classes are defined within the scope of other classes, similarly, inner beans are beans that are defined within the scope of another bean. Thus, a <bean/> element inside the <property/> or <constructor-arg/> elements is called inner bean and it is shown below." }, { "code": null, "e": 57948, "s": 57483, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <bean id = \"outerBean\" class = \"...\">\n <property name = \"target\">\n <bean id = \"innerBean\" class = \"...\"/>\n </property>\n </bean>\n\n</beans>" }, { "code": null, "e": 58053, "s": 57948, "text": "Let us have working Eclipse IDE in place and follow the following steps to create a Spring application −" }, { "code": null, "e": 58099, "s": 58053, "text": "Here is the content of TextEditor.java file −" }, { "code": null, "e": 58600, "s": 58099, "text": "package com.tutorialspoint;\n\npublic class TextEditor {\n private SpellChecker spellChecker;\n \n // a setter method to inject the dependency.\n public void setSpellChecker(SpellChecker spellChecker) {\n System.out.println(\"Inside setSpellChecker.\" );\n this.spellChecker = spellChecker;\n }\n \n // a getter method to return spellChecker\n public SpellChecker getSpellChecker() {\n return spellChecker;\n }\n public void spellCheck() {\n spellChecker.checkSpelling();\n }\n}" }, { "code": null, "e": 58677, "s": 58600, "text": "Following is the content of another dependent class file SpellChecker.java −" }, { "code": null, "e": 58919, "s": 58677, "text": "package com.tutorialspoint;\n\npublic class SpellChecker {\n public SpellChecker(){\n System.out.println(\"Inside SpellChecker constructor.\" );\n }\n public void checkSpelling(){\n System.out.println(\"Inside checkSpelling.\" );\n }\n}" }, { "code": null, "e": 58971, "s": 58919, "text": "Following is the content of the MainApp.java file −" }, { "code": null, "e": 59378, "s": 58971, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n TextEditor te = (TextEditor) context.getBean(\"textEditor\");\n te.spellCheck();\n }\n}" }, { "code": null, "e": 59503, "s": 59378, "text": "Following is the configuration file Beans.xml which has configuration for the setter-based injection but using inner beans −" }, { "code": null, "e": 60092, "s": 59503, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <!-- Definition for textEditor bean using inner bean -->\n <bean id = \"textEditor\" class = \"com.tutorialspoint.TextEditor\">\n <property name = \"spellChecker\">\n <bean id = \"spellChecker\" class = \"com.tutorialspoint.SpellChecker\"/>\n </property>\n </bean>\n\n</beans>" }, { "code": null, "e": 60271, "s": 60092, "text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −" }, { "code": null, "e": 60351, "s": 60271, "text": "Inside SpellChecker constructor.\nInside setSpellChecker.\nInside checkSpelling.\n" }, { "code": null, "e": 60580, "s": 60351, "text": "You have seen how to configure primitive data type using value attribute and object references using ref attribute of the <property> tag in your Bean configuration file. Both the cases deal with passing singular value to a bean." }, { "code": null, "e": 60800, "s": 60580, "text": "Now what if you want to pass plural values like Java Collection types such as List, Set, Map, and Properties. To handle the situation, Spring offers four types of collection configuration elements which are as follows −" }, { "code": null, "e": 60807, "s": 60800, "text": "<list>" }, { "code": null, "e": 60880, "s": 60807, "text": "This helps in wiring ie injecting a list of values, allowing duplicates." }, { "code": null, "e": 60886, "s": 60880, "text": "<set>" }, { "code": null, "e": 60951, "s": 60886, "text": "This helps in wiring a set of values but without any duplicates." }, { "code": null, "e": 60957, "s": 60951, "text": "<map>" }, { "code": null, "e": 61058, "s": 60957, "text": "This can be used to inject a collection of name-value pairs where name and value can be of any type." }, { "code": null, "e": 61066, "s": 61058, "text": "<props>" }, { "code": null, "e": 61169, "s": 61066, "text": "This can be used to inject a collection of name-value pairs where the name and value are both Strings." }, { "code": null, "e": 61268, "s": 61169, "text": "You can use either <list> or <set> to wire any implementation of java.util.Collection or an array." }, { "code": null, "e": 61421, "s": 61268, "text": "You will come across two situations (a) Passing direct values of the collection and (b) Passing a reference of a bean as one of the collection elements." }, { "code": null, "e": 61526, "s": 61421, "text": "Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −" }, { "code": null, "e": 61576, "s": 61526, "text": "Here is the content of JavaCollection.java file −" }, { "code": null, "e": 63002, "s": 61576, "text": "package com.tutorialspoint;\nimport java.util.*;\n\npublic class JavaCollection {\n List addressList;\n Set addressSet;\n Map addressMap;\n Properties addressProp;\n\n // a setter method to set List\n public void setAddressList(List addressList) {\n this.addressList = addressList;\n }\n \n // prints and returns all the elements of the list.\n public List getAddressList() {\n System.out.println(\"List Elements :\" + addressList);\n return addressList;\n }\n \n // a setter method to set Set\n public void setAddressSet(Set addressSet) {\n this.addressSet = addressSet;\n }\n \n // prints and returns all the elements of the Set.\n public Set getAddressSet() {\n System.out.println(\"Set Elements :\" + addressSet);\n return addressSet;\n }\n \n // a setter method to set Map\n public void setAddressMap(Map addressMap) {\n this.addressMap = addressMap;\n }\n \n // prints and returns all the elements of the Map.\n public Map getAddressMap() {\n System.out.println(\"Map Elements :\" + addressMap);\n return addressMap;\n }\n \n // a setter method to set Property\n public void setAddressProp(Properties addressProp) {\n this.addressProp = addressProp;\n }\n \n // prints and returns all the elements of the Property.\n public Properties getAddressProp() {\n System.out.println(\"Property Elements :\" + addressProp);\n return addressProp;\n }\n}" }, { "code": null, "e": 63054, "s": 63002, "text": "Following is the content of the MainApp.java file −" }, { "code": null, "e": 63554, "s": 63054, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n JavaCollection jc=(JavaCollection)context.getBean(\"javaCollection\");\n\n jc.getAddressList();\n jc.getAddressSet();\n jc.getAddressMap();\n jc.getAddressProp();\n }\n}" }, { "code": null, "e": 63658, "s": 63554, "text": "Following is the configuration file Beans.xml which has configuration for all the type of collections −" }, { "code": null, "e": 65393, "s": 63658, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <!-- Definition for javaCollection -->\n <bean id = \"javaCollection\" class = \"com.tutorialspoint.JavaCollection\">\n \n <!-- results in a setAddressList(java.util.List) call -->\n <property name = \"addressList\">\n <list>\n <value>INDIA</value>\n <value>Pakistan</value>\n <value>USA</value>\n <value>USA</value>\n </list>\n </property>\n\n <!-- results in a setAddressSet(java.util.Set) call -->\n <property name = \"addressSet\">\n <set>\n <value>INDIA</value>\n <value>Pakistan</value>\n <value>USA</value>\n <value>USA</value>\n </set>\n </property>\n\n <!-- results in a setAddressMap(java.util.Map) call -->\n <property name = \"addressMap\">\n <map>\n <entry key = \"1\" value = \"INDIA\"/>\n <entry key = \"2\" value = \"Pakistan\"/>\n <entry key = \"3\" value = \"USA\"/>\n <entry key = \"4\" value = \"USA\"/>\n </map>\n </property>\n \n <!-- results in a setAddressProp(java.util.Properties) call -->\n <property name = \"addressProp\">\n <props>\n <prop key = \"one\">INDIA</prop>\n <prop key = \"one\">INDIA</prop>\n <prop key = \"two\">Pakistan</prop>\n <prop key = \"three\">USA</prop>\n <prop key = \"four\">USA</prop>\n </props>\n </property>\n </bean>\n\n</beans>" }, { "code": null, "e": 65572, "s": 65393, "text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −" }, { "code": null, "e": 65788, "s": 65572, "text": "List Elements :[INDIA, Pakistan, USA, USA] \nSet Elements :[INDIA, Pakistan, USA] \nap Elements :{1 = INDIA, 2 = Pakistan, 3 = USA, 4 = USA} \nProperty Elements :{two = Pakistan, one = INDIA, three = USA, four = USA} \n" }, { "code": null, "e": 66002, "s": 65788, "text": "The following Bean definition will help you understand how to inject bean references as one of the collection's element. Even you can mix references and values all together as shown in the following code snippet −" }, { "code": null, "e": 67253, "s": 66002, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <!-- Bean Definition to handle references and values -->\n <bean id = \"...\" class = \"...\">\n\n <!-- Passing bean reference for java.util.List -->\n <property name = \"addressList\">\n <list>\n <ref bean = \"address1\"/>\n <ref bean = \"address2\"/>\n <value>Pakistan</value>\n </list>\n </property>\n \n <!-- Passing bean reference for java.util.Set -->\n <property name = \"addressSet\">\n <set>\n <ref bean = \"address1\"/>\n <ref bean = \"address2\"/>\n <value>Pakistan</value>\n </set>\n </property>\n \n <!-- Passing bean reference for java.util.Map -->\n <property name = \"addressMap\">\n <map>\n <entry key = \"one\" value = \"INDIA\"/>\n <entry key = \"two\" value-ref = \"address1\"/>\n <entry key = \"three\" value-ref = \"address2\"/>\n </map>\n </property>\n </bean>\n\n</beans>" }, { "code": null, "e": 67395, "s": 67253, "text": "To use the above bean definition, you need to define your setter methods in such a way that they should be able to handle references as well." }, { "code": null, "e": 67477, "s": 67395, "text": "If you need to pass an empty string as a value, then you can pass it as follows −" }, { "code": null, "e": 67566, "s": 67477, "text": "<bean id = \"...\" class = \"exampleBean\">\n <property name = \"email\" value = \"\"/>\n</bean>" }, { "code": null, "e": 67645, "s": 67566, "text": "The preceding example is equivalent to the Java code: exampleBean.setEmail(\"\")" }, { "code": null, "e": 67713, "s": 67645, "text": "If you need to pass a NULL value, then you can pass it as follows −" }, { "code": null, "e": 67808, "s": 67713, "text": "<bean id = \"...\" class = \"exampleBean\">\n <property name = \"email\"><null/></property>\n</bean>" }, { "code": null, "e": 67889, "s": 67808, "text": "The preceding example is equivalent to the Java code: exampleBean.setEmail(null)" }, { "code": null, "e": 68044, "s": 67889, "text": "You have learnt how to declare beans using the <bean> element and inject <bean> using <constructor-arg> and <property> elements in XML configuration file." }, { "code": null, "e": 68279, "s": 68044, "text": "The Spring container can autowire relationships between collaborating beans without using <constructor-arg> and <property> elements, which helps cut down on the amount of XML configuration you write for a big Spring-based application." }, { "code": null, "e": 68512, "s": 68279, "text": "Following are the autowiring modes, which can be used to instruct the Spring container to use autowiring for dependency injection. You use the autowire attribute of the <bean/> element to specify autowire mode for a bean definition." }, { "code": null, "e": 68733, "s": 68512, "text": "This is default setting which means no autowiring and you should use explicit bean reference for wiring. You have nothing to do special for this wiring. This is what you already have seen in Dependency Injection chapter." }, { "code": null, "e": 69008, "s": 68733, "text": "Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file." }, { "code": null, "e": 69358, "s": 69008, "text": "Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is thrown." }, { "code": null, "e": 69529, "s": 69358, "text": "Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised." }, { "code": null, "e": 69644, "s": 69529, "text": "Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType." }, { "code": null, "e": 69738, "s": 69644, "text": "You can use byType or constructor autowiring mode to wire arrays and other typed-collections." }, { "code": null, "e": 70125, "s": 69738, "text": "Autowiring works best when it is used consistently across a project. If autowiring is not used in general, it might be confusing for developers to use it to wire only one or two bean definitions. Though, autowiring can significantly reduce the need to specify properties or constructor arguments but you should consider the limitations and disadvantages of autowiring before using them." }, { "code": null, "e": 70148, "s": 70125, "text": "Overriding possibility" }, { "code": null, "e": 70270, "s": 70148, "text": "You can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring." }, { "code": null, "e": 70291, "s": 70270, "text": "Primitive data types" }, { "code": null, "e": 70381, "s": 70291, "text": "You cannot autowire so-called simple properties such as primitives, Strings, and Classes." }, { "code": null, "e": 70398, "s": 70381, "text": "Confusing nature" }, { "code": null, "e": 70489, "s": 70398, "text": "Autowiring is less exact than explicit wiring, so if possible prefer using explict wiring." }, { "code": null, "e": 70783, "s": 70489, "text": "Starting from Spring 2.5 it became possible to configure the dependency injection using annotations. So instead of using XML to describe a bean wiring, you can move the bean configuration into the component class itself by using annotations on the relevant class, method, or field declaration." }, { "code": null, "e": 70941, "s": 70783, "text": "Annotation injection is performed before XML injection. Thus, the latter configuration will override the former for properties wired through both approaches." }, { "code": null, "e": 71231, "s": 70941, "text": "Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file. So consider the following configuration file in case you want to use any annotation in your Spring application." }, { "code": null, "e": 71802, "s": 71231, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:context = \"http://www.springframework.org/schema/context\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\n http://www.springframework.org/schema/context\n http://www.springframework.org/schema/context/spring-context-3.0.xsd\">\n\n <context:annotation-config/>\n <!-- bean definitions go here -->\n\n</beans>" }, { "code": null, "e": 72060, "s": 71802, "text": "Once <context:annotation-config/> is configured, you can start annotating your code to indicate that Spring should automatically wire values into properties, methods, and constructors. Let us look at a few important annotations to understand how they work −" }, { "code": null, "e": 72126, "s": 72060, "text": "The @Required annotation applies to bean property setter methods." }, { "code": null, "e": 72243, "s": 72126, "text": "The @Autowired annotation can apply to bean property setter methods, non-setter methods, constructor and properties." }, { "code": null, "e": 72374, "s": 72243, "text": "The @Qualifier annotation along with @Autowired can be used to remove the confusion by specifiying which exact bean will be wired." }, { "code": null, "e": 72485, "s": 72374, "text": "Spring supports JSR-250 based annotations which include @Resource, @PostConstruct and @PreDestroy annotations." }, { "code": null, "e": 72788, "s": 72485, "text": "So far you have seen how we configure Spring beans using XML configuration file. If you are comfortable with XML configuration, then it is really not required to learn how to proceed with Java-based configuration as you are going to achieve the same result using either of the configurations available." }, { "code": null, "e": 72962, "s": 72788, "text": "Java-based configuration option enables you to write most of your Spring configuration without XML but with the help of few Java-based annotations explained in this chapter." }, { "code": null, "e": 73330, "s": 72962, "text": "Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context. The simplest possible @Configuration class would be as follows −" }, { "code": null, "e": 73538, "s": 73330, "text": "package com.tutorialspoint;\nimport org.springframework.context.annotation.*;\n\n@Configuration\npublic class HelloWorldConfig {\n @Bean \n public HelloWorld helloWorld(){\n return new HelloWorld();\n }\n}" }, { "code": null, "e": 73609, "s": 73538, "text": "The above code will be equivalent to the following XML configuration −" }, { "code": null, "e": 73696, "s": 73609, "text": "<beans>\n <bean id = \"helloWorld\" class = \"com.tutorialspoint.HelloWorld\" />\n</beans>" }, { "code": null, "e": 74025, "s": 73696, "text": "Here, the method name is annotated with @Bean works as bean ID and it creates and returns the actual bean. Your configuration class can have a declaration for more than one @Bean. Once your configuration classes are defined, you can load and provide them to Spring container using AnnotationConfigApplicationContext as follows −" }, { "code": null, "e": 74292, "s": 74025, "text": "public static void main(String[] args) {\n ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class);\n \n HelloWorld helloWorld = ctx.getBean(HelloWorld.class);\n helloWorld.setMessage(\"Hello World!\");\n helloWorld.getMessage();\n}" }, { "code": null, "e": 74348, "s": 74292, "text": "You can load various configuration classes as follows −" }, { "code": null, "e": 74670, "s": 74348, "text": "public static void main(String[] args) {\n AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();\n\n ctx.register(AppConfig.class, OtherConfig.class);\n ctx.register(AdditionalConfig.class);\n ctx.refresh();\n\n MyService myService = ctx.getBean(MyService.class);\n myService.doStuff();\n}" }, { "code": null, "e": 74775, "s": 74670, "text": "Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −" }, { "code": null, "e": 74825, "s": 74775, "text": "Here is the content of HelloWorldConfig.java file" }, { "code": null, "e": 75033, "s": 74825, "text": "package com.tutorialspoint;\nimport org.springframework.context.annotation.*;\n\n@Configuration\npublic class HelloWorldConfig {\n @Bean \n public HelloWorld helloWorld(){\n return new HelloWorld();\n }\n}" }, { "code": null, "e": 75077, "s": 75033, "text": "Here is the content of HelloWorld.java file" }, { "code": null, "e": 75330, "s": 75077, "text": "package com.tutorialspoint;\n\npublic class HelloWorld {\n private String message;\n\n public void setMessage(String message){\n this.message = message;\n }\n public void getMessage(){\n System.out.println(\"Your Message : \" + message);\n }\n}" }, { "code": null, "e": 75380, "s": 75330, "text": "Following is the content of the MainApp.java file" }, { "code": null, "e": 75834, "s": 75380, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.annotation.*;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext ctx = \n new AnnotationConfigApplicationContext(HelloWorldConfig.class);\n \n HelloWorld helloWorld = ctx.getBean(HelloWorld.class);\n helloWorld.setMessage(\"Hello World!\");\n helloWorld.getMessage();\n }\n}" }, { "code": null, "e": 76101, "s": 75834, "text": "Once you are done creating all the source files and adding the required additional libraries, let us run the application. You should note that there is no configuration file required. If everything is fine with your application, it will print the following message −" }, { "code": null, "e": 76130, "s": 76101, "text": "Your Message : Hello World!\n" }, { "code": null, "e": 76275, "s": 76130, "text": "When @Beans have dependencies on one another, expressing that the dependency is as simple as having one bean method calling another as follows −" }, { "code": null, "e": 76520, "s": 76275, "text": "package com.tutorialspoint;\nimport org.springframework.context.annotation.*;\n\n@Configuration\npublic class AppConfig {\n @Bean\n public Foo foo() {\n return new Foo(bar());\n }\n @Bean\n public Bar bar() {\n return new Bar();\n }\n}" }, { "code": null, "e": 76642, "s": 76520, "text": "Here, the foo bean receives a reference to bar via the constructor injection. Now let us look at another working example." }, { "code": null, "e": 76747, "s": 76642, "text": "Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −" }, { "code": null, "e": 76797, "s": 76747, "text": "Here is the content of TextEditorConfig.java file" }, { "code": null, "e": 77110, "s": 76797, "text": "package com.tutorialspoint;\nimport org.springframework.context.annotation.*;\n\n@Configuration\npublic class TextEditorConfig {\n @Bean \n public TextEditor textEditor(){\n return new TextEditor( spellChecker() );\n }\n\n @Bean \n public SpellChecker spellChecker(){\n return new SpellChecker( );\n }\n}" }, { "code": null, "e": 77154, "s": 77110, "text": "Here is the content of TextEditor.java file" }, { "code": null, "e": 77475, "s": 77154, "text": "package com.tutorialspoint;\n\npublic class TextEditor {\n private SpellChecker spellChecker;\n\n public TextEditor(SpellChecker spellChecker){\n System.out.println(\"Inside TextEditor constructor.\" );\n this.spellChecker = spellChecker;\n }\n public void spellCheck(){\n spellChecker.checkSpelling();\n }\n}" }, { "code": null, "e": 77550, "s": 77475, "text": "Following is the content of another dependent class file SpellChecker.java" }, { "code": null, "e": 77792, "s": 77550, "text": "package com.tutorialspoint;\n\npublic class SpellChecker {\n public SpellChecker(){\n System.out.println(\"Inside SpellChecker constructor.\" );\n }\n public void checkSpelling(){\n System.out.println(\"Inside checkSpelling.\" );\n }\n}" }, { "code": null, "e": 77842, "s": 77792, "text": "Following is the content of the MainApp.java file" }, { "code": null, "e": 78232, "s": 77842, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.annotation.*;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext ctx = \n new AnnotationConfigApplicationContext(TextEditorConfig.class);\n\n TextEditor te = ctx.getBean(TextEditor.class);\n te.spellCheck();\n }\n}" }, { "code": null, "e": 78499, "s": 78232, "text": "Once you are done creating all the source files and adding the required additional libraries, let us run the application. You should note that there is no configuration file required. If everything is fine with your application, it will print the following message −" }, { "code": null, "e": 78586, "s": 78499, "text": "Inside SpellChecker constructor.\nInside TextEditor constructor.\nInside checkSpelling.\n" }, { "code": null, "e": 78718, "s": 78586, "text": "The @Import annotation allows for loading @Bean definitions from another configuration class. Consider a ConfigA class as follows −" }, { "code": null, "e": 78813, "s": 78718, "text": "@Configuration\npublic class ConfigA {\n @Bean\n public A a() {\n return new A(); \n }\n}" }, { "code": null, "e": 78892, "s": 78813, "text": "You can import above Bean declaration in another Bean Declaration as follows −" }, { "code": null, "e": 79010, "s": 78892, "text": "@Configuration\n@Import(ConfigA.class)\npublic class ConfigB {\n @Bean\n public B b() {\n return new B(); \n }\n}" }, { "code": null, "e": 79162, "s": 79010, "text": "Now, rather than needing to specify both ConfigA.class and ConfigB.class when instantiating the context, only ConfigB needs to be supplied as follows −" }, { "code": null, "e": 79404, "s": 79162, "text": "public static void main(String[] args) {\n ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB.class);\n \n // now both beans A and B will be available...\n A a = ctx.getBean(A.class);\n B b = ctx.getBean(B.class);\n}" }, { "code": null, "e": 79591, "s": 79404, "text": "The @Bean annotation supports specifying arbitrary initialization and destruction callback methods, much like Spring XML's init-method and destroy-method attributes on the bean element −" }, { "code": null, "e": 79881, "s": 79591, "text": "public class Foo {\n public void init() {\n // initialization logic\n }\n public void cleanup() {\n // destruction logic\n }\n}\n@Configuration\npublic class AppConfig {\n @Bean(initMethod = \"init\", destroyMethod = \"cleanup\" )\n public Foo foo() {\n return new Foo();\n }\n}" }, { "code": null, "e": 79979, "s": 79881, "text": "The default scope is singleton, but you can override this with the @Scope annotation as follows −" }, { "code": null, "e": 80104, "s": 79979, "text": "@Configuration\npublic class AppConfig {\n @Bean\n @Scope(\"prototype\")\n public Foo foo() {\n return new Foo();\n }\n}" }, { "code": null, "e": 80464, "s": 80104, "text": "You have seen in all the chapters that the core of Spring is the ApplicationContext, which manages the complete life cycle of the beans. The ApplicationContext publishes certain types of events when loading the beans. For example, a ContextStartedEvent is published when the context is started and ContextStoppedEvent is published when the context is stopped." }, { "code": null, "e": 80741, "s": 80464, "text": "Event handling in the ApplicationContext is provided through the ApplicationEvent class and ApplicationListener interface. Hence, if a bean implements the ApplicationListener, then every time an ApplicationEvent gets published to the ApplicationContext, that bean is notified." }, { "code": null, "e": 80789, "s": 80741, "text": "Spring provides the following standard events −" }, { "code": null, "e": 80811, "s": 80789, "text": "ContextRefreshedEvent" }, { "code": null, "e": 80999, "s": 80811, "text": "This event is published when the ApplicationContext is either initialized or refreshed. This can also be raised using the refresh() method on the ConfigurableApplicationContext interface." }, { "code": null, "e": 81019, "s": 80999, "text": "ContextStartedEvent" }, { "code": null, "e": 81255, "s": 81019, "text": "This event is published when the ApplicationContext is started using the start() method on the ConfigurableApplicationContext interface. You can poll your database or you can restart any stopped application after receiving this event." }, { "code": null, "e": 81275, "s": 81255, "text": "ContextStoppedEvent" }, { "code": null, "e": 81474, "s": 81275, "text": "This event is published when the ApplicationContext is stopped using the stop() method on the ConfigurableApplicationContext interface. You can do required housekeep work after receiving this event." }, { "code": null, "e": 81493, "s": 81474, "text": "ContextClosedEvent" }, { "code": null, "e": 81708, "s": 81493, "text": "This event is published when the ApplicationContext is closed using the close() method on the ConfigurableApplicationContext interface. A closed context reaches its end of life; it cannot be refreshed or restarted." }, { "code": null, "e": 81728, "s": 81708, "text": "RequestHandledEvent" }, { "code": null, "e": 81815, "s": 81728, "text": "This is a web-specific event telling all beans that an HTTP request has been serviced." }, { "code": null, "e": 82094, "s": 81815, "text": "Spring's event handling is single-threaded so if an event is published, until and unless all the receivers get the message, the processes are blocked and the flow will not continue. Hence, care should be taken when designing your application if the event handling is to be used." }, { "code": null, "e": 82366, "s": 82094, "text": "To listen to a context event, a bean should implement the ApplicationListener interface which has just one method onApplicationEvent(). So let us write an example to see how the events propagates and how you can put your code to do required task based on certain events." }, { "code": null, "e": 82471, "s": 82366, "text": "Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −" }, { "code": null, "e": 82515, "s": 82471, "text": "Here is the content of HelloWorld.java file" }, { "code": null, "e": 82768, "s": 82515, "text": "package com.tutorialspoint;\n\npublic class HelloWorld {\n private String message;\n\n public void setMessage(String message){\n this.message = message;\n }\n public void getMessage(){\n System.out.println(\"Your Message : \" + message);\n }\n}" }, { "code": null, "e": 82829, "s": 82768, "text": "Following is the content of the CStartEventHandler.java file" }, { "code": null, "e": 83195, "s": 82829, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationListener;\nimport org.springframework.context.event.ContextStartedEvent;\n\npublic class CStartEventHandler \n implements ApplicationListener<ContextStartedEvent>{\n\n public void onApplicationEvent(ContextStartedEvent event) {\n System.out.println(\"ContextStartedEvent Received\");\n }\n}" }, { "code": null, "e": 83255, "s": 83195, "text": "Following is the content of the CStopEventHandler.java file" }, { "code": null, "e": 83620, "s": 83255, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationListener;\nimport org.springframework.context.event.ContextStoppedEvent;\n\npublic class CStopEventHandler \n implements ApplicationListener<ContextStoppedEvent>{\n\n public void onApplicationEvent(ContextStoppedEvent event) {\n System.out.println(\"ContextStoppedEvent Received\");\n }\n}" }, { "code": null, "e": 83670, "s": 83620, "text": "Following is the content of the MainApp.java file" }, { "code": null, "e": 84237, "s": 83670, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.ConfigurableApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n ConfigurableApplicationContext context = \n new ClassPathXmlApplicationContext(\"Beans.xml\");\n\n // Let us raise a start event.\n context.start();\n\t \n HelloWorld obj = (HelloWorld) context.getBean(\"helloWorld\");\n obj.getMessage();\n\n // Let us raise a stop event.\n context.stop();\n }\n}" }, { "code": null, "e": 84283, "s": 84237, "text": "Following is the configuration file Beans.xml" }, { "code": null, "e": 84903, "s": 84283, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <bean id = \"helloWorld\" class = \"com.tutorialspoint.HelloWorld\">\n <property name = \"message\" value = \"Hello World!\"/>\n </bean>\n\n <bean id = \"cStartEventHandler\" class = \"com.tutorialspoint.CStartEventHandler\"/>\n <bean id = \"cStopEventHandler\" class = \"com.tutorialspoint.CStopEventHandler\"/>\n\n</beans>" }, { "code": null, "e": 85082, "s": 84903, "text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −" }, { "code": null, "e": 85169, "s": 85082, "text": "ContextStartedEvent Received\nYour Message : Hello World!\nContextStoppedEvent Received\n" }, { "code": null, "e": 85400, "s": 85169, "text": "If you like, you can publish your own custom events and later you can capture the same to take any action against those custom events. If you are interested in writing your own custom events, you can check Custom Events in Spring." }, { "code": null, "e": 85580, "s": 85400, "text": "There are number of steps to be taken to write and publish your own custom events. Follow the instructions given in this chapter to write, publish and handle Custom Spring Events." }, { "code": null, "e": 85625, "s": 85580, "text": "Here is the content of CustomEvent.java file" }, { "code": null, "e": 85892, "s": 85625, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationEvent;\n\npublic class CustomEvent extends ApplicationEvent{\n public CustomEvent(Object source) {\n super(source);\n }\n public String toString(){\n return \"My Custom Event\";\n }\n}" }, { "code": null, "e": 85955, "s": 85892, "text": "Following is the content of the CustomEventPublisher.java file" }, { "code": null, "e": 86481, "s": 85955, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationEventPublisher;\nimport org.springframework.context.ApplicationEventPublisherAware;\n\npublic class CustomEventPublisher implements ApplicationEventPublisherAware {\n private ApplicationEventPublisher publisher;\n \n public void setApplicationEventPublisher (ApplicationEventPublisher publisher) {\n this.publisher = publisher;\n }\n public void publish() {\n CustomEvent ce = new CustomEvent(this);\n publisher.publishEvent(ce);\n }\n}" }, { "code": null, "e": 86542, "s": 86481, "text": "Following is the content of the CustomEventHandler.java file" }, { "code": null, "e": 86812, "s": 86542, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationListener;\n\npublic class CustomEventHandler implements ApplicationListener<CustomEvent> {\n public void onApplicationEvent(CustomEvent event) {\n System.out.println(event.toString());\n }\n}" }, { "code": null, "e": 86862, "s": 86812, "text": "Following is the content of the MainApp.java file" }, { "code": null, "e": 87376, "s": 86862, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.ConfigurableApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n ConfigurableApplicationContext context = \n new ClassPathXmlApplicationContext(\"Beans.xml\");\n\t \n CustomEventPublisher cvp = \n (CustomEventPublisher) context.getBean(\"customEventPublisher\");\n \n cvp.publish(); \n cvp.publish();\n }\n}" }, { "code": null, "e": 87422, "s": 87376, "text": "Following is the configuration file Beans.xml" }, { "code": null, "e": 87910, "s": 87422, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <bean id = \"customEventHandler\" class = \"com.tutorialspoint.CustomEventHandler\"/>\n <bean id = \"customEventPublisher\" class = \"com.tutorialspoint.CustomEventPublisher\"/>\n\n</beans>" }, { "code": null, "e": 88089, "s": 87910, "text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −" }, { "code": null, "e": 88120, "s": 88089, "text": "y Custom Event\ny Custom Event\n" }, { "code": null, "e": 88643, "s": 88120, "text": "One of the key components of Spring Framework is the Aspect oriented programming (AOP) framework. Aspect-Oriented Programming entails breaking down program logic into distinct parts called so-called concerns. The functions that span multiple points of an application are called cross-cutting concerns and these cross-cutting concerns are conceptually separate from the application's business logic. There are various common good examples of aspects like logging, auditing, declarative transactions, security, caching, etc." }, { "code": null, "e": 88994, "s": 88643, "text": "The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Dependency Injection helps you decouple your application objects from each other and AOP helps you decouple cross-cutting concerns from the objects that they affect. AOP is like triggers in programming languages such as Perl, .NET, Java, and others." }, { "code": null, "e": 89173, "s": 88994, "text": "Spring AOP module provides interceptors to intercept an application. For example, when a method is executed, you can add extra functionality before or after the method execution." }, { "code": null, "e": 89341, "s": 89173, "text": "Before we start working with AOP, let us become familiar with the AOP concepts and terminology. These terms are not specific to Spring, rather they are related to AOP." }, { "code": null, "e": 89348, "s": 89341, "text": "Aspect" }, { "code": null, "e": 89573, "s": 89348, "text": "This is a module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement." }, { "code": null, "e": 89584, "s": 89573, "text": "Join point" }, { "code": null, "e": 89784, "s": 89584, "text": "This represents a point in your application where you can plug-in the AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework." }, { "code": null, "e": 89791, "s": 89784, "text": "Advice" }, { "code": null, "e": 89976, "s": 89791, "text": "This is the actual action to be taken either before or after the method execution. This is an actual piece of code that is invoked during the program execution by Spring AOP framework." }, { "code": null, "e": 89985, "s": 89976, "text": "Pointcut" }, { "code": null, "e": 90154, "s": 89985, "text": "This is a set of one or more join points where an advice should be executed. You can specify pointcuts using expressions or patterns as we will see in our AOP examples." }, { "code": null, "e": 90167, "s": 90154, "text": "Introduction" }, { "code": null, "e": 90252, "s": 90167, "text": "An introduction allows you to add new methods or attributes to the existing classes." }, { "code": null, "e": 90266, "s": 90252, "text": "Target object" }, { "code": null, "e": 90400, "s": 90266, "text": "The object being advised by one or more aspects. This object will always be a proxied object, also referred to as the advised object." }, { "code": null, "e": 90408, "s": 90400, "text": "Weaving" }, { "code": null, "e": 90579, "s": 90408, "text": "Weaving is the process of linking aspects with other application types or objects to create an advised object. This can be done at compile time, load time, or at runtime." }, { "code": null, "e": 90652, "s": 90579, "text": "Spring aspects can work with five kinds of advice mentioned as follows −" }, { "code": null, "e": 90659, "s": 90652, "text": "before" }, { "code": null, "e": 90701, "s": 90659, "text": "Run advice before the a method execution." }, { "code": null, "e": 90707, "s": 90701, "text": "after" }, { "code": null, "e": 90773, "s": 90707, "text": "Run advice after the method execution, regardless of its outcome." }, { "code": null, "e": 90789, "s": 90773, "text": "after-returning" }, { "code": null, "e": 90868, "s": 90789, "text": "Run advice after the a method execution only if method completes successfully." }, { "code": null, "e": 90883, "s": 90868, "text": "after-throwing" }, { "code": null, "e": 90970, "s": 90883, "text": "Run advice after the a method execution only if method exits by throwing an exception." }, { "code": null, "e": 90977, "s": 90970, "text": "around" }, { "code": null, "e": 91036, "s": 90977, "text": "Run advice before and after the advised method is invoked." }, { "code": null, "e": 91228, "s": 91036, "text": "Spring supports the @AspectJ annotation style approach and the schema-based approach to implement custom aspects. These two approaches have been explained in detail in the following sections." }, { "code": null, "e": 91314, "s": 91228, "text": "Aspects are implemented using the regular classes along with XML based configuration." }, { "code": null, "e": 91421, "s": 91314, "text": "@AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations." }, { "code": null, "e": 91814, "s": 91421, "text": "While working with the database using plain old JDBC, it becomes cumbersome to write unnecessary code to handle exceptions, opening and closing database connections, etc. However, Spring JDBC Framework takes care of all the low-level details starting from opening the connection, prepare and execute the SQL statement, process exceptions, handle transactions and finally close the connection." }, { "code": null, "e": 92006, "s": 91814, "text": "So what you have to do is just define the connection parameters and specify the SQL statement to be executed and do the required work for each iteration while fetching data from the database." }, { "code": null, "e": 92332, "s": 92006, "text": "Spring JDBC provides several approaches and correspondingly different classes to interface with the database. I'm going to take classic and the most popular approach which makes use of JdbcTemplate class of the framework. This is the central framework class that manages all the database communication and exception handling." }, { "code": null, "e": 92652, "s": 92332, "text": "The JDBC Template class executes SQL queries, updates statements, stores procedure calls, performs iteration over ResultSets, and extracts returned parameter values. It also catches JDBC exceptions and translates them to the generic, more informative, exception hierarchy defined in the org.springframework.dao package." }, { "code": null, "e": 92842, "s": 92652, "text": "Instances of the JdbcTemplate class are threadsafe once configured. So you can configure a single instance of a JdbcTemplate and then safely inject this shared reference into multiple DAOs." }, { "code": null, "e": 93103, "s": 92842, "text": "A common practice when using the JDBC Template class is to configure a DataSource in your Spring configuration file, and then dependency-inject that shared DataSource bean into your DAO classes, and the JdbcTemplate is created in the setter for the DataSource." }, { "code": null, "e": 93305, "s": 93103, "text": "Let us create a database table Student in our database TEST. We assume you are working with MySQL database, if you work with any other database then you can change your DDL and SQL queries accordingly." }, { "code": null, "e": 93439, "s": 93305, "text": "CREATE TABLE Student(\n ID INT NOT NULL AUTO_INCREMENT,\n NAME VARCHAR(20) NOT NULL,\n AGE INT NOT NULL,\n PRIMARY KEY (ID)\n);" }, { "code": null, "e": 93657, "s": 93439, "text": "Now we need to supply a DataSource to the JDBC Template so it can configure itself to get database access. You can configure the DataSource in the XML file with a piece of code as shown in the following code snippet −" }, { "code": null, "e": 94007, "s": 93657, "text": "<bean id = \"dataSource\" \n class = \"org.springframework.jdbc.datasource.DriverManagerDataSource\">\n <property name = \"driverClassName\" value = \"com.mysql.jdbc.Driver\"/>\n <property name = \"url\" value = \"jdbc:mysql://localhost:3306/TEST\"/>\n <property name = \"username\" value = \"root\"/>\n <property name = \"password\" value = \"password\"/>\n</bean>" }, { "code": null, "e": 94278, "s": 94007, "text": "DAO stands for Data Access Object, which is commonly used for database interaction. DAOs exist to provide a means to read and write data to the database and they should expose this functionality through an interface by which the rest of the application will access them." }, { "code": null, "e": 94411, "s": 94278, "text": "The DAO support in Spring makes it easy to work with data access technologies like JDBC, Hibernate, JPA, or JDO in a consistent way." }, { "code": null, "e": 94545, "s": 94411, "text": "Let us see how we can perform CRUD (Create, Read, Update and Delete) operation on database tables using SQL and JDBC Template object." }, { "code": null, "e": 94569, "s": 94545, "text": "Querying for an integer" }, { "code": null, "e": 94668, "s": 94569, "text": "String SQL = \"select count(*) from Student\";\nint rowCount = jdbcTemplateObject.queryForInt( SQL );" }, { "code": null, "e": 94688, "s": 94668, "text": "Querying for a long" }, { "code": null, "e": 94789, "s": 94688, "text": "String SQL = \"select count(*) from Student\";\nlong rowCount = jdbcTemplateObject.queryForLong( SQL );" }, { "code": null, "e": 94826, "s": 94789, "text": "A simple query using a bind variable" }, { "code": null, "e": 94944, "s": 94826, "text": "String SQL = \"select age from Student where id = ?\";\nint age = jdbcTemplateObject.queryForInt(SQL, new Object[]{10});" }, { "code": null, "e": 94966, "s": 94944, "text": "Querying for a String" }, { "code": null, "e": 95106, "s": 94966, "text": "String SQL = \"select name from Student where id = ?\";\nString name = jdbcTemplateObject.queryForObject(SQL, new Object[]{10}, String.class);" }, { "code": null, "e": 95139, "s": 95106, "text": "Querying and returning an object" }, { "code": null, "e": 95622, "s": 95139, "text": "String SQL = \"select * from Student where id = ?\";\nStudent student = jdbcTemplateObject.queryForObject(\n SQL, new Object[]{10}, new StudentMapper());\n\npublic class StudentMapper implements RowMapper<Student> {\n public Student mapRow(ResultSet rs, int rowNum) throws SQLException {\n Student student = new Student();\n student.setID(rs.getInt(\"id\"));\n student.setName(rs.getString(\"name\"));\n student.setAge(rs.getInt(\"age\"));\n \n return student;\n }\n}" }, { "code": null, "e": 95662, "s": 95622, "text": "Querying and returning multiple objects" }, { "code": null, "e": 96112, "s": 95662, "text": "String SQL = \"select * from Student\";\nList<Student> students = jdbcTemplateObject.query(\n SQL, new StudentMapper());\n\npublic class StudentMapper implements RowMapper<Student> {\n public Student mapRow(ResultSet rs, int rowNum) throws SQLException {\n Student student = new Student();\n student.setID(rs.getInt(\"id\"));\n student.setName(rs.getString(\"name\"));\n student.setAge(rs.getInt(\"age\"));\n \n return student;\n }\n}" }, { "code": null, "e": 96143, "s": 96112, "text": "Inserting a row into the table" }, { "code": null, "e": 96265, "s": 96143, "text": "String SQL = \"insert into Student (name, age) values (?, ?)\";\njdbcTemplateObject.update( SQL, new Object[]{\"Zara\", 11} );" }, { "code": null, "e": 96295, "s": 96265, "text": "Updating a row into the table" }, { "code": null, "e": 96412, "s": 96295, "text": "String SQL = \"update Student set name = ? where id = ?\";\njdbcTemplateObject.update( SQL, new Object[]{\"Zara\", 10} );" }, { "code": null, "e": 96442, "s": 96412, "text": "Deleting a row from the table" }, { "code": null, "e": 96538, "s": 96442, "text": "String SQL = \"delete Student where id = ?\";\njdbcTemplateObject.update( SQL, new Object[]{20} );" }, { "code": null, "e": 96708, "s": 96538, "text": "You can use the execute(..) method from jdbcTemplate to execute any SQL statements or DDL statements. Following is an example to use CREATE statement to create a table −" }, { "code": null, "e": 96912, "s": 96708, "text": "String SQL = \"CREATE TABLE Student( \" +\n \"ID INT NOT NULL AUTO_INCREMENT, \" +\n \"NAME VARCHAR(20) NOT NULL, \" +\n \"AGE INT NOT NULL, \" +\n \"PRIMARY KEY (ID));\"\n\njdbcTemplateObject.execute( SQL );" }, { "code": null, "e": 97050, "s": 96912, "text": "Based on the above concepts, let us check few important examples which will help you in understanding usage of JDBC framework in Spring −" }, { "code": null, "e": 97129, "s": 97050, "text": "This example will explain how to write a simple JDBC-based Spring application." }, { "code": null, "e": 97196, "s": 97129, "text": "Learn how to call SQL stored procedure while using JDBC in Spring." }, { "code": null, "e": 97590, "s": 97196, "text": "A database transaction is a sequence of actions that are treated as a single unit of work. These actions should either complete entirely or take no effect at all. Transaction management is an important part of RDBMS-oriented enterprise application to ensure data integrity and consistency. The concept of transactions can be described with the following four key properties described as ACID −" }, { "code": null, "e": 97749, "s": 97590, "text": "Atomicity − A transaction should be treated as a single unit of operation, which means either the entire sequence of operations is successful or unsuccessful." }, { "code": null, "e": 97908, "s": 97749, "text": "Atomicity − A transaction should be treated as a single unit of operation, which means either the entire sequence of operations is successful or unsuccessful." }, { "code": null, "e": 98036, "s": 97908, "text": "Consistency − This represents the consistency of the referential integrity of the database, unique primary keys in tables, etc." }, { "code": null, "e": 98164, "s": 98036, "text": "Consistency − This represents the consistency of the referential integrity of the database, unique primary keys in tables, etc." }, { "code": null, "e": 98334, "s": 98164, "text": "Isolation − There may be many transaction processing with the same data set at the same time. Each transaction should be isolated from others to prevent data corruption." }, { "code": null, "e": 98504, "s": 98334, "text": "Isolation − There may be many transaction processing with the same data set at the same time. Each transaction should be isolated from others to prevent data corruption." }, { "code": null, "e": 98671, "s": 98504, "text": "Durability − Once a transaction has completed, the results of this transaction have to be made permanent and cannot be erased from the database due to system failure." }, { "code": null, "e": 98838, "s": 98671, "text": "Durability − Once a transaction has completed, the results of this transaction have to be made permanent and cannot be erased from the database due to system failure." }, { "code": null, "e": 99010, "s": 98838, "text": "A real RDBMS database system will guarantee all four properties for each transaction. The simplistic view of a transaction issued to the database using SQL is as follows −" }, { "code": null, "e": 99065, "s": 99010, "text": "Begin the transaction using begin transaction command." }, { "code": null, "e": 99120, "s": 99065, "text": "Begin the transaction using begin transaction command." }, { "code": null, "e": 99192, "s": 99120, "text": "Perform various deleted, update or insert operations using SQL queries." }, { "code": null, "e": 99264, "s": 99192, "text": "Perform various deleted, update or insert operations using SQL queries." }, { "code": null, "e": 99359, "s": 99264, "text": "If all the operation are successful then perform commit otherwise rollback all the operations." }, { "code": null, "e": 99454, "s": 99359, "text": "If all the operation are successful then perform commit otherwise rollback all the operations." }, { "code": null, "e": 99889, "s": 99454, "text": "Spring framework provides an abstract layer on top of different underlying transaction management APIs. Spring's transaction support aims to provide an alternative to EJB transactions by adding transaction capabilities to POJOs. Spring supports both programmatic and declarative transaction management. EJBs require an application server, but Spring transaction management can be implemented without the need of an application server." }, { "code": null, "e": 100092, "s": 99889, "text": "Local transactions are specific to a single transactional resource like a JDBC connection, whereas global transactions can span multiple transactional resources like transaction in a distributed system." }, { "code": null, "e": 100387, "s": 100092, "text": "Local transaction management can be useful in a centralized computing environment where application components and resources are located at a single site, and transaction management only involves a local data manager running on a single machine. Local transactions are easier to be implemented." }, { "code": null, "e": 100847, "s": 100387, "text": "Global transaction management is required in a distributed computing environment where all the resources are distributed across multiple systems. In such a case, transaction management needs to be done both at local and global levels. A distributed or a global transaction is executed across multiple systems, and its execution requires coordination between the global transaction management system and all the local data managers of all the involved systems." }, { "code": null, "e": 100901, "s": 100847, "text": "Spring supports two types of transaction management −" }, { "code": null, "e": 101089, "s": 100901, "text": "Programmatic transaction management − This means that you have to manage the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain." }, { "code": null, "e": 101277, "s": 101089, "text": "Programmatic transaction management − This means that you have to manage the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain." }, { "code": null, "e": 101465, "s": 101277, "text": "Declarative transaction management − This means you separate transaction management from the business code. You only use annotations or XML-based configuration to manage the transactions." }, { "code": null, "e": 101653, "s": 101465, "text": "Declarative transaction management − This means you separate transaction management from the business code. You only use annotations or XML-based configuration to manage the transactions." }, { "code": null, "e": 102073, "s": 101653, "text": "Declarative transaction management is preferable over programmatic transaction management though it is less flexible than programmatic transaction management, which allows you to control transactions through your code. But as a kind of crosscutting concern, declarative transaction management can be modularized with the AOP approach. Spring supports declarative transaction management through the Spring AOP framework." }, { "code": null, "e": 102229, "s": 102073, "text": "The key to the Spring transaction abstraction is defined by the org.springframework.transaction.PlatformTransactionManager interface, which is as follows −" }, { "code": null, "e": 102526, "s": 102229, "text": "public interface PlatformTransactionManager {\n TransactionStatus getTransaction(TransactionDefinition definition);\n throws TransactionException;\n \n void commit(TransactionStatus status) throws TransactionException;\n void rollback(TransactionStatus status) throws TransactionException;\n}" }, { "code": null, "e": 102593, "s": 102526, "text": "TransactionStatus getTransaction(TransactionDefinition definition)" }, { "code": null, "e": 102715, "s": 102593, "text": "This method returns a currently active transaction or creates a new one, according to the specified propagation behavior." }, { "code": null, "e": 102753, "s": 102715, "text": "void commit(TransactionStatus status)" }, { "code": null, "e": 102823, "s": 102753, "text": "This method commits the given transaction, with regard to its status." }, { "code": null, "e": 102863, "s": 102823, "text": "void rollback(TransactionStatus status)" }, { "code": null, "e": 102921, "s": 102863, "text": "This method performs a rollback of the given transaction." }, { "code": null, "e": 103037, "s": 102921, "text": "The TransactionDefinition is the core interface of the transaction support in Spring and it is defined as follows −" }, { "code": null, "e": 103208, "s": 103037, "text": "public interface TransactionDefinition {\n int getPropagationBehavior();\n int getIsolationLevel();\n String getName();\n int getTimeout();\n boolean isReadOnly();\n}" }, { "code": null, "e": 103237, "s": 103208, "text": "int getPropagationBehavior()" }, { "code": null, "e": 103363, "s": 103237, "text": "This method returns the propagation behavior. Spring offers all of the transaction propagation options familiar from EJB CMT." }, { "code": null, "e": 103387, "s": 103363, "text": "int getIsolationLevel()" }, { "code": null, "e": 103493, "s": 103387, "text": "This method returns the degree to which this transaction is isolated from the work of other transactions." }, { "code": null, "e": 103510, "s": 103493, "text": "String getName()" }, { "code": null, "e": 103560, "s": 103510, "text": "This method returns the name of this transaction." }, { "code": null, "e": 103577, "s": 103560, "text": "int getTimeout()" }, { "code": null, "e": 103657, "s": 103577, "text": "This method returns the time in seconds in which the transaction must complete." }, { "code": null, "e": 103678, "s": 103657, "text": "boolean isReadOnly()" }, { "code": null, "e": 103736, "s": 103678, "text": "This method returns whether the transaction is read-only." }, { "code": null, "e": 103792, "s": 103736, "text": "Following are the possible values for isolation level −" }, { "code": null, "e": 103832, "s": 103792, "text": "TransactionDefinition.ISOLATION_DEFAULT" }, { "code": null, "e": 103869, "s": 103832, "text": "This is the default isolation level." }, { "code": null, "e": 103916, "s": 103869, "text": "TransactionDefinition.ISOLATION_READ_COMMITTED" }, { "code": null, "e": 104008, "s": 103916, "text": "Indicates that dirty reads are prevented; non-repeatable reads and phantom reads can occur." }, { "code": null, "e": 104057, "s": 104008, "text": "TransactionDefinition.ISOLATION_READ_UNCOMMITTED" }, { "code": null, "e": 104136, "s": 104057, "text": "Indicates that dirty reads, non-repeatable reads, and phantom reads can occur." }, { "code": null, "e": 104184, "s": 104136, "text": "TransactionDefinition.ISOLATION_REPEATABLE_READ" }, { "code": null, "e": 104276, "s": 104184, "text": "Indicates that dirty reads and non-repeatable reads are prevented; phantom reads can occur." }, { "code": null, "e": 104321, "s": 104276, "text": "TransactionDefinition.ISOLATION_SERIALIZABLE" }, { "code": null, "e": 104404, "s": 104321, "text": "Indicates that dirty reads, non-repeatable reads, and phantom reads are prevented." }, { "code": null, "e": 104462, "s": 104404, "text": "Following are the possible values for propagation types −" }, { "code": null, "e": 104506, "s": 104462, "text": "TransactionDefinition.PROPAGATION_MANDATORY" }, { "code": null, "e": 104592, "s": 104506, "text": "Supports a current transaction; throws an exception if no current transaction exists." }, { "code": null, "e": 104634, "s": 104592, "text": "TransactionDefinition.PROPAGATION_NESTED " }, { "code": null, "e": 104704, "s": 104634, "text": "Executes within a nested transaction if a current transaction exists." }, { "code": null, "e": 104745, "s": 104704, "text": "TransactionDefinition.PROPAGATION_NEVER " }, { "code": null, "e": 104838, "s": 104745, "text": "Does not support a current transaction; throws an exception if a current transaction exists." }, { "code": null, "e": 104887, "s": 104838, "text": "TransactionDefinition.PROPAGATION_NOT_SUPPORTED " }, { "code": null, "e": 104969, "s": 104887, "text": "Does not support a current transaction; rather always execute nontransactionally." }, { "code": null, "e": 105012, "s": 104969, "text": "TransactionDefinition.PROPAGATION_REQUIRED" }, { "code": null, "e": 105078, "s": 105012, "text": "Supports a current transaction; creates a new one if none exists." }, { "code": null, "e": 105125, "s": 105078, "text": "TransactionDefinition.PROPAGATION_REQUIRES_NEW" }, { "code": null, "e": 105202, "s": 105125, "text": "Creates a new transaction, suspending the current transaction if one exists." }, { "code": null, "e": 105245, "s": 105202, "text": "TransactionDefinition.PROPAGATION_SUPPORTS" }, { "code": null, "e": 105322, "s": 105245, "text": "Supports a current transaction; executes non-transactionally if none exists." }, { "code": null, "e": 105360, "s": 105322, "text": "TransactionDefinition.TIMEOUT_DEFAULT" }, { "code": null, "e": 105462, "s": 105360, "text": "Uses the default timeout of the underlying transaction system, or none if timeouts are not supported." }, { "code": null, "e": 105602, "s": 105462, "text": "The TransactionStatus interface provides a simple way for transactional code to control transaction execution and query transaction status." }, { "code": null, "e": 105806, "s": 105602, "text": "public interface TransactionStatus extends SavepointManager {\n boolean isNewTransaction();\n boolean hasSavepoint();\n void setRollbackOnly();\n boolean isRollbackOnly();\n boolean isCompleted();\n}" }, { "code": null, "e": 105829, "s": 105806, "text": "boolean hasSavepoint()" }, { "code": null, "e": 105973, "s": 105829, "text": "This method returns whether this transaction internally carries a savepoint, i.e., has been created as nested transaction based on a savepoint." }, { "code": null, "e": 105995, "s": 105973, "text": "boolean isCompleted()" }, { "code": null, "e": 106114, "s": 105995, "text": "This method returns whether this transaction is completed, i.e., whether it has already been committed or rolled back." }, { "code": null, "e": 106141, "s": 106114, "text": "boolean isNewTransaction()" }, { "code": null, "e": 106206, "s": 106141, "text": "This method returns true in case the present transaction is new." }, { "code": null, "e": 106231, "s": 106206, "text": "boolean isRollbackOnly()" }, { "code": null, "e": 106309, "s": 106231, "text": "This method returns whether the transaction has been marked as rollback-only." }, { "code": null, "e": 106332, "s": 106309, "text": "void setRollbackOnly()" }, { "code": null, "e": 106383, "s": 106332, "text": "This method sets the transaction as rollback-only." }, { "code": null, "e": 106739, "s": 106383, "text": "The Spring Web MVC framework provides Model-View-Controller (MVC) architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements." }, { "code": null, "e": 106825, "s": 106739, "text": "The Model encapsulates the application data and in general they will consist of POJO." }, { "code": null, "e": 106911, "s": 106825, "text": "The Model encapsulates the application data and in general they will consist of POJO." }, { "code": null, "e": 107045, "s": 106911, "text": "The View is responsible for rendering the model data and in general it generates HTML output that the client's browser can interpret." }, { "code": null, "e": 107179, "s": 107045, "text": "The View is responsible for rendering the model data and in general it generates HTML output that the client's browser can interpret." }, { "code": null, "e": 107313, "s": 107179, "text": "The Controller is responsible for processing user requests and building an appropriate model and passes it to the view for rendering." }, { "code": null, "e": 107447, "s": 107313, "text": "The Controller is responsible for processing user requests and building an appropriate model and passes it to the view for rendering." }, { "code": null, "e": 107703, "s": 107447, "text": "The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that handles all the HTTP requests and responses. The request processing workflow of the Spring Web MVC DispatcherServlet is illustrated in the following diagram −" }, { "code": null, "e": 107804, "s": 107703, "text": "Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet −" }, { "code": null, "e": 107921, "s": 107804, "text": "After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller. " }, { "code": null, "e": 108038, "s": 107921, "text": "After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller. " }, { "code": null, "e": 108266, "s": 108038, "text": "The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet." }, { "code": null, "e": 108494, "s": 108266, "text": "The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet." }, { "code": null, "e": 108593, "s": 108494, "text": "The DispatcherServlet will take help from ViewResolver to pickup the defined view for the request." }, { "code": null, "e": 108692, "s": 108593, "text": "The DispatcherServlet will take help from ViewResolver to pickup the defined view for the request." }, { "code": null, "e": 108815, "s": 108692, "text": "Once view is finalized, The DispatcherServlet passes the model data to the view which is finally rendered on the browser." }, { "code": null, "e": 108938, "s": 108815, "text": "Once view is finalized, The DispatcherServlet passes the model data to the view which is finally rendered on the browser." }, { "code": null, "e": 109169, "s": 108938, "text": "All the above-mentioned components, i.e. HandlerMapping, Controller, and ViewResolver are parts of WebApplicationContext which is an extension of the plainApplicationContext with some extra features necessary for web applications." }, { "code": null, "e": 109386, "s": 109169, "text": "You need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in the web.xml file. The following is an example to show declaration and mapping for HelloWeb DispatcherServlet example −" }, { "code": null, "e": 110065, "s": 109386, "text": "<web-app id = \"WebApp_ID\" version = \"2.4\"\n xmlns = \"http://java.sun.com/xml/ns/j2ee\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://java.sun.com/xml/ns/j2ee \n http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd\">\n \n <display-name>Spring MVC Application</display-name>\n \n <servlet>\n <servlet-name>HelloWeb</servlet-name>\n <servlet-class>\n org.springframework.web.servlet.DispatcherServlet\n </servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n\n <servlet-mapping>\n <servlet-name>HelloWeb</servlet-name>\n <url-pattern>*.jsp</url-pattern>\n </servlet-mapping>\n\n</web-app>" }, { "code": null, "e": 110418, "s": 110065, "text": "The web.xml file will be kept in the WebContent/WEB-INF directory of your web application. Upon initialization of HelloWeb DispatcherServlet, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in the application's WebContent/WEB-INF directory. In this case, our file will be HelloWebservlet.xml." }, { "code": null, "e": 110605, "s": 110418, "text": "Next, <servlet-mapping> tag indicates what URLs will be handled by which DispatcherServlet. Here all the HTTP requests ending with .jsp will be handled by the HelloWeb DispatcherServlet." }, { "code": null, "e": 110859, "s": 110605, "text": "If you do not want to go with default filename as [servlet-name]-servlet.xml and default location as WebContent/WEB-INF, you can customize this file name and location by adding the servlet listener ContextLoaderListener in your web.xml file as follows −" }, { "code": null, "e": 111250, "s": 110859, "text": "<web-app...>\n\n <!-------- DispatcherServlet definition goes here----->\n ....\n <context-param>\n <param-name>contextConfigLocation</param-name>\n <param-value>/WEB-INF/HelloWeb-servlet.xml</param-value>\n </context-param>\n\n <listener>\n <listener-class>\n org.springframework.web.context.ContextLoaderListener\n </listener-class>\n </listener>\n \n</web-app>" }, { "code": null, "e": 111390, "s": 111250, "text": "Now, let us check the required configuration for HelloWeb-servlet.xml file, placed in your web application's WebContent/WEB-INF directory −" }, { "code": null, "e": 112127, "s": 111390, "text": "<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:context = \"http://www.springframework.org/schema/context\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans \n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\n http://www.springframework.org/schema/context \n http://www.springframework.org/schema/context/spring-context-3.0.xsd\">\n\n <context:component-scan base-package = \"com.tutorialspoint\" />\n\n <bean class = \"org.springframework.web.servlet.view.InternalResourceViewResolver\">\n <property name = \"prefix\" value = \"/WEB-INF/jsp/\" />\n <property name = \"suffix\" value = \".jsp\" />\n </bean>\n\n</beans>" }, { "code": null, "e": 112196, "s": 112127, "text": "Following are the important points about HelloWeb-servlet.xml file −" }, { "code": null, "e": 112362, "s": 112196, "text": "The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined with the same name in the global scope." }, { "code": null, "e": 112528, "s": 112362, "text": "The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined with the same name in the global scope." }, { "code": null, "e": 112712, "s": 112528, "text": "The <context:component-scan...> tag will be use to activate Spring MVC annotation scanning capability which allows to make use of annotations like @Controller and @RequestMapping etc." }, { "code": null, "e": 112896, "s": 112712, "text": "The <context:component-scan...> tag will be use to activate Spring MVC annotation scanning capability which allows to make use of annotations like @Controller and @RequestMapping etc." }, { "code": null, "e": 113113, "s": 112896, "text": "The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above defined rule, a logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp ." }, { "code": null, "e": 113330, "s": 113113, "text": "The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above defined rule, a logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp ." }, { "code": null, "e": 113439, "s": 113330, "text": "The following section will show you how to create your actual components, i.e., Controller, Model, and View." }, { "code": null, "e": 113751, "s": 113439, "text": "The DispatcherServlet delegates the request to the controllers to execute the functionality specific to it. The @Controller annotation indicates that a particular class serves the role of a controller. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method." }, { "code": null, "e": 114011, "s": 113751, "text": "@Controller\n@RequestMapping(\"/hello\")\npublic class HelloController { \n @RequestMapping(method = RequestMethod.GET)\n public String printHello(ModelMap model) {\n model.addAttribute(\"message\", \"Hello Spring MVC Framework!\");\n return \"hello\";\n }\n}" }, { "code": null, "e": 114461, "s": 114011, "text": "The @Controller annotation defines the class as a Spring MVC controller. Here, the first usage of @RequestMapping indicates that all handling methods on this controller are relative to the /hello path. Next annotation @RequestMapping(method = RequestMethod.GET) is used to declare the printHello() method as the controller's default service method to handle HTTP GET request. You can define another method to handle any POST request at the same URL." }, { "code": null, "e": 114585, "s": 114461, "text": "You can write the above controller in another form where you can add additional attributes in @RequestMapping as follows −" }, { "code": null, "e": 114836, "s": 114585, "text": "@Controller\npublic class HelloController {\n @RequestMapping(value = \"/hello\", method = RequestMethod.GET)\n public String printHello(ModelMap model) {\n model.addAttribute(\"message\", \"Hello Spring MVC Framework!\");\n return \"hello\";\n }\n}" }, { "code": null, "e": 115076, "s": 114836, "text": "The value attribute indicates the URL to which the handler method is mapped and the method attribute defines the service method to handle HTTP GET request. The following important points are to be noted about the controller defined above −" }, { "code": null, "e": 115208, "s": 115076, "text": "You will define required business logic inside a service method. You can call another method inside this method as per requirement." }, { "code": null, "e": 115340, "s": 115208, "text": "You will define required business logic inside a service method. You can call another method inside this method as per requirement." }, { "code": null, "e": 115605, "s": 115340, "text": "Based on the business logic defined, you will create a model within this method. You can use setter different model attributes and these attributes will be accessed by the view to present the final result. This example creates a model with its attribute \"message\"." }, { "code": null, "e": 115870, "s": 115605, "text": "Based on the business logic defined, you will create a model within this method. You can use setter different model attributes and these attributes will be accessed by the view to present the final result. This example creates a model with its attribute \"message\"." }, { "code": null, "e": 116035, "s": 115870, "text": "A defined service method can return a String, which contains the name of the view to be used to render the model. This example returns \"hello\" as logical view name." }, { "code": null, "e": 116200, "s": 116035, "text": "A defined service method can return a String, which contains the name of the view to be used to render the model. This example returns \"hello\" as logical view name." }, { "code": null, "e": 116467, "s": 116200, "text": "Spring MVC supports many types of views for different presentation technologies. These include - JSPs, HTML, PDF, Excel worksheets, XML, Velocity templates, XSLT, JSON, Atom and RSS feeds, JasperReports, etc. But most commonly we use JSP templates written with JSTL." }, { "code": null, "e": 116530, "s": 116467, "text": "Let us write a simple hello view in /WEB-INF/hello/hello.jsp −" }, { "code": null, "e": 116655, "s": 116530, "text": "<html>\n <head>\n <title>Hello Spring MVC</title>\n </head>\n \n <body>\n <h2>${message}</h2>\n </body>\n</html>" }, { "code": null, "e": 116799, "s": 116655, "text": "Here ${message} is the attribute which we have set up inside the Controller. You can have multiple attributes to be displayed inside your view." }, { "code": null, "e": 116927, "s": 116799, "text": "Based on the above concepts, let us check few important examples which will help you in building your Spring Web Applications −" }, { "code": null, "e": 117011, "s": 116927, "text": "This example will explain how to write a simple Spring Web Hello World application." }, { "code": null, "e": 117161, "s": 117011, "text": "This example will explain how to write a Spring Web application using HTML forms to submit the data to the controller and display a processed result." }, { "code": null, "e": 117234, "s": 117161, "text": "Learn how to use page redirection functionality in Spring MVC Framework." }, { "code": null, "e": 117317, "s": 117234, "text": "Learn how to access static pages along with dynamic pages in Spring MVC Framework." }, { "code": null, "e": 117373, "s": 117317, "text": "Learn how to handle exceptions in Spring MVC Framework." }, { "code": null, "e": 117565, "s": 117373, "text": "This is a very easy-to-use Log4J functionality inside Spring applications. The following example will take you through simple steps to explain the simple integration between Log4J and Spring." }, { "code": null, "e": 117804, "s": 117565, "text": "We assume you already have log4J installed on your machine. If you do not have it then you can download it from https://logging.apache.org/ and simply extract the zipped file in any folder. We will use only log4j-x.y.z.jar in our project." }, { "code": null, "e": 117959, "s": 117804, "text": "Next, let us have a working Eclipse IDE in place and take the following steps to develop a Dynamic Form-based Web Application using Spring Web Framework −" }, { "code": null, "e": 118003, "s": 117959, "text": "Here is the content of HelloWorld.java file" }, { "code": null, "e": 118260, "s": 118003, "text": "package com.tutorialspoint;\n\npublic class HelloWorld {\n private String message;\n \n public void setMessage(String message){\n this.message = message;\n }\n public void getMessage() {\n System.out.println(\"Your Message : \" + message);\n }\n}" }, { "code": null, "e": 118317, "s": 118260, "text": "Following is the content of the second file MainApp.java" }, { "code": null, "e": 118923, "s": 118317, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\nimport org.apache.log4j.Logger;\n\npublic class MainApp {\n static Logger log = Logger.getLogger(MainApp.class.getName());\n \n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n log.info(\"Going to create HelloWord Obj\");\n HelloWorld obj = (HelloWorld) context.getBean(\"helloWorld\");\n obj.getMessage();\n \n log.info(\"Exiting the program\");\n }\n}" }, { "code": null, "e": 119062, "s": 118923, "text": "You can generate debug and error message in a similar way as we have generated info messages. Now let us see the content of Beans.xml file" }, { "code": null, "e": 119513, "s": 119062, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <bean id = \"helloWorld\" class = \"com.tutorialspoint.HelloWorld\">\n <property name = \"message\" value = \"Hello World!\"/>\n </bean>\n\n</beans>" }, { "code": null, "e": 119634, "s": 119513, "text": "Following is the content of log4j.properties which defines the standard rules required for Log4J to produce log messages" }, { "code": null, "e": 120225, "s": 119634, "text": "# Define the root logger with appender file\nlog4j.rootLogger = DEBUG, FILE\n\n# Define the file appender\nlog4j.appender.FILE=org.apache.log4j.FileAppender\n# Set the name of the file\nlog4j.appender.FILE.File=C:\\\\log.out\n\n# Set the immediate flush to true (default)\nlog4j.appender.FILE.ImmediateFlush=true\n\n# Set the threshold to debug mode\nlog4j.appender.FILE.Threshold=debug\n\n# Set the append to false, overwrite\nlog4j.appender.FILE.Append=false\n\n# Define the layout for file appender\nlog4j.appender.FILE.layout=org.apache.log4j.PatternLayout\nlog4j.appender.FILE.layout.conversionPattern=%m%n" }, { "code": null, "e": 120426, "s": 120225, "text": "Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message in Eclipse console −" }, { "code": null, "e": 120455, "s": 120426, "text": "Your Message : Hello World!\n" }, { "code": null, "e": 120583, "s": 120455, "text": "If you check your C:\\\\ drive, then you should find your log file log.out with various log messages, like something as follows −" }, { "code": null, "e": 120729, "s": 120583, "text": "<!-- initialization log messages -->\n\nGoing to create HelloWord Obj\nReturning cached instance of singleton bean 'helloWorld'\nExiting the program\n" }, { "code": null, "e": 121118, "s": 120729, "text": "Alternatively you can use Jakarta Commons Logging (JCL) API to generate a log in your Spring application. JCL can be downloaded from the https://jakarta.apache.org/commons/logging/. The only file we technically need out of this package is the commons-logging-x.y.z.jar file, which needs to be placed in your classpath in a similar way as you had put log4j-x.y.z.jar in the above example." }, { "code": null, "e": 121276, "s": 121118, "text": "To use the logging functionality you need a org.apache.commons.logging.Log object and then you can call one of the following methods as per your requirment −" }, { "code": null, "e": 121298, "s": 121276, "text": "fatal(Object message)" }, { "code": null, "e": 121320, "s": 121298, "text": "error(Object message)" }, { "code": null, "e": 121341, "s": 121320, "text": "warn(Object message)" }, { "code": null, "e": 121362, "s": 121341, "text": "info(Object message)" }, { "code": null, "e": 121384, "s": 121362, "text": "debug(Object message)" }, { "code": null, "e": 121406, "s": 121384, "text": "trace(Object message)" }, { "code": null, "e": 121479, "s": 121406, "text": "Following is the replacement of MainApp.java, which makes use of JCL API" }, { "code": null, "e": 122129, "s": 121479, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\nimport org.apache.commons.logging. Log;\nimport org.apache.commons.logging. LogFactory;\n\npublic class MainApp {\n static Log log = LogFactory.getLog(MainApp.class.getName());\n\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n log.info(\"Going to create HelloWord Obj\");\n HelloWorld obj = (HelloWorld) context.getBean(\"helloWorld\");\n obj.getMessage();\n\n log.info(\"Exiting the program\");\n }\n}" }, { "code": null, "e": 122264, "s": 122129, "text": "You have to make sure that you have included commons-logging-x.y.z.jar file in your project, before compiling and running the program." }, { "code": null, "e": 122454, "s": 122264, "text": "Now keeping the rest of the configuration and content unchanged in the above example, if you compile and run your application, you will get a similar result as what you got using Log4J API." }, { "code": null, "e": 122488, "s": 122454, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 122502, "s": 122488, "text": " Karthikeya T" }, { "code": null, "e": 122535, "s": 122502, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 122550, "s": 122535, "text": " Chaand Sheikh" }, { "code": null, "e": 122585, "s": 122550, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 122597, "s": 122585, "text": " Senol Atac" }, { "code": null, "e": 122632, "s": 122597, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 122644, "s": 122632, "text": " Senol Atac" }, { "code": null, "e": 122679, "s": 122644, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 122691, "s": 122679, "text": " Senol Atac" }, { "code": null, "e": 122724, "s": 122691, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 122736, "s": 122724, "text": " Senol Atac" }, { "code": null, "e": 122743, "s": 122736, "text": " Print" }, { "code": null, "e": 122754, "s": 122743, "text": " Add Notes" } ]
Introduction to Apache POI - GeeksforGeeks
10 Dec, 2021 Apache POI is an open-source java library to create and manipulate various file formats based on Microsoft Office. Using POI, one should be able to perform create, modify and display/read operations on the following file formats. For Example, Java doesn’t provide built-in support for working with excel files, so we need to look for open-source APIs for the job. Apache POI provides Java API for manipulating various file formats based on the Office Open XML (OOXML) standard and OLE2 standard from Microsoft. Apache POI releases are available under the Apache License (V2.0). Some important features of Apache POI are as follows: Apache POI provides stream-based processing, that is suitable for large files and requires less memory. Apache POI is able to handle both XLS and XLSX formats of spreadsheets. Apache POI contains HSSF implementation for Excel ’97(-2007) file format i.e XLS. Apache POI XSSF implementation should be used for Excel 2007 OOXML (.xlsx) file format. Apache POI HSSF and XSSF API provide mechanisms to read, write or modify excel spreadsheets. Apache POI also provides SXSSF API that is an extension of XSSF to work with very large excel sheets. SXSSF API requires less memory and is suitable when working with very large spreadsheets and heap memory is limited. There are two models to choose from – the event model and the user model. The event model requires less memory because the excel file is read in tokens and requires processing. The user model is more object-oriented and easy to use. Apache POI provides excellent support for additional excel features such as working with Formulas, creating cell styles by filling colors and borders, fonts, headers and footers, data validations, images, hyperlinks, etc. Commonly used components of Apache POI HSSF (Horrible Spreadsheet Format): It is used to read and write xls format of MS-Excel files.XSSF (XML Spreadsheet Format): It is used for xlsx file format of MS-Excel.POIFS (Poor Obfuscation Implementation File System): This component is the basic factor of all other POI elements. It is used to read different files explicitly.HWPF (Horrible Word Processor Format): It is used to read and write doc extension files of MS-Word.HSLF (Horrible Slide Layout Format): It is used for read, create, and edit PowerPoint presentations. HSSF (Horrible Spreadsheet Format): It is used to read and write xls format of MS-Excel files. XSSF (XML Spreadsheet Format): It is used for xlsx file format of MS-Excel. POIFS (Poor Obfuscation Implementation File System): This component is the basic factor of all other POI elements. It is used to read different files explicitly. HWPF (Horrible Word Processor Format): It is used to read and write doc extension files of MS-Word. HSLF (Horrible Slide Layout Format): It is used for read, create, and edit PowerPoint presentations. Environment Apache POI runtime dependencies: If you are working on a maven project, you can include the POI dependency in the pom.xml file using the below set of lines of code. <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> Now, in order to add this in eclipse, go to Window -> Show View -> Other -> Maven -> Maven Repositories If you are not using maven, then you can download maven jar files from the POI download page. Include the following jar files minimum to run the sample code: poi-3.10-FINAL.jar poi-ooxml-3.10-FINAL.jar commons-codec-1.5.jar poi-ooxml-schemas-3.10-FINAL.jar xml-apis-1.0.b2.jar stax-api-1.0.1.jar xmlbeans-2.3.0.jar dom4j-1.6.1.jar This article is contributed by Pankaj Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. solankimayank GBlog Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Roadmap to Become a Web Developer in 2022 DSA Sheet by Love Babbar GET and POST requests using Python Top 10 Projects For Beginners To Practice HTML and CSS Skills Working with csv files in Python Roadmap to Become a Web Developer in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? Installation of Node.js on Linux Convert a string to an integer in JavaScript
[ { "code": null, "e": 24558, "s": 24530, "text": "\n10 Dec, 2021" }, { "code": null, "e": 24923, "s": 24558, "text": "Apache POI is an open-source java library to create and manipulate various file formats based on Microsoft Office. Using POI, one should be able to perform create, modify and display/read operations on the following file formats. For Example, Java doesn’t provide built-in support for working with excel files, so we need to look for open-source APIs for the job. " }, { "code": null, "e": 25138, "s": 24923, "text": "Apache POI provides Java API for manipulating various file formats based on the Office Open XML (OOXML) standard and OLE2 standard from Microsoft. Apache POI releases are available under the Apache License (V2.0). " }, { "code": null, "e": 25193, "s": 25138, "text": "Some important features of Apache POI are as follows: " }, { "code": null, "e": 25297, "s": 25193, "text": "Apache POI provides stream-based processing, that is suitable for large files and requires less memory." }, { "code": null, "e": 25369, "s": 25297, "text": "Apache POI is able to handle both XLS and XLSX formats of spreadsheets." }, { "code": null, "e": 25451, "s": 25369, "text": "Apache POI contains HSSF implementation for Excel ’97(-2007) file format i.e XLS." }, { "code": null, "e": 25539, "s": 25451, "text": "Apache POI XSSF implementation should be used for Excel 2007 OOXML (.xlsx) file format." }, { "code": null, "e": 25632, "s": 25539, "text": "Apache POI HSSF and XSSF API provide mechanisms to read, write or modify excel spreadsheets." }, { "code": null, "e": 25734, "s": 25632, "text": "Apache POI also provides SXSSF API that is an extension of XSSF to work with very large excel sheets." }, { "code": null, "e": 25851, "s": 25734, "text": "SXSSF API requires less memory and is suitable when working with very large spreadsheets and heap memory is limited." }, { "code": null, "e": 26084, "s": 25851, "text": "There are two models to choose from – the event model and the user model. The event model requires less memory because the excel file is read in tokens and requires processing. The user model is more object-oriented and easy to use." }, { "code": null, "e": 26306, "s": 26084, "text": "Apache POI provides excellent support for additional excel features such as working with Formulas, creating cell styles by filling colors and borders, fonts, headers and footers, data validations, images, hyperlinks, etc." }, { "code": null, "e": 26345, "s": 26306, "text": "Commonly used components of Apache POI" }, { "code": null, "e": 26875, "s": 26345, "text": "HSSF (Horrible Spreadsheet Format): It is used to read and write xls format of MS-Excel files.XSSF (XML Spreadsheet Format): It is used for xlsx file format of MS-Excel.POIFS (Poor Obfuscation Implementation File System): This component is the basic factor of all other POI elements. It is used to read different files explicitly.HWPF (Horrible Word Processor Format): It is used to read and write doc extension files of MS-Word.HSLF (Horrible Slide Layout Format): It is used for read, create, and edit PowerPoint presentations." }, { "code": null, "e": 26970, "s": 26875, "text": "HSSF (Horrible Spreadsheet Format): It is used to read and write xls format of MS-Excel files." }, { "code": null, "e": 27046, "s": 26970, "text": "XSSF (XML Spreadsheet Format): It is used for xlsx file format of MS-Excel." }, { "code": null, "e": 27208, "s": 27046, "text": "POIFS (Poor Obfuscation Implementation File System): This component is the basic factor of all other POI elements. It is used to read different files explicitly." }, { "code": null, "e": 27308, "s": 27208, "text": "HWPF (Horrible Word Processor Format): It is used to read and write doc extension files of MS-Word." }, { "code": null, "e": 27409, "s": 27308, "text": "HSLF (Horrible Slide Layout Format): It is used for read, create, and edit PowerPoint presentations." }, { "code": null, "e": 27421, "s": 27409, "text": "Environment" }, { "code": null, "e": 27586, "s": 27421, "text": "Apache POI runtime dependencies: If you are working on a maven project, you can include the POI dependency in the pom.xml file using the below set of lines of code." }, { "code": null, "e": 27716, "s": 27586, "text": "<dependency> \n <groupId>org.apache.poi</groupId> \n <artifactId>poi</artifactId> \n <version>3.9</version> \n</dependency> " }, { "code": null, "e": 27761, "s": 27716, "text": "Now, in order to add this in eclipse, go to " }, { "code": null, "e": 27821, "s": 27761, "text": "Window -> Show View -> Other -> Maven -> Maven Repositories" }, { "code": null, "e": 27980, "s": 27821, "text": "If you are not using maven, then you can download maven jar files from the POI download page. Include the following jar files minimum to run the sample code: " }, { "code": null, "e": 27999, "s": 27980, "text": "poi-3.10-FINAL.jar" }, { "code": null, "e": 28024, "s": 27999, "text": "poi-ooxml-3.10-FINAL.jar" }, { "code": null, "e": 28046, "s": 28024, "text": "commons-codec-1.5.jar" }, { "code": null, "e": 28079, "s": 28046, "text": "poi-ooxml-schemas-3.10-FINAL.jar" }, { "code": null, "e": 28099, "s": 28079, "text": "xml-apis-1.0.b2.jar" }, { "code": null, "e": 28118, "s": 28099, "text": "stax-api-1.0.1.jar" }, { "code": null, "e": 28137, "s": 28118, "text": "xmlbeans-2.3.0.jar" }, { "code": null, "e": 28153, "s": 28137, "text": "dom4j-1.6.1.jar" }, { "code": null, "e": 28574, "s": 28153, "text": "This article is contributed by Pankaj Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28588, "s": 28574, "text": "solankimayank" }, { "code": null, "e": 28594, "s": 28588, "text": "GBlog" }, { "code": null, "e": 28611, "s": 28594, "text": "Web Technologies" }, { "code": null, "e": 28709, "s": 28611, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28751, "s": 28709, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28776, "s": 28751, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 28811, "s": 28776, "text": "GET and POST requests using Python" }, { "code": null, "e": 28873, "s": 28811, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28906, "s": 28873, "text": "Working with csv files in Python" }, { "code": null, "e": 28948, "s": 28906, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29010, "s": 28948, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29053, "s": 29010, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29086, "s": 29053, "text": "Installation of Node.js on Linux" } ]
Program to find largest rectangle area under histogram in python
Suppose we have a list of numbers representing heights of bars in a histogram. We have to find area of the largest rectangle that can be formed under the bars. So, if the input is like nums = [3, 2, 5, 7] then the output will be 10 To solve this, we will follow these steps − stk := a stack and initially insert -1 into it insert 0 at the end of heights ans := 0 for i in range 0 to size of heights, dowhile heights[i] < heights[top of stk], doh := heights[top of stk] and pop from stkw := i - top of stk - 1ans := maximum of ans and (h * w)push i into stk while heights[i] < heights[top of stk], doh := heights[top of stk] and pop from stkw := i - top of stk - 1ans := maximum of ans and (h * w) h := heights[top of stk] and pop from stk w := i - top of stk - 1 ans := maximum of ans and (h * w) push i into stk return ans Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, heights): stk = [-1] heights.append(0) ans = 0 for i in range(len(heights)): while heights[i] < heights[stk[-1]]: h = heights[stk.pop()] w = i - stk[-1] - 1 ans = max(ans, h * w) stk.append(i) return ans ob = Solution() nums = [3, 2, 5, 7] print(ob.solve(nums)) [3, 2, 5, 7] 10
[ { "code": null, "e": 1222, "s": 1062, "text": "Suppose we have a list of numbers representing heights of bars in a histogram. We have to find area of the largest rectangle that can be formed under the bars." }, { "code": null, "e": 1267, "s": 1222, "text": "So, if the input is like nums = [3, 2, 5, 7]" }, { "code": null, "e": 1294, "s": 1267, "text": "then the output will be 10" }, { "code": null, "e": 1338, "s": 1294, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1385, "s": 1338, "text": "stk := a stack and initially insert -1 into it" }, { "code": null, "e": 1416, "s": 1385, "text": "insert 0 at the end of heights" }, { "code": null, "e": 1425, "s": 1416, "text": "ans := 0" }, { "code": null, "e": 1619, "s": 1425, "text": "for i in range 0 to size of heights, dowhile heights[i] < heights[top of stk], doh := heights[top of stk] and pop from stkw := i - top of stk - 1ans := maximum of ans and (h * w)push i into stk" }, { "code": null, "e": 1759, "s": 1619, "text": "while heights[i] < heights[top of stk], doh := heights[top of stk] and pop from stkw := i - top of stk - 1ans := maximum of ans and (h * w)" }, { "code": null, "e": 1801, "s": 1759, "text": "h := heights[top of stk] and pop from stk" }, { "code": null, "e": 1825, "s": 1801, "text": "w := i - top of stk - 1" }, { "code": null, "e": 1859, "s": 1825, "text": "ans := maximum of ans and (h * w)" }, { "code": null, "e": 1875, "s": 1859, "text": "push i into stk" }, { "code": null, "e": 1886, "s": 1875, "text": "return ans" }, { "code": null, "e": 1956, "s": 1886, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1966, "s": 1956, "text": "Live Demo" }, { "code": null, "e": 2348, "s": 1966, "text": "class Solution:\n def solve(self, heights):\n stk = [-1]\n heights.append(0)\n ans = 0\n for i in range(len(heights)):\n while heights[i] < heights[stk[-1]]:\n h = heights[stk.pop()]\n w = i - stk[-1] - 1\n ans = max(ans, h * w)\n stk.append(i)\n return ans\n\nob = Solution()\nnums = [3, 2, 5, 7]\nprint(ob.solve(nums))" }, { "code": null, "e": 2361, "s": 2348, "text": "[3, 2, 5, 7]" }, { "code": null, "e": 2364, "s": 2361, "text": "10" } ]
Print nodes of linked list at given indexes - GeeksforGeeks
15 Sep, 2021 Given a singly linked list which is sorted in ascending order and another singly linked list which is unsorted. The task is to print the elements of the second linked list according to the position pointed out by the data in the nodes of the first linked list. For example, if the first linked list is 1->2->5 then you have to print the 1st, 2nd and 5th elements of the second linked list. Examples: Input: l1 = 1->2->5 l2 = 1->8->7->6->2->9->10 Output : 1->8->2 Elements in l1 are 1, 2 and 5. Therefore, print 1st, 2nd and 5th elements of l2, Which are 1, 8 and 2. Input: l1 = 2->5 l2 = 7->5->3->2->8 Output: 5->8 Take two pointers to traverse the two linked lists using two nested loops. The outer loop points to the elements of the first list and the inner loop point to the elements of the second list respectively. In the first iteration of outer loop, the pointer to the head of the first linked list points to its root node. We traverse the second linked list until we reach the position pointed out by the node’s data in the first linked list. Once the required position is reached, print the data of the second list and repeat this process again until we reach the end of the first linked list. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to print second linked list// according to data in the first linked list#include <iostream>using namespace std; // Linked List Nodestruct Node { int data; struct Node* next;}; /* Function to insert a node at the beginning */void push(struct Node** head_ref, int new_data){ Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Function to print the second list according// to the positions referred by the 1st listvoid printSecondList(Node* l1, Node* l2){ struct Node* temp = l1; struct Node* temp1 = l2; // While first linked list is not null. while (temp != NULL) { int i = 1; // While second linked list is not equal // to the data in the node of the // first linked list. while (i < temp->data) { // Keep incrementing second list temp1 = temp1->next; i++; } // Print the node at position in second list // pointed by current element of first list cout << temp1->data << " "; // Increment first linked list temp = temp->next; // Set temp1 to the start of the // second linked list temp1 = l2; }} // Driver Codeint main(){ struct Node *l1 = NULL, *l2 = NULL; // Creating 1st list // 2 -> 5 push(&l1, 5); push(&l1, 2); // Creating 2nd list // 4 -> 5 -> 6 -> 7 -> 8 push(&l2, 8); push(&l2, 7); push(&l2, 6); push(&l2, 5); push(&l2, 4); printSecondList(l1, l2); return 0;} // Java program to print second linked list// according to data in the first linked listclass GFG{ // Linked List Nodestatic class Node{ int data; Node next;}; /* Function to insert a node at the beginning */static Node push( Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} // Function to print the second list according// to the positions referred by the 1st liststatic void printSecondList(Node l1, Node l2){ Node temp = l1; Node temp1 = l2; // While first linked list is not null. while (temp != null) { int i = 1; // While second linked list is not equal // to the data in the node of the // first linked list. while (i < temp.data) { // Keep incrementing second list temp1 = temp1.next; i++; } // Print the node at position in second list // pointed by current element of first list System.out.print( temp1.data + " "); // Increment first linked list temp = temp.next; // Set temp1 to the start of the // second linked list temp1 = l2; }} // Driver Codepublic static void main(String args[]){ Node l1 = null, l2 = null; // Creating 1st list // 2 . 5 l1 = push(l1, 5); l1 = push(l1, 2); // Creating 2nd list // 4 . 5 . 6 . 7 . 8 l2 = push(l2, 8); l2 = push(l2, 7); l2 = push(l2, 6); l2 = push(l2, 5); l2 = push(l2, 4); printSecondList(l1, l2);}} // This code is contributed by Arnab Kundu # Python3 program to prsecond linked list# according to data in the first linked list # Linked List Nodeclass new_Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None ''' Function to insert a node at the beginning '''def push(head_ref, new_data): new_node = new_Node(new_data) new_node.next = head_ref head_ref = new_node return head_ref # Function to print second list according# to the positions referred by the 1st listdef printSecondList(l1,l2): temp = l1 temp1 = l2 # While first linked list is not None. while (temp != None): i = 1 # While second linked list is not equal # to the data in the node of the # first linked list. while (i < temp.data): # Keep incrementing second list temp1 = temp1.next i += 1 # Print node at position in second list # pointed by current element of first list print(temp1.data,end=" ") # Increment first linked list temp = temp.next # Set temp1 to the start of the # second linked list temp1 = l2 # Driver Codel1 = Nonel2 = None # Creating 1st list# 2 . 5l1 = push(l1, 5)l1 = push(l1, 2) # Creating 2nd list# 4 . 5 . 6 . 7 . 8l2 = push(l2, 8)l2 = push(l2, 7)l2 = push(l2, 6)l2 = push(l2, 5)l2 = push(l2, 4) printSecondList(l1, l2) # This code is contributed by shubhamsingh10 // C# program to print second linked list// according to data in the first linked listusing System; class GFG{ // Linked List Nodepublic class Node{ public int data; public Node next;}; /* Function to insert a node at the beginning */static Node push( Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} // Function to print the second list according// to the positions referred by the 1st liststatic void printSecondList(Node l1, Node l2){ Node temp = l1; Node temp1 = l2; // While first linked list is not null. while (temp != null) { int i = 1; // While second linked list is not equal // to the data in the node of the // first linked list. while (i < temp.data) { // Keep incrementing second list temp1 = temp1.next; i++; } // Print the node at position in second list // pointed by current element of first list Console.Write( temp1.data + " "); // Increment first linked list temp = temp.next; // Set temp1 to the start of the // second linked list temp1 = l2; }} // Driver Codepublic static void Main(){ Node l1 = null, l2 = null; // Creating 1st list // 2 . 5 l1 = push(l1, 5); l1 = push(l1, 2); // Creating 2nd list // 4 . 5 . 6 . 7 . 8 l2 = push(l2, 8); l2 = push(l2, 7); l2 = push(l2, 6); l2 = push(l2, 5); l2 = push(l2, 4); printSecondList(l1, l2);}} // This code has been contributed by 29AjayKumar <script> // JavaScript program to print second linked list// according to data in the first linked list class Node{ constructor() { this.data=0; this.next=null; }} /* Function to insert a node at the beginning */function push(head_ref, new_data){ let new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} // Function to print the second list according// to the positions referred by the 1st listfunction printSecondList(l1,l2){ let temp = l1; let temp1 = l2; // While first linked list is not null. while (temp != null) { let i = 1; // While second linked list is not equal // to the data in the node of the // first linked list. while (i < temp.data) { // Keep incrementing second list temp1 = temp1.next; i++; } // Print the node at position in second list // pointed by current element of first list document.write( temp1.data + " "); // Increment first linked list temp = temp.next; // Set temp1 to the start of the // second linked list temp1 = l2; }} // Driver Codelet l1 = null, l2 = null; // Creating 1st list// 2 . 5l1 = push(l1, 5);l1 = push(l1, 2); // Creating 2nd list// 4 . 5 . 6 . 7 . 8l2 = push(l2, 8);l2 = push(l2, 7);l2 = push(l2, 6);l2 = push(l2, 5);l2 = push(l2, 4); printSecondList(l1, l2); // This code is contributed by avanitrachhadiya2155 </script> 5 8 andrew1234 29AjayKumar SHUBHAMSINGH10 Akanksha_Rai avanitrachhadiya2155 khushboogoyal499 Traversal Linked List Linked List Traversal Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Delete a node in a Doubly Linked List Given a linked list which is sorted, how will you insert in sorted way Insert a node at a specific position in a linked list Circular Linked List | Set 2 (Traversal) Swap nodes in a linked list without swapping data Program to implement Singly Linked List in C++ using class Priority Queue using Linked List Circular Singly Linked List | Insertion Real-time application of Data Structures Insertion Sort for Singly Linked List
[ { "code": null, "e": 24567, "s": 24539, "text": "\n15 Sep, 2021" }, { "code": null, "e": 24957, "s": 24567, "text": "Given a singly linked list which is sorted in ascending order and another singly linked list which is unsorted. The task is to print the elements of the second linked list according to the position pointed out by the data in the nodes of the first linked list. For example, if the first linked list is 1->2->5 then you have to print the 1st, 2nd and 5th elements of the second linked list." }, { "code": null, "e": 24968, "s": 24957, "text": "Examples: " }, { "code": null, "e": 25203, "s": 24968, "text": "Input: l1 = 1->2->5\n l2 = 1->8->7->6->2->9->10\nOutput : 1->8->2\nElements in l1 are 1, 2 and 5. \nTherefore, print 1st, 2nd and 5th elements of l2,\nWhich are 1, 8 and 2.\n\nInput: l1 = 2->5 \n l2 = 7->5->3->2->8\nOutput: 5->8 \n " }, { "code": null, "e": 25793, "s": 25203, "text": "Take two pointers to traverse the two linked lists using two nested loops. The outer loop points to the elements of the first list and the inner loop point to the elements of the second list respectively. In the first iteration of outer loop, the pointer to the head of the first linked list points to its root node. We traverse the second linked list until we reach the position pointed out by the node’s data in the first linked list. Once the required position is reached, print the data of the second list and repeat this process again until we reach the end of the first linked list. " }, { "code": null, "e": 25846, "s": 25793, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25850, "s": 25846, "text": "C++" }, { "code": null, "e": 25855, "s": 25850, "text": "Java" }, { "code": null, "e": 25863, "s": 25855, "text": "Python3" }, { "code": null, "e": 25866, "s": 25863, "text": "C#" }, { "code": null, "e": 25877, "s": 25866, "text": "Javascript" }, { "code": "// C++ program to print second linked list// according to data in the first linked list#include <iostream>using namespace std; // Linked List Nodestruct Node { int data; struct Node* next;}; /* Function to insert a node at the beginning */void push(struct Node** head_ref, int new_data){ Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Function to print the second list according// to the positions referred by the 1st listvoid printSecondList(Node* l1, Node* l2){ struct Node* temp = l1; struct Node* temp1 = l2; // While first linked list is not null. while (temp != NULL) { int i = 1; // While second linked list is not equal // to the data in the node of the // first linked list. while (i < temp->data) { // Keep incrementing second list temp1 = temp1->next; i++; } // Print the node at position in second list // pointed by current element of first list cout << temp1->data << \" \"; // Increment first linked list temp = temp->next; // Set temp1 to the start of the // second linked list temp1 = l2; }} // Driver Codeint main(){ struct Node *l1 = NULL, *l2 = NULL; // Creating 1st list // 2 -> 5 push(&l1, 5); push(&l1, 2); // Creating 2nd list // 4 -> 5 -> 6 -> 7 -> 8 push(&l2, 8); push(&l2, 7); push(&l2, 6); push(&l2, 5); push(&l2, 4); printSecondList(l1, l2); return 0;}", "e": 27438, "s": 25877, "text": null }, { "code": "// Java program to print second linked list// according to data in the first linked listclass GFG{ // Linked List Nodestatic class Node{ int data; Node next;}; /* Function to insert a node at the beginning */static Node push( Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} // Function to print the second list according// to the positions referred by the 1st liststatic void printSecondList(Node l1, Node l2){ Node temp = l1; Node temp1 = l2; // While first linked list is not null. while (temp != null) { int i = 1; // While second linked list is not equal // to the data in the node of the // first linked list. while (i < temp.data) { // Keep incrementing second list temp1 = temp1.next; i++; } // Print the node at position in second list // pointed by current element of first list System.out.print( temp1.data + \" \"); // Increment first linked list temp = temp.next; // Set temp1 to the start of the // second linked list temp1 = l2; }} // Driver Codepublic static void main(String args[]){ Node l1 = null, l2 = null; // Creating 1st list // 2 . 5 l1 = push(l1, 5); l1 = push(l1, 2); // Creating 2nd list // 4 . 5 . 6 . 7 . 8 l2 = push(l2, 8); l2 = push(l2, 7); l2 = push(l2, 6); l2 = push(l2, 5); l2 = push(l2, 4); printSecondList(l1, l2);}} // This code is contributed by Arnab Kundu", "e": 29065, "s": 27438, "text": null }, { "code": "# Python3 program to prsecond linked list# according to data in the first linked list # Linked List Nodeclass new_Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None ''' Function to insert a node at the beginning '''def push(head_ref, new_data): new_node = new_Node(new_data) new_node.next = head_ref head_ref = new_node return head_ref # Function to print second list according# to the positions referred by the 1st listdef printSecondList(l1,l2): temp = l1 temp1 = l2 # While first linked list is not None. while (temp != None): i = 1 # While second linked list is not equal # to the data in the node of the # first linked list. while (i < temp.data): # Keep incrementing second list temp1 = temp1.next i += 1 # Print node at position in second list # pointed by current element of first list print(temp1.data,end=\" \") # Increment first linked list temp = temp.next # Set temp1 to the start of the # second linked list temp1 = l2 # Driver Codel1 = Nonel2 = None # Creating 1st list# 2 . 5l1 = push(l1, 5)l1 = push(l1, 2) # Creating 2nd list# 4 . 5 . 6 . 7 . 8l2 = push(l2, 8)l2 = push(l2, 7)l2 = push(l2, 6)l2 = push(l2, 5)l2 = push(l2, 4) printSecondList(l1, l2) # This code is contributed by shubhamsingh10", "e": 30565, "s": 29065, "text": null }, { "code": "// C# program to print second linked list// according to data in the first linked listusing System; class GFG{ // Linked List Nodepublic class Node{ public int data; public Node next;}; /* Function to insert a node at the beginning */static Node push( Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} // Function to print the second list according// to the positions referred by the 1st liststatic void printSecondList(Node l1, Node l2){ Node temp = l1; Node temp1 = l2; // While first linked list is not null. while (temp != null) { int i = 1; // While second linked list is not equal // to the data in the node of the // first linked list. while (i < temp.data) { // Keep incrementing second list temp1 = temp1.next; i++; } // Print the node at position in second list // pointed by current element of first list Console.Write( temp1.data + \" \"); // Increment first linked list temp = temp.next; // Set temp1 to the start of the // second linked list temp1 = l2; }} // Driver Codepublic static void Main(){ Node l1 = null, l2 = null; // Creating 1st list // 2 . 5 l1 = push(l1, 5); l1 = push(l1, 2); // Creating 2nd list // 4 . 5 . 6 . 7 . 8 l2 = push(l2, 8); l2 = push(l2, 7); l2 = push(l2, 6); l2 = push(l2, 5); l2 = push(l2, 4); printSecondList(l1, l2);}} // This code has been contributed by 29AjayKumar", "e": 32208, "s": 30565, "text": null }, { "code": "<script> // JavaScript program to print second linked list// according to data in the first linked list class Node{ constructor() { this.data=0; this.next=null; }} /* Function to insert a node at the beginning */function push(head_ref, new_data){ let new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} // Function to print the second list according// to the positions referred by the 1st listfunction printSecondList(l1,l2){ let temp = l1; let temp1 = l2; // While first linked list is not null. while (temp != null) { let i = 1; // While second linked list is not equal // to the data in the node of the // first linked list. while (i < temp.data) { // Keep incrementing second list temp1 = temp1.next; i++; } // Print the node at position in second list // pointed by current element of first list document.write( temp1.data + \" \"); // Increment first linked list temp = temp.next; // Set temp1 to the start of the // second linked list temp1 = l2; }} // Driver Codelet l1 = null, l2 = null; // Creating 1st list// 2 . 5l1 = push(l1, 5);l1 = push(l1, 2); // Creating 2nd list// 4 . 5 . 6 . 7 . 8l2 = push(l2, 8);l2 = push(l2, 7);l2 = push(l2, 6);l2 = push(l2, 5);l2 = push(l2, 4); printSecondList(l1, l2); // This code is contributed by avanitrachhadiya2155 </script>", "e": 33759, "s": 32208, "text": null }, { "code": null, "e": 33763, "s": 33759, "text": "5 8" }, { "code": null, "e": 33776, "s": 33765, "text": "andrew1234" }, { "code": null, "e": 33788, "s": 33776, "text": "29AjayKumar" }, { "code": null, "e": 33803, "s": 33788, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 33816, "s": 33803, "text": "Akanksha_Rai" }, { "code": null, "e": 33837, "s": 33816, "text": "avanitrachhadiya2155" }, { "code": null, "e": 33854, "s": 33837, "text": "khushboogoyal499" }, { "code": null, "e": 33864, "s": 33854, "text": "Traversal" }, { "code": null, "e": 33876, "s": 33864, "text": "Linked List" }, { "code": null, "e": 33888, "s": 33876, "text": "Linked List" }, { "code": null, "e": 33898, "s": 33888, "text": "Traversal" }, { "code": null, "e": 33996, "s": 33898, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34005, "s": 33996, "text": "Comments" }, { "code": null, "e": 34018, "s": 34005, "text": "Old Comments" }, { "code": null, "e": 34056, "s": 34018, "text": "Delete a node in a Doubly Linked List" }, { "code": null, "e": 34127, "s": 34056, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 34181, "s": 34127, "text": "Insert a node at a specific position in a linked list" }, { "code": null, "e": 34222, "s": 34181, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 34272, "s": 34222, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 34331, "s": 34272, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 34364, "s": 34331, "text": "Priority Queue using Linked List" }, { "code": null, "e": 34404, "s": 34364, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 34445, "s": 34404, "text": "Real-time application of Data Structures" } ]
Data Transformation. How to apply modern Machine Learning on... | by Ke Gui | Towards Data Science
Warning: There is no magical formula or Holy Grail here, though a new world might open the door for you. Identifying OutliersIdentifying Outliers — Part TwoIdentifying Outliers — Part ThreeStylized FactsFeature Engineering & Feature SelectionData TransformationFractionally Differentiated FeaturesData LabellingMeta-labeling and Stacking Identifying Outliers Identifying Outliers — Part Two Identifying Outliers — Part Three Stylized Facts Feature Engineering & Feature Selection Data Transformation Fractionally Differentiated Features Data Labelling Meta-labeling and Stacking In the previews article, I briefly introduced the Volume Spread Analysis(VSA). After we did feature-engineering and feature-selection, there were two things I noticed immediately, the first one was that there were outliers in the dataset and the second issue was the distribution were no way close to normal. By using the method described here, here and here, I removed most of the outliers. Now is the time to face the bigger problem, the normality. There are many ways to transfer the data. One of the well-known examples is the one-hot encoding, even better one is word embedding in natural language processing (NLP). Considering one of the advantages of using deep learning is that it completely automates what used to be the most crucial step in a machine-learning workflow: feature engineering. Before we get into the deep learning in the later articles, let’s have a look at some simple ways to transfer data to see if we can make it closer to normal distribution. In this article, I would like to try a few things. The first one is to transfer all the features to a simple percentage change. The second one is to do a Percentile Ranking. In the end, I will show you what happens if I only pick the sign of all the data. Methods like Z-score, which are standard pre-processing in deep learning, I would rather leave it for now. For consistency, in all the 📈Python for finance series, I will try to reuse the same data as much as I can. More details about data preparation can be found here, here and here or you can refer back to my previous article. Or if you like, you can ignore all the code below and use whatever clean data you have at hand, it won’t affect the things we are going to do together. #import all the librariesimport pandas as pdimport numpy as npimport seaborn as sns import yfinance as yf #the stock data from Yahoo Financeimport matplotlib.pyplot as plt #set the parameters for plottingplt.style.use('seaborn')plt.rcParams['figure.dpi'] = 300#define a function to get datadef get_data(symbols, begin_date=None,end_date=None): df = yf.download('AAPL', start = '2000-01-01', auto_adjust=True,#only download adjusted data end= '2010-12-31') #my convention: always lowercase df.columns = ['open','high','low', 'close','volume'] return dfprices = get_data('AAPL', '2000-01-01', '2010-12-31')#create some featuresdef create_HLCV(i):#as we don't care open that much, that leaves volume, #high,low and close df = pd.DataFrame(index=prices.index) df[f'high_{i}D'] = prices.high.rolling(i).max() df[f'low_{i}D'] = prices.low.rolling(i).min() df[f'close_{i}D'] = prices.close.rolling(i).\ apply(lambda x:x[-1]) # close_2D = close as rolling backwards means today is # literly the last day of the rolling window. df[f'volume_{i}D'] = prices.volume.rolling(i).sum() return df# create features at different rolling windowsdef create_features_and_outcomes(i): df = create_HLCV(i) high = df[f'high_{i}D'] low = df[f'low_{i}D'] close = df[f'close_{i}D'] volume = df[f'volume_{i}D'] features = pd.DataFrame(index=prices.index) outcomes = pd.DataFrame(index=prices.index) #as we already considered the different time span, #here only day of simple percentage change used. features[f'volume_{i}D'] = volume.pct_change() features[f'price_spread_{i}D'] = (high - low).pct_change() #aligne the close location with the stock price change features[f'close_loc_{i}D'] = ((close - low) / \ (high - low)).pct_change() #the future outcome is what we are going to predict outcomes[f'close_change_{i}D'] = close.pct_change(-i) return features, outcomesdef create_bunch_of_features_and_outcomes(): ''' the timespan that i would like to explore are 1, 2, 3 days and 1 week, 1 month, 2 month, 3 month which roughly are [1,2,3,5,20,40,60] ''' days = [1,2,3,5,20,40,60] bunch_of_features = pd.DataFrame(index=prices.index) bunch_of_outcomes = pd.DataFrame(index=prices.index) for day in days: f,o = create_features_and_outcomes(day) bunch_of_features = bunch_of_features.join(f) bunch_of_outcomes = bunch_of_outcomes .join(o) return bunch_of_features, bunch_of_outcomesbunch_of_features, bunch_of_outcomes = create_bunch_of_features_and_outcomes()#define the method to identify outliersdef get_outliers(df, i=4): #i is number of sigma, which define the boundary along mean outliers = pd.DataFrame() stats = df.describe() for col in df.columns: mu = stats.loc['mean', col] sigma = stats.loc['std', col] condition = (df[col] > mu + sigma * i) | \ (df[col] < mu - sigma * i) outliers[f'{col}_outliers'] = df[col][condition] return outliers#remove all the outliersfeatures_outcomes = bunch_of_features.join(bunch_of_outcomes)outliers = get_outliers(features_outcomes, i=1)features_outcomes_rmv_outliers = features_outcomes.drop(index = outliers.index).dropna()features = features_outcomes_rmv_outliers[bunch_of_features.columns]outcomes = features_outcomes_rmv_outliers[bunch_of_outcomes.columns]features.info(), outcomes.info() In the end, we will have the basic four features based on Volume Spread Analysis (VSA) at different time scale listed below, namely, 1 day, 2 days, 3 days, a week, a month, 2 months and 3 months. Volume: pretty straight forward Range/Spread: Difference between high and close Closing Price Relative to Range: Is the closing price near the top or the bottom of the price bar? The change of stock price: pretty straight forward I know that’s a whole lot of codes above. We have all the features transformed into a simple percentage change through the function below. def create_features_and_outcomes(i): df = create_HLCV(i) high = df[f'high_{i}D'] low = df[f'low_{i}D'] close = df[f'close_{i}D'] volume = df[f'volume_{i}D'] features = pd.DataFrame(index=prices.index) outcomes = pd.DataFrame(index=prices.index) #as we already considered the different time span, #here only 1 day of simple percentage change used. features[f'volume_{i}D'] = volume.pct_change() features[f'price_spread_{i}D'] = (high - low).pct_change() #aligne the close location with the stock price change features[f'close_loc_{i}D'] = ((close - low) / \ (high - low)).pct_change()#the future outcome is what we are going to predict outcomes[f'close_change_{i}D'] = close.pct_change(-i) return features, outcomes Now, let’s have a look at their correlations using cluster map. Seaborn’s clustermap() hierarchical clustering algorithm shows a nice way to group the most closely related features. corr_features = features.corr().sort_index()sns.clustermap(corr_features, cmap='coolwarm', linewidth=1); Based on this cluster map, to minimize the amount of feature overlap in selected features, I will remove those features that are paired with other features closely and having less correlation with the outcome targets. From the cluster map above, it is easy to spot that features on [40D, 60D] and [2D, 3D] are paired together. To see how those features are related to the outcomes, let’s have a look at how the outcomes are correlated first. corr_outcomes = outcomes.corr()sns.clustermap(corr_outcomes, cmap='coolwarm', linewidth=2); From top to bottom, 20 days, 40 days and 60 days price percentage change are grouped together, so as the 2 days, 3 days and 5 days. Whereas, 1-day stock price percentage change is relatively independent of those two groups. If we pick the next day price percentage change as the outcome target, let’s see how those features are related to it. corr_features_outcomes = features.corrwith(outcomes. \ close_change_1D).sort_values()corr_features_outcomes.dropna(inplace=True)corr_features_outcomes.plot(kind='barh',title = 'Strength of Correlation'); The correlation coefficients are way too small to make a solid conclusion. I will expect that the most recent data have a stronger correlation, but that is not the case here. How about the pair plot? We only pick those features based on a 1-day time scale as a demonstration. At the meantime, I transferred the close_change_1D to sign base on it’s a negative or positive number to add extra dimensionality to the plots. selected_features_1D_list = ['volume_1D', 'price_spread_1D', 'close_loc_1D', 'close_change_1D']features_outcomes_rmv_outliers['sign_of_close'] = features_outcomes_rmv_outliers['close_change_1D']. \ apply(np.sign)sns.pairplot(features_outcomes_rmv_outliers, vars=selected_features_1D_list, diag_kind='kde', palette='husl', hue='sign_of_close', markers = ['*', '<', '+'], plot_kws={'alpha':0.3}); The pair plot builds on two basic figures, the histogram and the scatter plot. The histogram on the diagonal allows us to see the distribution of a single variable while the scatter plots on the upper and lower triangles show the relationship (or lack thereof) between two variables. From the plots above, we can see that price spreads are getting wider with high volume. Most of the price change locate at a narrow price spread, in another word, wider spread doesn’t always come with bigger price fluctuation. Either low volume or high volume can cause price change at almost all scale. And we can apply all those conclusions to both up days and down days. you can also use the close location of bars to add more dimensionality, simply apply features[‘sign_of_close_loc’] = np.where( \ features[‘close_loc_1D’] > 0.5, \ 1, -1) to see how many bars’ close location above the 0.5 or below 0.5. One thing that I don’t really like in the pair plot is all the plots with the close_loc_1D condensed, looks like the outliers still there, even I know I used one standard deviation as the boundary which is a very low threshold and 338 outliers were removed. I realize that because the location of close is already a percentage change, adding another percentage change on top doesn’t make much sense. Let’s change it. def create_features_and_outcomes(i): df = create_HLCV(i) high = df[f'high_{i}D'] low = df[f'low_{i}D'] close = df[f'close_{i}D'] volume = df[f'volume_{i}D'] features = pd.DataFrame(index=prices.index) outcomes = pd.DataFrame(index=prices.index) #as we already considered the different time span, #simple percentage change of 1 day used here. features[f'volume_{i}D'] = volume.pct_change() features[f'price_spread_{i}D'] = (high - low).pct_change() #remove pct_change() here features[f'close_loc_{i}D'] = ((close - low) / (high - low)) #predict the future with -i outcomes[f'close_change_{i}D'] = close.pct_change(-i) return features, outcomes With pct_change() removed, let’s see how the cluster map looks like now. corr_features = features.corr().sort_index()sns.clustermap(corr_features, cmap='coolwarm', linewidth=1); The cluster map makes more sense now. All four basic features have pretty much the same pattern. [40D, 60D], [2D, 3D] are paired together. and in terms of the features correlations with the outcome. corr_features_outcomes.plot(kind='barh',title = 'Strength of Correlation'); The longer-range time scale features have weak correlations with stock price return, while the more recent events have more effects on the price returns. By removing pct_change() of the close_loc_1D, the biggest difference is laid on the pairplot(). Finally, the close_loc_1D variable plots at the right range. This illustrates that we should be careful with over-engineering. It may lead to a totally unexpected way. According to Wikipedia, the percentile rank is “The percentile rank of a score is the percentage of scores in its frequency distribution that are equal to or lower than it. For example, a test score that is greater than 75% of the scores of people taking the test is said to be at the 75th percentile, where 75 is the percentile rank.” The below example returns the percentile rank (from 0.00 to 1.00) of traded volume for each value as compared to a trailing 60-day period. roll_rank = lambda x: pd.Series(x).rank(pct=True)[-1]# you only pick the first value [0]# of the 60 windows rank if you rolling forward.# if you rolling backward, we should pick last one,[-1].features_rank = features.rolling(60, min_periods=60). \ apply(roll_rank).dropna()outcomes_rank = outcomes.rolling(60, min_periods=60). \ apply(roll_rank).dropna() Pandasrolling(), by default, the result is set to the right edge of the window. That means the window is backward-looking windows, from the past rolls towards current timestamp. That is why, to rank() in that window frame, we pick the last value [-1]. More information about rolling(), please check the official document. First, we have a quick look at the outcomes’ cluster map. It is almost identical to the percentage change one with a different order. corr_outcomes_rank = outcomes_rank.corr().sort_index()sns.clustermap(corr_outcomes_rank, cmap='coolwarm', linewidth=2); The same pattern goes to the features’ cluster map. corr_features_rank = features_rank.corr().sort_index()sns.clustermap(corr_features_rank, cmap='coolwarm', linewidth=2); Even with a different method, # using 'ward' methodcorr_features_rank = features_rank.corr().sort_index()sns.clustermap(corr_features_rank, cmap='coolwarm', linewidth=2, method='ward'); and of course, the correlation of features and outcome are the same as well. corr_features_outcomes_rank = features_rank.corrwith( \ outcomes_rank. \ close_change_1D).sort_values()corr_features_outcomes_rank corr_features_outcomes_rank.plot(kind='barh',title = 'Strength of Correlation'); Last, you may guess the pair plot will be the same as well. selected_features_1D_list = ['volume_1D', 'price_spread_1D', 'close_loc_1D', 'close_change_1D']features_outcomes_rank['sign_of_close'] = features_outcomes_rmv_outliers['close_change_1D']. \ apply(np.sign)sns.pairplot(features_outcomes_rank, vars=selected_features_1D_list, diag_kind='kde', palette='husl', hue='sign_of_close', markers = ['*', '<', '+'], plot_kws={'alpha':0.3}); Because of the percentile rank (from 0.00 to 1.00) we utilized in the set window, the spots are evenly distributed across all features. The distribution of all the features is more or less close to a normal distribution than the same data without transformation. The last not least, I would like to remove all the data grain and see how those features related under this scenario. features_sign = features.apply(np.sign)outcomes_sign = outcomes.apply(np.sign) Then calculate the correlation coefficiency again. corr_features_outcomes_sign = features_sign.corrwith( outcomes_sign. \ close_change_1D).sort_values(ascending=False)corr_features_outcomes_sign corr_features_outcomes_sign.plot(kind='barh',title = 'Strength of Correlation'); It turns out a bit weird now, like volume_1D and price_spread_1D has a very weak correlation with the outcome now. Luckily, the cluster map remains pretty much the same. corr_features_sign = features_sign.corr().sort_index()sns.clustermap(corr_features_sign, cmap='coolwarm', linewidth=2); And the same goes for the relationship between outcomes. corr_outcomes_sign = outcomes_sign.corr().sort_index()sns.clustermap(corr_outcomes_sign, cmap='coolwarm', linewidth=2); As for pair plot, as all the data are transferred to either -1 or 1, it doesn’t show anything meaningful. It is sometimes vital to “standardize” or “normalize” data so that we get fair comparisons between features of differing scale. I am tempted to use Z-score to normalize the data set. The formula of Z-score requires the mean and standard deviation, by calculating these two parameters across the entire dataset, we have the chance to peek to the future. Of course, we can take advantage of the rolling window again. But generally, people will normalize their data before injecting them into their model. In summary, by utilizing 3 different data transformations methods, now we are pretty confident we can select the most related features and discard those abundant ones as all 3 methods pretty much share the same patterns. The last question can the transformed data pass the stationary/normality test? Here, I will use the Augmented Dickey-Fuller test1, which is a type of statistical test called a unit root test. At the meantime, I want to see the skewness and kurtosis as well. import statsmodels.api as smimport scipy.stats as scsp_val = lambda s: sm.tsa.stattools.adfuller(s)[1]def build_stats(df): stats = pd.DataFrame({'skew':scs.skew(df), 'skew_test':scs.skewtest(df)[1], 'kurtosis': scs.kurtosis(df), 'kurtosis_test' : scs.kurtosistest(df)[1], 'normal_test' : scs.normaltest(df)[1]}, index = df.columns) return stats The null hypothesis of the test is that the time series can be represented by a unit root, that it is not stationary (has some time-dependent structure). The alternate hypothesis (rejecting the null hypothesis) is that the time series is stationary. Null Hypothesis (H0): If failed to be rejected, it suggests the time series has a unit root, meaning it is non-stationary. It has some time dependent structure. Alternate Hypothesis (H1): The null hypothesis is rejected; it suggests the time series does not have a unit root, meaning it is stationary. It does not have time-dependent structure. Here is the result from Augmented Dickey-Fuller test: For features and outcomes: features_p_val = features.apply(p_val)outcomes_p_val = outcomes.apply(p_val)outcomes_p_val,features_p_val The test can be interpreted by the p-value. A p-value below a threshold (such as 5% or 1%) suggests we reject the null hypothesis (stationary), otherwise, a p-value above the threshold suggests we cannot reject the null hypothesis (non-stationary). p-value > 0.05: cannot reject the null hypothesis (H0), the data has a unit root and is non-stationary. p-value <= 0.05: Reject the null hypothesis (H0), the data does not have a unit root and is stationary. From this test, we can see that all the results are well below 5%, that shows we can reject the null hypothesis and all the transformed data are stationary. Next, let’s test the normality. build_stats(features_outcomes_rmv_outliers) For normally distributed data, the skewness should be about zero. For unimodal continuous distributions, a skewness value greater than zero meansthat there is more weight in the right tail of the distribution and vice versa. scs.skewtest() tests the null hypothesis that the skewness of the population that the sample was drawn from is the same as that of a corresponding normal distribution. As all the numbers are below 5% threshold, we have to reject the null hypothesis and say the skewness doesn’t correspond to normal distribution. The same thing goes to scs.kurtosistest(). scs.normaltest() tests the null hypothesis that a sample comes from a normal distribution. It is based on D’Agostino and Pearson’s test2 3 that combines skew and kurtosis to produce an omnibus test of normality. Again, all the numbers are below 5% threshold. We have to reject the null hypothesis and say the data transformed by percentage change is not normal distribution. We can do the same tests on data transformed by Percentile Ranking and Signing. I don’t want to scare people off by complexing thing further. I am better off ending here before this article goes way too long. MacKinnon, J.G. 1994. “Approximate asymptotic distribution functions for unit-root and cointegration tests. `Journal of Business and Economic Statistics` 12, 167–76.D’Agostino, R. B. (1971), “An omnibus test of normality for moderate and large sample size”, Biometrika, 58, 341–348D’Agostino, R. and Pearson, E. S. (1973), “Tests for departure from normality”, Biometrika, 60, 613–622 MacKinnon, J.G. 1994. “Approximate asymptotic distribution functions for unit-root and cointegration tests. `Journal of Business and Economic Statistics` 12, 167–76. D’Agostino, R. B. (1971), “An omnibus test of normality for moderate and large sample size”, Biometrika, 58, 341–348 D’Agostino, R. and Pearson, E. S. (1973), “Tests for departure from normality”, Biometrika, 60, 613–622
[ { "code": null, "e": 277, "s": 172, "text": "Warning: There is no magical formula or Holy Grail here, though a new world might open the door for you." }, { "code": null, "e": 510, "s": 277, "text": "Identifying OutliersIdentifying Outliers — Part TwoIdentifying Outliers — Part ThreeStylized FactsFeature Engineering & Feature SelectionData TransformationFractionally Differentiated FeaturesData LabellingMeta-labeling and Stacking" }, { "code": null, "e": 531, "s": 510, "text": "Identifying Outliers" }, { "code": null, "e": 563, "s": 531, "text": "Identifying Outliers — Part Two" }, { "code": null, "e": 597, "s": 563, "text": "Identifying Outliers — Part Three" }, { "code": null, "e": 612, "s": 597, "text": "Stylized Facts" }, { "code": null, "e": 652, "s": 612, "text": "Feature Engineering & Feature Selection" }, { "code": null, "e": 672, "s": 652, "text": "Data Transformation" }, { "code": null, "e": 709, "s": 672, "text": "Fractionally Differentiated Features" }, { "code": null, "e": 724, "s": 709, "text": "Data Labelling" }, { "code": null, "e": 751, "s": 724, "text": "Meta-labeling and Stacking" }, { "code": null, "e": 1202, "s": 751, "text": "In the previews article, I briefly introduced the Volume Spread Analysis(VSA). After we did feature-engineering and feature-selection, there were two things I noticed immediately, the first one was that there were outliers in the dataset and the second issue was the distribution were no way close to normal. By using the method described here, here and here, I removed most of the outliers. Now is the time to face the bigger problem, the normality." }, { "code": null, "e": 1723, "s": 1202, "text": "There are many ways to transfer the data. One of the well-known examples is the one-hot encoding, even better one is word embedding in natural language processing (NLP). Considering one of the advantages of using deep learning is that it completely automates what used to be the most crucial step in a machine-learning workflow: feature engineering. Before we get into the deep learning in the later articles, let’s have a look at some simple ways to transfer data to see if we can make it closer to normal distribution." }, { "code": null, "e": 2086, "s": 1723, "text": "In this article, I would like to try a few things. The first one is to transfer all the features to a simple percentage change. The second one is to do a Percentile Ranking. In the end, I will show you what happens if I only pick the sign of all the data. Methods like Z-score, which are standard pre-processing in deep learning, I would rather leave it for now." }, { "code": null, "e": 2461, "s": 2086, "text": "For consistency, in all the 📈Python for finance series, I will try to reuse the same data as much as I can. More details about data preparation can be found here, here and here or you can refer back to my previous article. Or if you like, you can ignore all the code below and use whatever clean data you have at hand, it won’t affect the things we are going to do together." }, { "code": null, "e": 6031, "s": 2461, "text": "#import all the librariesimport pandas as pdimport numpy as npimport seaborn as sns import yfinance as yf #the stock data from Yahoo Financeimport matplotlib.pyplot as plt #set the parameters for plottingplt.style.use('seaborn')plt.rcParams['figure.dpi'] = 300#define a function to get datadef get_data(symbols, begin_date=None,end_date=None): df = yf.download('AAPL', start = '2000-01-01', auto_adjust=True,#only download adjusted data end= '2010-12-31') #my convention: always lowercase df.columns = ['open','high','low', 'close','volume'] return dfprices = get_data('AAPL', '2000-01-01', '2010-12-31')#create some featuresdef create_HLCV(i):#as we don't care open that much, that leaves volume, #high,low and close df = pd.DataFrame(index=prices.index) df[f'high_{i}D'] = prices.high.rolling(i).max() df[f'low_{i}D'] = prices.low.rolling(i).min() df[f'close_{i}D'] = prices.close.rolling(i).\\ apply(lambda x:x[-1]) # close_2D = close as rolling backwards means today is # literly the last day of the rolling window. df[f'volume_{i}D'] = prices.volume.rolling(i).sum() return df# create features at different rolling windowsdef create_features_and_outcomes(i): df = create_HLCV(i) high = df[f'high_{i}D'] low = df[f'low_{i}D'] close = df[f'close_{i}D'] volume = df[f'volume_{i}D'] features = pd.DataFrame(index=prices.index) outcomes = pd.DataFrame(index=prices.index) #as we already considered the different time span, #here only day of simple percentage change used. features[f'volume_{i}D'] = volume.pct_change() features[f'price_spread_{i}D'] = (high - low).pct_change() #aligne the close location with the stock price change features[f'close_loc_{i}D'] = ((close - low) / \\ (high - low)).pct_change() #the future outcome is what we are going to predict outcomes[f'close_change_{i}D'] = close.pct_change(-i) return features, outcomesdef create_bunch_of_features_and_outcomes(): ''' the timespan that i would like to explore are 1, 2, 3 days and 1 week, 1 month, 2 month, 3 month which roughly are [1,2,3,5,20,40,60] ''' days = [1,2,3,5,20,40,60] bunch_of_features = pd.DataFrame(index=prices.index) bunch_of_outcomes = pd.DataFrame(index=prices.index) for day in days: f,o = create_features_and_outcomes(day) bunch_of_features = bunch_of_features.join(f) bunch_of_outcomes = bunch_of_outcomes .join(o) return bunch_of_features, bunch_of_outcomesbunch_of_features, bunch_of_outcomes = create_bunch_of_features_and_outcomes()#define the method to identify outliersdef get_outliers(df, i=4): #i is number of sigma, which define the boundary along mean outliers = pd.DataFrame() stats = df.describe() for col in df.columns: mu = stats.loc['mean', col] sigma = stats.loc['std', col] condition = (df[col] > mu + sigma * i) | \\ (df[col] < mu - sigma * i) outliers[f'{col}_outliers'] = df[col][condition] return outliers#remove all the outliersfeatures_outcomes = bunch_of_features.join(bunch_of_outcomes)outliers = get_outliers(features_outcomes, i=1)features_outcomes_rmv_outliers = features_outcomes.drop(index = outliers.index).dropna()features = features_outcomes_rmv_outliers[bunch_of_features.columns]outcomes = features_outcomes_rmv_outliers[bunch_of_outcomes.columns]features.info(), outcomes.info()" }, { "code": null, "e": 6227, "s": 6031, "text": "In the end, we will have the basic four features based on Volume Spread Analysis (VSA) at different time scale listed below, namely, 1 day, 2 days, 3 days, a week, a month, 2 months and 3 months." }, { "code": null, "e": 6259, "s": 6227, "text": "Volume: pretty straight forward" }, { "code": null, "e": 6307, "s": 6259, "text": "Range/Spread: Difference between high and close" }, { "code": null, "e": 6406, "s": 6307, "text": "Closing Price Relative to Range: Is the closing price near the top or the bottom of the price bar?" }, { "code": null, "e": 6457, "s": 6406, "text": "The change of stock price: pretty straight forward" }, { "code": null, "e": 6596, "s": 6457, "text": "I know that’s a whole lot of codes above. We have all the features transformed into a simple percentage change through the function below." }, { "code": null, "e": 7381, "s": 6596, "text": "def create_features_and_outcomes(i): df = create_HLCV(i) high = df[f'high_{i}D'] low = df[f'low_{i}D'] close = df[f'close_{i}D'] volume = df[f'volume_{i}D'] features = pd.DataFrame(index=prices.index) outcomes = pd.DataFrame(index=prices.index) #as we already considered the different time span, #here only 1 day of simple percentage change used. features[f'volume_{i}D'] = volume.pct_change() features[f'price_spread_{i}D'] = (high - low).pct_change() #aligne the close location with the stock price change features[f'close_loc_{i}D'] = ((close - low) / \\ (high - low)).pct_change()#the future outcome is what we are going to predict outcomes[f'close_change_{i}D'] = close.pct_change(-i) return features, outcomes" }, { "code": null, "e": 7563, "s": 7381, "text": "Now, let’s have a look at their correlations using cluster map. Seaborn’s clustermap() hierarchical clustering algorithm shows a nice way to group the most closely related features." }, { "code": null, "e": 7668, "s": 7563, "text": "corr_features = features.corr().sort_index()sns.clustermap(corr_features, cmap='coolwarm', linewidth=1);" }, { "code": null, "e": 8110, "s": 7668, "text": "Based on this cluster map, to minimize the amount of feature overlap in selected features, I will remove those features that are paired with other features closely and having less correlation with the outcome targets. From the cluster map above, it is easy to spot that features on [40D, 60D] and [2D, 3D] are paired together. To see how those features are related to the outcomes, let’s have a look at how the outcomes are correlated first." }, { "code": null, "e": 8202, "s": 8110, "text": "corr_outcomes = outcomes.corr()sns.clustermap(corr_outcomes, cmap='coolwarm', linewidth=2);" }, { "code": null, "e": 8545, "s": 8202, "text": "From top to bottom, 20 days, 40 days and 60 days price percentage change are grouped together, so as the 2 days, 3 days and 5 days. Whereas, 1-day stock price percentage change is relatively independent of those two groups. If we pick the next day price percentage change as the outcome target, let’s see how those features are related to it." }, { "code": null, "e": 8780, "s": 8545, "text": "corr_features_outcomes = features.corrwith(outcomes. \\ close_change_1D).sort_values()corr_features_outcomes.dropna(inplace=True)corr_features_outcomes.plot(kind='barh',title = 'Strength of Correlation');" }, { "code": null, "e": 8955, "s": 8780, "text": "The correlation coefficients are way too small to make a solid conclusion. I will expect that the most recent data have a stronger correlation, but that is not the case here." }, { "code": null, "e": 9200, "s": 8955, "text": "How about the pair plot? We only pick those features based on a 1-day time scale as a demonstration. At the meantime, I transferred the close_change_1D to sign base on it’s a negative or positive number to add extra dimensionality to the plots." }, { "code": null, "e": 9706, "s": 9200, "text": "selected_features_1D_list = ['volume_1D', 'price_spread_1D', 'close_loc_1D', 'close_change_1D']features_outcomes_rmv_outliers['sign_of_close'] = features_outcomes_rmv_outliers['close_change_1D']. \\ apply(np.sign)sns.pairplot(features_outcomes_rmv_outliers, vars=selected_features_1D_list, diag_kind='kde', palette='husl', hue='sign_of_close', markers = ['*', '<', '+'], plot_kws={'alpha':0.3});" }, { "code": null, "e": 10364, "s": 9706, "text": "The pair plot builds on two basic figures, the histogram and the scatter plot. The histogram on the diagonal allows us to see the distribution of a single variable while the scatter plots on the upper and lower triangles show the relationship (or lack thereof) between two variables. From the plots above, we can see that price spreads are getting wider with high volume. Most of the price change locate at a narrow price spread, in another word, wider spread doesn’t always come with bigger price fluctuation. Either low volume or high volume can cause price change at almost all scale. And we can apply all those conclusions to both up days and down days." }, { "code": null, "e": 10449, "s": 10364, "text": "you can also use the close location of bars to add more dimensionality, simply apply" }, { "code": null, "e": 10534, "s": 10449, "text": "features[‘sign_of_close_loc’] = np.where( \\ features[‘close_loc_1D’] > 0.5, \\ 1, -1)" }, { "code": null, "e": 10599, "s": 10534, "text": "to see how many bars’ close location above the 0.5 or below 0.5." }, { "code": null, "e": 11016, "s": 10599, "text": "One thing that I don’t really like in the pair plot is all the plots with the close_loc_1D condensed, looks like the outliers still there, even I know I used one standard deviation as the boundary which is a very low threshold and 338 outliers were removed. I realize that because the location of close is already a percentage change, adding another percentage change on top doesn’t make much sense. Let’s change it." }, { "code": null, "e": 11727, "s": 11016, "text": "def create_features_and_outcomes(i): df = create_HLCV(i) high = df[f'high_{i}D'] low = df[f'low_{i}D'] close = df[f'close_{i}D'] volume = df[f'volume_{i}D'] features = pd.DataFrame(index=prices.index) outcomes = pd.DataFrame(index=prices.index) #as we already considered the different time span, #simple percentage change of 1 day used here. features[f'volume_{i}D'] = volume.pct_change() features[f'price_spread_{i}D'] = (high - low).pct_change() #remove pct_change() here features[f'close_loc_{i}D'] = ((close - low) / (high - low)) #predict the future with -i outcomes[f'close_change_{i}D'] = close.pct_change(-i) return features, outcomes" }, { "code": null, "e": 11800, "s": 11727, "text": "With pct_change() removed, let’s see how the cluster map looks like now." }, { "code": null, "e": 11905, "s": 11800, "text": "corr_features = features.corr().sort_index()sns.clustermap(corr_features, cmap='coolwarm', linewidth=1);" }, { "code": null, "e": 12044, "s": 11905, "text": "The cluster map makes more sense now. All four basic features have pretty much the same pattern. [40D, 60D], [2D, 3D] are paired together." }, { "code": null, "e": 12104, "s": 12044, "text": "and in terms of the features correlations with the outcome." }, { "code": null, "e": 12180, "s": 12104, "text": "corr_features_outcomes.plot(kind='barh',title = 'Strength of Correlation');" }, { "code": null, "e": 12334, "s": 12180, "text": "The longer-range time scale features have weak correlations with stock price return, while the more recent events have more effects on the price returns." }, { "code": null, "e": 12430, "s": 12334, "text": "By removing pct_change() of the close_loc_1D, the biggest difference is laid on the pairplot()." }, { "code": null, "e": 12598, "s": 12430, "text": "Finally, the close_loc_1D variable plots at the right range. This illustrates that we should be careful with over-engineering. It may lead to a totally unexpected way." }, { "code": null, "e": 12645, "s": 12598, "text": "According to Wikipedia, the percentile rank is" }, { "code": null, "e": 12934, "s": 12645, "text": "“The percentile rank of a score is the percentage of scores in its frequency distribution that are equal to or lower than it. For example, a test score that is greater than 75% of the scores of people taking the test is said to be at the 75th percentile, where 75 is the percentile rank.”" }, { "code": null, "e": 13073, "s": 12934, "text": "The below example returns the percentile rank (from 0.00 to 1.00) of traded volume for each value as compared to a trailing 60-day period." }, { "code": null, "e": 13458, "s": 13073, "text": "roll_rank = lambda x: pd.Series(x).rank(pct=True)[-1]# you only pick the first value [0]# of the 60 windows rank if you rolling forward.# if you rolling backward, we should pick last one,[-1].features_rank = features.rolling(60, min_periods=60). \\ apply(roll_rank).dropna()outcomes_rank = outcomes.rolling(60, min_periods=60). \\ apply(roll_rank).dropna()" }, { "code": null, "e": 13710, "s": 13458, "text": "Pandasrolling(), by default, the result is set to the right edge of the window. That means the window is backward-looking windows, from the past rolls towards current timestamp. That is why, to rank() in that window frame, we pick the last value [-1]." }, { "code": null, "e": 13780, "s": 13710, "text": "More information about rolling(), please check the official document." }, { "code": null, "e": 13914, "s": 13780, "text": "First, we have a quick look at the outcomes’ cluster map. It is almost identical to the percentage change one with a different order." }, { "code": null, "e": 14034, "s": 13914, "text": "corr_outcomes_rank = outcomes_rank.corr().sort_index()sns.clustermap(corr_outcomes_rank, cmap='coolwarm', linewidth=2);" }, { "code": null, "e": 14086, "s": 14034, "text": "The same pattern goes to the features’ cluster map." }, { "code": null, "e": 14206, "s": 14086, "text": "corr_features_rank = features_rank.corr().sort_index()sns.clustermap(corr_features_rank, cmap='coolwarm', linewidth=2);" }, { "code": null, "e": 14236, "s": 14206, "text": "Even with a different method," }, { "code": null, "e": 14392, "s": 14236, "text": "# using 'ward' methodcorr_features_rank = features_rank.corr().sort_index()sns.clustermap(corr_features_rank, cmap='coolwarm', linewidth=2, method='ward');" }, { "code": null, "e": 14469, "s": 14392, "text": "and of course, the correlation of features and outcome are the same as well." }, { "code": null, "e": 14658, "s": 14469, "text": "corr_features_outcomes_rank = features_rank.corrwith( \\ outcomes_rank. \\ close_change_1D).sort_values()corr_features_outcomes_rank" }, { "code": null, "e": 14739, "s": 14658, "text": "corr_features_outcomes_rank.plot(kind='barh',title = 'Strength of Correlation');" }, { "code": null, "e": 14799, "s": 14739, "text": "Last, you may guess the pair plot will be the same as well." }, { "code": null, "e": 15289, "s": 14799, "text": "selected_features_1D_list = ['volume_1D', 'price_spread_1D', 'close_loc_1D', 'close_change_1D']features_outcomes_rank['sign_of_close'] = features_outcomes_rmv_outliers['close_change_1D']. \\ apply(np.sign)sns.pairplot(features_outcomes_rank, vars=selected_features_1D_list, diag_kind='kde', palette='husl', hue='sign_of_close', markers = ['*', '<', '+'], plot_kws={'alpha':0.3});" }, { "code": null, "e": 15552, "s": 15289, "text": "Because of the percentile rank (from 0.00 to 1.00) we utilized in the set window, the spots are evenly distributed across all features. The distribution of all the features is more or less close to a normal distribution than the same data without transformation." }, { "code": null, "e": 15670, "s": 15552, "text": "The last not least, I would like to remove all the data grain and see how those features related under this scenario." }, { "code": null, "e": 15749, "s": 15670, "text": "features_sign = features.apply(np.sign)outcomes_sign = outcomes.apply(np.sign)" }, { "code": null, "e": 15800, "s": 15749, "text": "Then calculate the correlation coefficiency again." }, { "code": null, "e": 16002, "s": 15800, "text": "corr_features_outcomes_sign = features_sign.corrwith( outcomes_sign. \\ close_change_1D).sort_values(ascending=False)corr_features_outcomes_sign" }, { "code": null, "e": 16083, "s": 16002, "text": "corr_features_outcomes_sign.plot(kind='barh',title = 'Strength of Correlation');" }, { "code": null, "e": 16198, "s": 16083, "text": "It turns out a bit weird now, like volume_1D and price_spread_1D has a very weak correlation with the outcome now." }, { "code": null, "e": 16253, "s": 16198, "text": "Luckily, the cluster map remains pretty much the same." }, { "code": null, "e": 16373, "s": 16253, "text": "corr_features_sign = features_sign.corr().sort_index()sns.clustermap(corr_features_sign, cmap='coolwarm', linewidth=2);" }, { "code": null, "e": 16430, "s": 16373, "text": "And the same goes for the relationship between outcomes." }, { "code": null, "e": 16550, "s": 16430, "text": "corr_outcomes_sign = outcomes_sign.corr().sort_index()sns.clustermap(corr_outcomes_sign, cmap='coolwarm', linewidth=2);" }, { "code": null, "e": 16656, "s": 16550, "text": "As for pair plot, as all the data are transferred to either -1 or 1, it doesn’t show anything meaningful." }, { "code": null, "e": 16839, "s": 16656, "text": "It is sometimes vital to “standardize” or “normalize” data so that we get fair comparisons between features of differing scale. I am tempted to use Z-score to normalize the data set." }, { "code": null, "e": 17159, "s": 16839, "text": "The formula of Z-score requires the mean and standard deviation, by calculating these two parameters across the entire dataset, we have the chance to peek to the future. Of course, we can take advantage of the rolling window again. But generally, people will normalize their data before injecting them into their model." }, { "code": null, "e": 17380, "s": 17159, "text": "In summary, by utilizing 3 different data transformations methods, now we are pretty confident we can select the most related features and discard those abundant ones as all 3 methods pretty much share the same patterns." }, { "code": null, "e": 17638, "s": 17380, "text": "The last question can the transformed data pass the stationary/normality test? Here, I will use the Augmented Dickey-Fuller test1, which is a type of statistical test called a unit root test. At the meantime, I want to see the skewness and kurtosis as well." }, { "code": null, "e": 18070, "s": 17638, "text": "import statsmodels.api as smimport scipy.stats as scsp_val = lambda s: sm.tsa.stattools.adfuller(s)[1]def build_stats(df): stats = pd.DataFrame({'skew':scs.skew(df), 'skew_test':scs.skewtest(df)[1], 'kurtosis': scs.kurtosis(df), 'kurtosis_test' : scs.kurtosistest(df)[1], 'normal_test' : scs.normaltest(df)[1]}, index = df.columns) return stats" }, { "code": null, "e": 18320, "s": 18070, "text": "The null hypothesis of the test is that the time series can be represented by a unit root, that it is not stationary (has some time-dependent structure). The alternate hypothesis (rejecting the null hypothesis) is that the time series is stationary." }, { "code": null, "e": 18481, "s": 18320, "text": "Null Hypothesis (H0): If failed to be rejected, it suggests the time series has a unit root, meaning it is non-stationary. It has some time dependent structure." }, { "code": null, "e": 18665, "s": 18481, "text": "Alternate Hypothesis (H1): The null hypothesis is rejected; it suggests the time series does not have a unit root, meaning it is stationary. It does not have time-dependent structure." }, { "code": null, "e": 18719, "s": 18665, "text": "Here is the result from Augmented Dickey-Fuller test:" }, { "code": null, "e": 18746, "s": 18719, "text": "For features and outcomes:" }, { "code": null, "e": 18852, "s": 18746, "text": "features_p_val = features.apply(p_val)outcomes_p_val = outcomes.apply(p_val)outcomes_p_val,features_p_val" }, { "code": null, "e": 19101, "s": 18852, "text": "The test can be interpreted by the p-value. A p-value below a threshold (such as 5% or 1%) suggests we reject the null hypothesis (stationary), otherwise, a p-value above the threshold suggests we cannot reject the null hypothesis (non-stationary)." }, { "code": null, "e": 19205, "s": 19101, "text": "p-value > 0.05: cannot reject the null hypothesis (H0), the data has a unit root and is non-stationary." }, { "code": null, "e": 19309, "s": 19205, "text": "p-value <= 0.05: Reject the null hypothesis (H0), the data does not have a unit root and is stationary." }, { "code": null, "e": 19466, "s": 19309, "text": "From this test, we can see that all the results are well below 5%, that shows we can reject the null hypothesis and all the transformed data are stationary." }, { "code": null, "e": 19498, "s": 19466, "text": "Next, let’s test the normality." }, { "code": null, "e": 19542, "s": 19498, "text": "build_stats(features_outcomes_rmv_outliers)" }, { "code": null, "e": 19767, "s": 19542, "text": "For normally distributed data, the skewness should be about zero. For unimodal continuous distributions, a skewness value greater than zero meansthat there is more weight in the right tail of the distribution and vice versa." }, { "code": null, "e": 20123, "s": 19767, "text": "scs.skewtest() tests the null hypothesis that the skewness of the population that the sample was drawn from is the same as that of a corresponding normal distribution. As all the numbers are below 5% threshold, we have to reject the null hypothesis and say the skewness doesn’t correspond to normal distribution. The same thing goes to scs.kurtosistest()." }, { "code": null, "e": 20498, "s": 20123, "text": "scs.normaltest() tests the null hypothesis that a sample comes from a normal distribution. It is based on D’Agostino and Pearson’s test2 3 that combines skew and kurtosis to produce an omnibus test of normality. Again, all the numbers are below 5% threshold. We have to reject the null hypothesis and say the data transformed by percentage change is not normal distribution." }, { "code": null, "e": 20707, "s": 20498, "text": "We can do the same tests on data transformed by Percentile Ranking and Signing. I don’t want to scare people off by complexing thing further. I am better off ending here before this article goes way too long." }, { "code": null, "e": 21092, "s": 20707, "text": "MacKinnon, J.G. 1994. “Approximate asymptotic distribution functions for unit-root and cointegration tests. `Journal of Business and Economic Statistics` 12, 167–76.D’Agostino, R. B. (1971), “An omnibus test of normality for moderate and large sample size”, Biometrika, 58, 341–348D’Agostino, R. and Pearson, E. S. (1973), “Tests for departure from normality”, Biometrika, 60, 613–622" }, { "code": null, "e": 21258, "s": 21092, "text": "MacKinnon, J.G. 1994. “Approximate asymptotic distribution functions for unit-root and cointegration tests. `Journal of Business and Economic Statistics` 12, 167–76." }, { "code": null, "e": 21375, "s": 21258, "text": "D’Agostino, R. B. (1971), “An omnibus test of normality for moderate and large sample size”, Biometrika, 58, 341–348" } ]
Clustering Product Names with Python — Part 1 | by Lily Wu | Towards Data Science
Natural Language Processing (NLP) refers to the automatic computational processing of human language like text and speech. It is particularly useful for analysing large amounts of unlabelled text to quickly extract meaning which is exactly the problem when it comes to categorising eCommerce products. Products can be either labelled with incorrect categories or not labelled at all. Manual categorisation is not efficient, if not impossible for some. Today we are going to talk about how we can use NLP and K-means in Python to automatically cluster unlabelled product names to quickly understand what kinds of products are in a data set. This method is unsupervised (the categories and number of categories are not set) and differs from classification which is supervised and allocates product names to target labels (known categories). For this guide I’ll be using a data set from the Australian Food Composition Database which contains data on the nutrient content of Australian foods. I’ll show you how I clustered 1,534 food names with a lot of uniqueness... ...to get an efficient, high level view of all the types of foods in the data set — with little human input. The method consists of the following steps: Preprocessing the text (the food names) into clean words so that we can turn it into numerical data. Vectorisation which is the process of turning words into numerical features to prepare for machine learning. Applying K-means clustering, an unsupervised machine learning algorithm, to group food names with similar words together. Assessing cluster quality through cluster labelling and visualisation. Finetuning steps 1–4 to improve cluster quality. This article is Part 1 and will cover: Preprocessing and Vectorisation. Be sure to also check out Part 2 which will cover: K-means Clustering, Assessing Cluster Quality and Finetuning. Full disclosure: this data set actually comes with a column ‘Classification Name’ with 268 categories but for demonstration purposes, let’s pretend it’s not there ;) This guide will use Pandas, NumPy, scikit-learn, FuzzyWuzzy, Matplotlib and Plotly. Optional are libraries used to preprocess this specific data set. I used Gensim, String, NLTK and Webcolors. If you don’t already have everything installed, the easiest way is to install via pip. pip install fuzzywuzzypip install plotlypip install gensimpip install webcolors Let’s import the libraries, load the data set and put the food names in a Pandas Series. The aim of the game here is to remove unnecessary words and characters so that the words in our food names are meaningful for clustering later. There are many preprocessing techniques and selecting which ones to use depends on how they’ll affect the clusters. Here are the techniques I used and why. Stopwords are the common words in language like ‘the’, ‘a’, ‘is’, ‘and’. Yielding a cluster because all the food names contain the word ‘and’ for example, which isn’t relevant to what the foods are, isn’t useful. We’ll remove stopwords using the Gensim library, and punctuation and numbers using the String library. Stemming words involves shortening them to their root forms. For example ‘apple’ and ‘apples’ both become ‘appl’ and are treated as the same word in the vectorisation stage. Note: lemmatisation would reduce both words to the real word ‘apple’ based on context. It is more computationally expensive and wasn’t required for this exercise as I could easily tell what the stemmed words referred to. Using the NLTK library will also make all words lower case. This is useful so that ‘Appl’ and ‘appl’ are treated as the same word in the vectorisation stage. Having colours in our food names will likely yield clusters of same-coloured but otherwise unrelated foods. We’ll remove colours using the Webcolors dictionary, but not the colours that are also foods (eg: ‘chocolate’ and ‘lime’). Here’s a before and after of our food names. We ended up with 851 distinct words in our text. Some Python libraries used in the vectorisation stage have some of these techniques built-in. However, if testing multiple vectorisation models, it’s best to start with a consistent, clean text to be able to compare output. We now want to turn our cleaned text into numerical data so that we can perform statistical analysis on it. Just like preprocessing, there are many techniques to choose from. These are the models I tested. Bag of words (using sci-kit learn’s CountVectorizer) is a basic model that counts the occurrences of words in a document. Here, each row — one food name — is a document. The result is a matrix containing a feature for each distinct word in the text and the count of each word in a row (or vector) as its numerical values. Here’s the matrix again, subsetted to show only the words in the first row. Note the counts for each row. A basic count of words like this may not be enough to extract meaning. In this case, some words in a food name are more pertinent to what type of food it is. For example in ‘Broccolini, fresh, raw’, the word ‘broccolini’ is more important than ‘fresh’ or ‘raw’ for our clustering but bag of words gives all three equal weight. TF-IDF (using sci-kit learn’s TfidfVectorizer) measures the frequency of a word in a document and compares it to the frequencies of all words in the text to assign it a weighted score of importance. Let’s see it in action at a word level where words are considered independently of each other for meaning. Now we have different values for each word of the vector. In the first row, ‘cardamom’ has the highest score which is great! We can use TF-IDF at an n-gram level where the frequency of sequences of words is also considered. Here I used the ngram_range parameter to tell the model to consider n-grams between 1 (individual words) and 2 (sequences of 2 words or bi-grams). The first row has values against the bi-grams ‘cardamom seed’, ‘seed dried’ and ‘dried ground’, with the highest score for ‘cardamom seed’. Awesome! I tested increasing the ngram_range upper limit to 3, 4 and 5 but 2 worked best for this data set in the clustering later. The documents (our food names) are relatively short and there weren’t many meaningful n-grams that were longer than 2 words. LDA identifies patterns in word frequency to probabilistically estimate the topics of documents and the words used in those topics. It assumes each document is made up of several topics and similar topics use similar words. Like in bag of words, each word is considered independently of each other in the model. LDA can be very useful for large documents, such as news articles, in uncovering its high level themes. However, it wasn’t quite right for this data set as each food name isn’t necessarily made up of multiple topics. I tested for the optimal learning rate and number of topics to tell the model to find. Here is the result at 30 topics and the top 5 words per topic. It’s done exactly what it’s meant to do. We have patterns of words used together to describe our foods but they don’t illuminate the types of foods in our data set. Lastly, Fuzzywuzzy calculates a similarity score between two strings and is great for fuzzy (as opposed to exact) matching. This one was some outside-the-box thinking. My logic was that if food names of the same food type were worded slightly differently (eg: different kinds of apples), they would yield a high similarity score. Here I created a matrix of each food name and its similarity score with every other food name. I ended up with 1,534 rows (one for each food name) and 1,500 columns (one for each distinct food name after preprocessing). Admittedly this was the slowest vectorisation method as it performed in-memory calculations for a 1,534 x 1,500 Pandas Dataframe. After clustering it performed similarly to bag of words. Keep reading in Part 2 to find out what the results of clustering were. This article is Part 1 and covered: Preprocessing and Vectorisation. Please keep reading in Part 2 which will cover: K-means Clustering, Assessing Cluster Quality and Finetuning. The data set used in this guide is from the Australian Food Composition Database and is licenced by Food Standards Australia New Zealand.
[ { "code": null, "e": 294, "s": 171, "text": "Natural Language Processing (NLP) refers to the automatic computational processing of human language like text and speech." }, { "code": null, "e": 623, "s": 294, "text": "It is particularly useful for analysing large amounts of unlabelled text to quickly extract meaning which is exactly the problem when it comes to categorising eCommerce products. Products can be either labelled with incorrect categories or not labelled at all. Manual categorisation is not efficient, if not impossible for some." }, { "code": null, "e": 1010, "s": 623, "text": "Today we are going to talk about how we can use NLP and K-means in Python to automatically cluster unlabelled product names to quickly understand what kinds of products are in a data set. This method is unsupervised (the categories and number of categories are not set) and differs from classification which is supervised and allocates product names to target labels (known categories)." }, { "code": null, "e": 1236, "s": 1010, "text": "For this guide I’ll be using a data set from the Australian Food Composition Database which contains data on the nutrient content of Australian foods. I’ll show you how I clustered 1,534 food names with a lot of uniqueness..." }, { "code": null, "e": 1345, "s": 1236, "text": "...to get an efficient, high level view of all the types of foods in the data set — with little human input." }, { "code": null, "e": 1389, "s": 1345, "text": "The method consists of the following steps:" }, { "code": null, "e": 1490, "s": 1389, "text": "Preprocessing the text (the food names) into clean words so that we can turn it into numerical data." }, { "code": null, "e": 1599, "s": 1490, "text": "Vectorisation which is the process of turning words into numerical features to prepare for machine learning." }, { "code": null, "e": 1721, "s": 1599, "text": "Applying K-means clustering, an unsupervised machine learning algorithm, to group food names with similar words together." }, { "code": null, "e": 1792, "s": 1721, "text": "Assessing cluster quality through cluster labelling and visualisation." }, { "code": null, "e": 1841, "s": 1792, "text": "Finetuning steps 1–4 to improve cluster quality." }, { "code": null, "e": 1913, "s": 1841, "text": "This article is Part 1 and will cover: Preprocessing and Vectorisation." }, { "code": null, "e": 2026, "s": 1913, "text": "Be sure to also check out Part 2 which will cover: K-means Clustering, Assessing Cluster Quality and Finetuning." }, { "code": null, "e": 2192, "s": 2026, "text": "Full disclosure: this data set actually comes with a column ‘Classification Name’ with 268 categories but for demonstration purposes, let’s pretend it’s not there ;)" }, { "code": null, "e": 2472, "s": 2192, "text": "This guide will use Pandas, NumPy, scikit-learn, FuzzyWuzzy, Matplotlib and Plotly. Optional are libraries used to preprocess this specific data set. I used Gensim, String, NLTK and Webcolors. If you don’t already have everything installed, the easiest way is to install via pip." }, { "code": null, "e": 2552, "s": 2472, "text": "pip install fuzzywuzzypip install plotlypip install gensimpip install webcolors" }, { "code": null, "e": 2641, "s": 2552, "text": "Let’s import the libraries, load the data set and put the food names in a Pandas Series." }, { "code": null, "e": 2785, "s": 2641, "text": "The aim of the game here is to remove unnecessary words and characters so that the words in our food names are meaningful for clustering later." }, { "code": null, "e": 2941, "s": 2785, "text": "There are many preprocessing techniques and selecting which ones to use depends on how they’ll affect the clusters. Here are the techniques I used and why." }, { "code": null, "e": 3154, "s": 2941, "text": "Stopwords are the common words in language like ‘the’, ‘a’, ‘is’, ‘and’. Yielding a cluster because all the food names contain the word ‘and’ for example, which isn’t relevant to what the foods are, isn’t useful." }, { "code": null, "e": 3257, "s": 3154, "text": "We’ll remove stopwords using the Gensim library, and punctuation and numbers using the String library." }, { "code": null, "e": 3431, "s": 3257, "text": "Stemming words involves shortening them to their root forms. For example ‘apple’ and ‘apples’ both become ‘appl’ and are treated as the same word in the vectorisation stage." }, { "code": null, "e": 3652, "s": 3431, "text": "Note: lemmatisation would reduce both words to the real word ‘apple’ based on context. It is more computationally expensive and wasn’t required for this exercise as I could easily tell what the stemmed words referred to." }, { "code": null, "e": 3810, "s": 3652, "text": "Using the NLTK library will also make all words lower case. This is useful so that ‘Appl’ and ‘appl’ are treated as the same word in the vectorisation stage." }, { "code": null, "e": 4041, "s": 3810, "text": "Having colours in our food names will likely yield clusters of same-coloured but otherwise unrelated foods. We’ll remove colours using the Webcolors dictionary, but not the colours that are also foods (eg: ‘chocolate’ and ‘lime’)." }, { "code": null, "e": 4135, "s": 4041, "text": "Here’s a before and after of our food names. We ended up with 851 distinct words in our text." }, { "code": null, "e": 4359, "s": 4135, "text": "Some Python libraries used in the vectorisation stage have some of these techniques built-in. However, if testing multiple vectorisation models, it’s best to start with a consistent, clean text to be able to compare output." }, { "code": null, "e": 4467, "s": 4359, "text": "We now want to turn our cleaned text into numerical data so that we can perform statistical analysis on it." }, { "code": null, "e": 4565, "s": 4467, "text": "Just like preprocessing, there are many techniques to choose from. These are the models I tested." }, { "code": null, "e": 4887, "s": 4565, "text": "Bag of words (using sci-kit learn’s CountVectorizer) is a basic model that counts the occurrences of words in a document. Here, each row — one food name — is a document. The result is a matrix containing a feature for each distinct word in the text and the count of each word in a row (or vector) as its numerical values." }, { "code": null, "e": 4993, "s": 4887, "text": "Here’s the matrix again, subsetted to show only the words in the first row. Note the counts for each row." }, { "code": null, "e": 5320, "s": 4993, "text": "A basic count of words like this may not be enough to extract meaning. In this case, some words in a food name are more pertinent to what type of food it is. For example in ‘Broccolini, fresh, raw’, the word ‘broccolini’ is more important than ‘fresh’ or ‘raw’ for our clustering but bag of words gives all three equal weight." }, { "code": null, "e": 5519, "s": 5320, "text": "TF-IDF (using sci-kit learn’s TfidfVectorizer) measures the frequency of a word in a document and compares it to the frequencies of all words in the text to assign it a weighted score of importance." }, { "code": null, "e": 5626, "s": 5519, "text": "Let’s see it in action at a word level where words are considered independently of each other for meaning." }, { "code": null, "e": 5751, "s": 5626, "text": "Now we have different values for each word of the vector. In the first row, ‘cardamom’ has the highest score which is great!" }, { "code": null, "e": 5850, "s": 5751, "text": "We can use TF-IDF at an n-gram level where the frequency of sequences of words is also considered." }, { "code": null, "e": 6146, "s": 5850, "text": "Here I used the ngram_range parameter to tell the model to consider n-grams between 1 (individual words) and 2 (sequences of 2 words or bi-grams). The first row has values against the bi-grams ‘cardamom seed’, ‘seed dried’ and ‘dried ground’, with the highest score for ‘cardamom seed’. Awesome!" }, { "code": null, "e": 6394, "s": 6146, "text": "I tested increasing the ngram_range upper limit to 3, 4 and 5 but 2 worked best for this data set in the clustering later. The documents (our food names) are relatively short and there weren’t many meaningful n-grams that were longer than 2 words." }, { "code": null, "e": 6706, "s": 6394, "text": "LDA identifies patterns in word frequency to probabilistically estimate the topics of documents and the words used in those topics. It assumes each document is made up of several topics and similar topics use similar words. Like in bag of words, each word is considered independently of each other in the model." }, { "code": null, "e": 6923, "s": 6706, "text": "LDA can be very useful for large documents, such as news articles, in uncovering its high level themes. However, it wasn’t quite right for this data set as each food name isn’t necessarily made up of multiple topics." }, { "code": null, "e": 7073, "s": 6923, "text": "I tested for the optimal learning rate and number of topics to tell the model to find. Here is the result at 30 topics and the top 5 words per topic." }, { "code": null, "e": 7238, "s": 7073, "text": "It’s done exactly what it’s meant to do. We have patterns of words used together to describe our foods but they don’t illuminate the types of foods in our data set." }, { "code": null, "e": 7568, "s": 7238, "text": "Lastly, Fuzzywuzzy calculates a similarity score between two strings and is great for fuzzy (as opposed to exact) matching. This one was some outside-the-box thinking. My logic was that if food names of the same food type were worded slightly differently (eg: different kinds of apples), they would yield a high similarity score." }, { "code": null, "e": 7788, "s": 7568, "text": "Here I created a matrix of each food name and its similarity score with every other food name. I ended up with 1,534 rows (one for each food name) and 1,500 columns (one for each distinct food name after preprocessing)." }, { "code": null, "e": 7975, "s": 7788, "text": "Admittedly this was the slowest vectorisation method as it performed in-memory calculations for a 1,534 x 1,500 Pandas Dataframe. After clustering it performed similarly to bag of words." }, { "code": null, "e": 8047, "s": 7975, "text": "Keep reading in Part 2 to find out what the results of clustering were." }, { "code": null, "e": 8116, "s": 8047, "text": "This article is Part 1 and covered: Preprocessing and Vectorisation." }, { "code": null, "e": 8226, "s": 8116, "text": "Please keep reading in Part 2 which will cover: K-means Clustering, Assessing Cluster Quality and Finetuning." } ]
Cucumber - Environment
In this chapter, we will see the environment setup for Cucumber with Selenium WebDriver and Java, on Windows Machine. Following are the prerequisites required to set up with − Why we need − Java is a robust programming language. Cucumber supports Java platform for the execution. How to install − Step 1 − Download jdk and jre from the following link http://www.oracle.com/technetwork/java/javase/downloads/index.html Step 2 − Accept license agreement. Step 3 − Install JDK and JRE. Step 4 − Set the environment variable as shown in the following screenshots. Why we need − Eclipse is an Integrated Development Environment (IDE). It contains a base workspace and an extensible plug-in system for customizing the environment. How to install − Step 1 − Make sure JAVA is installed on your machine. Step 2 − Download Eclipse from https://eclipse.org/downloads/ Step 3 − Unzip and Eclipse is installed. Why we need − Maven is a build automation tool used primarily for Java projects. It provides a common platform to perform activities like generating source code, compiling code, packaging code to a jar, etc. Later if any of the software versions gets changed, Maven provides an easy way to modify the test project accordingly. How to install − Step 1 − Download Maven from the following link − https://maven.apache.org/download.cgi Step 2 − Unzip the file and remember the location. Step 3 − Create environment variable MAVEN_HOME as shown in the following screenshot. Step 4 − Edit Path variable and include Maven as shown in the following screenshot. Step 5 − Download MAVEN plugin from Eclipse. Step 6 − Open Eclipse. Step 7 − Go to Help → Eclipse Marketplace → Search Maven → Maven Integration for Eclipse → INSTALL. Step 1 − Create a Maven project. Go to File → New → Others → Maven → Maven Project → Next. Go to File → New → Others → Maven → Maven Project → Next. Provide group Id (group Id will identify your project uniquely across all projects). Provide group Id (group Id will identify your project uniquely across all projects). Provide artifact Id (artifact Id is the name of the jar without version. You can choose any name, which is in lowercase). Click on Finish. Provide artifact Id (artifact Id is the name of the jar without version. You can choose any name, which is in lowercase). Click on Finish. Step 2 − Open pom.xml. Go to package explorer on the left hand side of Eclipse. Go to package explorer on the left hand side of Eclipse. Expand the project CucumberTest. Expand the project CucumberTest. Locate pom.xml file. Locate pom.xml file. Right-click and select the option, open with “Text Editor”. Right-click and select the option, open with “Text Editor”. Step 3 − Add dependency for selenium: This will indicate Maven which Selenium jar files are to be downloaded from the central repository to the local repository. Open pom.xml is in the edit mode, create dependencies tag (<dependencies></dependencies>), inside the project tag. Open pom.xml is in the edit mode, create dependencies tag (<dependencies></dependencies>), inside the project tag. Inside the dependencies tag, create dependency tag (<dependency></dependency>). Inside the dependencies tag, create dependency tag (<dependency></dependency>). Provide the following information within the dependency tag. Provide the following information within the dependency tag. <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>2.47.1</version> </dependency> Step 4 − Add dependency for Cucumber-Java: This will indicate Maven, which Cucumber files are to be downloaded from the central repository to the local repository. Create one more dependency tag. Create one more dependency tag. Provide the following information within the dependency tag Provide the following information within the dependency tag <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-java</artifactId> <version>1.0.2</version> <scope>test</scope> </dependency> Step 5 − Add dependency for Cucumber-JUnit: This will indicate Maven, which Cucumber JUnit files are to be downloaded from the central repository to the local repository. Create one more dependency tag. Create one more dependency tag. Provide the following information within the dependency tag Provide the following information within the dependency tag <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-junit</artifactId> <version>1.0.2</version> <scope>test</scope> </dependency> Step 6 − Add dependency for JUnit: This will indicate Maven, which JUnit files are to be downloaded from the central repository to the local repository. Create one more dependency tag. Create one more dependency tag. Provide the following information within the dependency tag. Provide the following information within the dependency tag. <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> Step 7 − Verify binaries. Once pom.xml is edited successfully, save it. Once pom.xml is edited successfully, save it. Go to Project → Clean − It will take a few minutes. Go to Project → Clean − It will take a few minutes. You will be able to see a Maven repository like shown in the following screenshot. Create a feature file (to be covered later). Create a feature file (to be covered later). Create a step definition file (to be covered later). Create a step definition file (to be covered later). Create a JUnit runner to run the test (to be covered later). Create a JUnit runner to run the test (to be covered later). Print Add Notes Bookmark this page
[ { "code": null, "e": 2080, "s": 1962, "text": "In this chapter, we will see the environment setup for Cucumber with Selenium WebDriver and Java, on Windows Machine." }, { "code": null, "e": 2138, "s": 2080, "text": "Following are the prerequisites required to set up with −" }, { "code": null, "e": 2242, "s": 2138, "text": "Why we need − Java is a robust programming language. Cucumber supports Java platform for the execution." }, { "code": null, "e": 2259, "s": 2242, "text": "How to install −" }, { "code": null, "e": 2380, "s": 2259, "text": "Step 1 − Download jdk and jre from the following link http://www.oracle.com/technetwork/java/javase/downloads/index.html" }, { "code": null, "e": 2415, "s": 2380, "text": "Step 2 − Accept license agreement." }, { "code": null, "e": 2445, "s": 2415, "text": "Step 3 − Install JDK and JRE." }, { "code": null, "e": 2522, "s": 2445, "text": "Step 4 − Set the environment variable as shown in the following screenshots." }, { "code": null, "e": 2687, "s": 2522, "text": "Why we need − Eclipse is an Integrated Development Environment (IDE). It contains a base workspace and an extensible plug-in system for customizing the environment." }, { "code": null, "e": 2704, "s": 2687, "text": "How to install −" }, { "code": null, "e": 2758, "s": 2704, "text": "Step 1 − Make sure JAVA is installed on your machine." }, { "code": null, "e": 2820, "s": 2758, "text": "Step 2 − Download Eclipse from https://eclipse.org/downloads/" }, { "code": null, "e": 2861, "s": 2820, "text": "Step 3 − Unzip and Eclipse is installed." }, { "code": null, "e": 3188, "s": 2861, "text": "Why we need − Maven is a build automation tool used primarily for Java projects. It provides a common platform to perform activities like generating source code, compiling code, packaging code to a jar, etc. Later if any of the software versions gets changed, Maven provides an easy way to modify the test project accordingly." }, { "code": null, "e": 3205, "s": 3188, "text": "How to install −" }, { "code": null, "e": 3293, "s": 3205, "text": "Step 1 − Download Maven from the following link − https://maven.apache.org/download.cgi" }, { "code": null, "e": 3344, "s": 3293, "text": "Step 2 − Unzip the file and remember the location." }, { "code": null, "e": 3430, "s": 3344, "text": "Step 3 − Create environment variable MAVEN_HOME as shown in the following screenshot." }, { "code": null, "e": 3514, "s": 3430, "text": "Step 4 − Edit Path variable and include Maven as shown in the following screenshot." }, { "code": null, "e": 3559, "s": 3514, "text": "Step 5 − Download MAVEN plugin from Eclipse." }, { "code": null, "e": 3582, "s": 3559, "text": "Step 6 − Open Eclipse." }, { "code": null, "e": 3682, "s": 3582, "text": "Step 7 − Go to Help → Eclipse Marketplace → Search Maven → Maven Integration for Eclipse → INSTALL." }, { "code": null, "e": 3715, "s": 3682, "text": "Step 1 − Create a Maven project." }, { "code": null, "e": 3773, "s": 3715, "text": "Go to File → New → Others → Maven → Maven Project → Next." }, { "code": null, "e": 3831, "s": 3773, "text": "Go to File → New → Others → Maven → Maven Project → Next." }, { "code": null, "e": 3916, "s": 3831, "text": "Provide group Id (group Id will identify your project uniquely across all projects)." }, { "code": null, "e": 4001, "s": 3916, "text": "Provide group Id (group Id will identify your project uniquely across all projects)." }, { "code": null, "e": 4140, "s": 4001, "text": "Provide artifact Id (artifact Id is the name of the jar without version. You can choose any name, which is in lowercase). Click on Finish." }, { "code": null, "e": 4279, "s": 4140, "text": "Provide artifact Id (artifact Id is the name of the jar without version. You can choose any name, which is in lowercase). Click on Finish." }, { "code": null, "e": 4302, "s": 4279, "text": "Step 2 − Open pom.xml." }, { "code": null, "e": 4359, "s": 4302, "text": "Go to package explorer on the left hand side of Eclipse." }, { "code": null, "e": 4416, "s": 4359, "text": "Go to package explorer on the left hand side of Eclipse." }, { "code": null, "e": 4449, "s": 4416, "text": "Expand the project CucumberTest." }, { "code": null, "e": 4482, "s": 4449, "text": "Expand the project CucumberTest." }, { "code": null, "e": 4503, "s": 4482, "text": "Locate pom.xml file." }, { "code": null, "e": 4524, "s": 4503, "text": "Locate pom.xml file." }, { "code": null, "e": 4584, "s": 4524, "text": "Right-click and select the option, open with “Text Editor”." }, { "code": null, "e": 4644, "s": 4584, "text": "Right-click and select the option, open with “Text Editor”." }, { "code": null, "e": 4806, "s": 4644, "text": "Step 3 − Add dependency for selenium: This will indicate Maven which Selenium jar files are to be downloaded from the central repository to the local repository." }, { "code": null, "e": 4921, "s": 4806, "text": "Open pom.xml is in the edit mode, create dependencies tag (<dependencies></dependencies>), inside the project tag." }, { "code": null, "e": 5036, "s": 4921, "text": "Open pom.xml is in the edit mode, create dependencies tag (<dependencies></dependencies>), inside the project tag." }, { "code": null, "e": 5116, "s": 5036, "text": "Inside the dependencies tag, create dependency tag (<dependency></dependency>)." }, { "code": null, "e": 5196, "s": 5116, "text": "Inside the dependencies tag, create dependency tag (<dependency></dependency>)." }, { "code": null, "e": 5257, "s": 5196, "text": "Provide the following information within the dependency tag." }, { "code": null, "e": 5318, "s": 5257, "text": "Provide the following information within the dependency tag." }, { "code": null, "e": 5466, "s": 5318, "text": "<dependency> \n <groupId>org.seleniumhq.selenium</groupId> \n <artifactId>selenium-java</artifactId> \n <version>2.47.1</version> \n</dependency>" }, { "code": null, "e": 5630, "s": 5466, "text": "Step 4 − Add dependency for Cucumber-Java: This will indicate Maven, which Cucumber files are to be downloaded from the central repository to the local repository." }, { "code": null, "e": 5662, "s": 5630, "text": "Create one more dependency tag." }, { "code": null, "e": 5694, "s": 5662, "text": "Create one more dependency tag." }, { "code": null, "e": 5754, "s": 5694, "text": "Provide the following information within the dependency tag" }, { "code": null, "e": 5814, "s": 5754, "text": "Provide the following information within the dependency tag" }, { "code": null, "e": 5972, "s": 5814, "text": "<dependency> \n <groupId>info.cukes</groupId> \n <artifactId>cucumber-java</artifactId> \n <version>1.0.2</version> \n <scope>test</scope> \n</dependency>" }, { "code": null, "e": 6143, "s": 5972, "text": "Step 5 − Add dependency for Cucumber-JUnit: This will indicate Maven, which Cucumber JUnit files are to be downloaded from the central repository to the local repository." }, { "code": null, "e": 6175, "s": 6143, "text": "Create one more dependency tag." }, { "code": null, "e": 6207, "s": 6175, "text": "Create one more dependency tag." }, { "code": null, "e": 6267, "s": 6207, "text": "Provide the following information within the dependency tag" }, { "code": null, "e": 6327, "s": 6267, "text": "Provide the following information within the dependency tag" }, { "code": null, "e": 6486, "s": 6327, "text": "<dependency> \n <groupId>info.cukes</groupId> \n <artifactId>cucumber-junit</artifactId> \n <version>1.0.2</version> \n <scope>test</scope> \n</dependency>" }, { "code": null, "e": 6639, "s": 6486, "text": "Step 6 − Add dependency for JUnit: This will indicate Maven, which JUnit files are to be downloaded from the central repository to the local repository." }, { "code": null, "e": 6671, "s": 6639, "text": "Create one more dependency tag." }, { "code": null, "e": 6703, "s": 6671, "text": "Create one more dependency tag." }, { "code": null, "e": 6764, "s": 6703, "text": "Provide the following information within the dependency tag." }, { "code": null, "e": 6825, "s": 6764, "text": "Provide the following information within the dependency tag." }, { "code": null, "e": 6969, "s": 6825, "text": "<dependency> \n <groupId>junit</groupId> \n <artifactId>junit</artifactId> \n <version>4.10</version> \n <scope>test</scope> \n</dependency>" }, { "code": null, "e": 6995, "s": 6969, "text": "Step 7 − Verify binaries." }, { "code": null, "e": 7041, "s": 6995, "text": "Once pom.xml is edited successfully, save it." }, { "code": null, "e": 7087, "s": 7041, "text": "Once pom.xml is edited successfully, save it." }, { "code": null, "e": 7139, "s": 7087, "text": "Go to Project → Clean − It will take a few minutes." }, { "code": null, "e": 7191, "s": 7139, "text": "Go to Project → Clean − It will take a few minutes." }, { "code": null, "e": 7274, "s": 7191, "text": "You will be able to see a Maven repository like shown in the following screenshot." }, { "code": null, "e": 7319, "s": 7274, "text": "Create a feature file (to be covered later)." }, { "code": null, "e": 7364, "s": 7319, "text": "Create a feature file (to be covered later)." }, { "code": null, "e": 7417, "s": 7364, "text": "Create a step definition file (to be covered later)." }, { "code": null, "e": 7470, "s": 7417, "text": "Create a step definition file (to be covered later)." }, { "code": null, "e": 7531, "s": 7470, "text": "Create a JUnit runner to run the test (to be covered later)." }, { "code": null, "e": 7592, "s": 7531, "text": "Create a JUnit runner to run the test (to be covered later)." }, { "code": null, "e": 7599, "s": 7592, "text": " Print" }, { "code": null, "e": 7610, "s": 7599, "text": " Add Notes" } ]
How do I write class names in Java?
While writing class names you need to keep the following points in mind. You shouldn’t use predefined or existing class names as the name of the current class. You shouldn’t use any Java keywords as class name (with the same case). The First letter of the class name should be capital and remaining letters should be small (mixed case). class Sample Likewise, first letter of each word in the name should be capital an remaining letters should be small. class Test Keeping interface names simple and descriptive is suggestable. Better not to use acronyms while writing class names. Live Demo public class Test { public void sample() { System.out.println("This is sample method"); } public void demo() { System.out.println("This is demo method"); } public static void main(String args[]) { Test obj = new Test(); obj.sample(); obj.demo(); } } This is sample method This is demo method
[ { "code": null, "e": 1135, "s": 1062, "text": "While writing class names you need to keep the following points in mind." }, { "code": null, "e": 1222, "s": 1135, "text": "You shouldn’t use predefined or existing class names as the name of the current class." }, { "code": null, "e": 1294, "s": 1222, "text": "You shouldn’t use any Java keywords as class name (with the same case)." }, { "code": null, "e": 1399, "s": 1294, "text": "The First letter of the class name should be capital and remaining letters should be small (mixed case)." }, { "code": null, "e": 1413, "s": 1399, "text": "class Sample\n" }, { "code": null, "e": 1517, "s": 1413, "text": "Likewise, first letter of each word in the name should be capital an remaining letters should be small." }, { "code": null, "e": 1529, "s": 1517, "text": "class Test\n" }, { "code": null, "e": 1592, "s": 1529, "text": "Keeping interface names simple and descriptive is suggestable." }, { "code": null, "e": 1646, "s": 1592, "text": "Better not to use acronyms while writing class names." }, { "code": null, "e": 1657, "s": 1646, "text": " Live Demo" }, { "code": null, "e": 1961, "s": 1657, "text": "public class Test {\n public void sample() {\n System.out.println(\"This is sample method\"); \n }\n public void demo() {\n System.out.println(\"This is demo method\"); \n }\n public static void main(String args[]) {\n Test obj = new Test();\n obj.sample();\n obj.demo();\n }\n}" }, { "code": null, "e": 2004, "s": 1961, "text": "This is sample method\nThis is demo method\n" } ]
Using Prophet after COVID? Read this first. | by JZ Lu | Towards Data Science
Prophet is a procedure for forecasting time series data based on an additive model where non-linear trends are fit with yearly, weekly, and daily seasonality, plus holiday effects. It works best with time series that have strong seasonal effects and several seasons of historical data. Prophet is robust to missing data and shifts in the trend, and typically handles outliers well. By using a decomposable time series model, the Prophet model has three main components: y(t) = g(t) + s(t) + h(t) + e(t)g(t): trend functions that models non-periodic changes; s(t): seasonality functions that models periodic changes; i.e. weekly, monthly, yearly seasonality;h(t): holdiay function that represents the effects of potentially irregular scheduled holidays;e(t): error terms that represents changes that are not captured by the model; If you are new to Prophet and would like to learn more details about it, please check these awesome Medium articles (one, two, three) as well as the original publication that can give you a quick and deep start. Assuming you’ve played with Prophet models for a while and understand the fundamentals, this article covers 3 important advanced topics that you may come across sooner or later when modeling time series with Prophet after COVID-19. How to deal with COVID’s impact? Additive vs Multiplicative model? which one to choose? How to deal with non-daily data? COVID’s impact has penetrated into every aspect. If you’re dealing with time-series data, you probably have noticed some weird model performance after 2020. This is like to be driven by the impact that COVID has made on the trend and seasonality of your time-series data. There are several ways to deal with this problem. Models don’t have emotions. We could do a simple “trick” to let the model treat COVID as an event or “holiday”. The concept is straightforward. Just like during holiday shopping seasons where we will expect increasing shopping mall traffic, the model will treat COVID as a special “holiday” where it estimates decreasing shopping mall traffic. The codes below will do the work. COVID_lockdown = pd.DataFrame({ 'holiday': 'covid', 'ds': pd.date_range(start='2020-03-15', end='2020-05-01', freq='D'), 'lower_window': 0, 'upper_window': 0, 'prior_scale': 1 }) However, this method is tricky since there are so many external factors (state policy changes) that make the COVID “holiday” effect inconsistent over time and across different scenarios. This is the simplest method. Just drop 2020’s data or interpolate 2020’s data based on 2019’s data. However, as you could imagine, this method is very unreliable especially when you have short historical data. We still want to include real 2020 data to help the model learn the seasonalities. However, if your time-series data is generally stable year over year, and you think COVID doesn't play a role in your data anymore, this method is worth to be tested out. COVID may create a weekly seasonal pattern that is different during the pandemic/lock-down than it is after the pandemic. This method will allow you to train two separate seasonality patterns, which might be helpful for some time series data. However, during the experiments, I found this method yielded the worst model performance. So think again whether it makes sense to use two different seasonalities to model your data. #define pre and post covid perioddef is_postcovid_seasonality(ds): date = pd.to_datetime(ds) return date.date() >= pd.to_datetime('2021-03-15').date()dfprophet['pre_covid_seasonality']=~dfprophet['ds'].apply(is_postcovid_seasonality)dfprophet['post_covid_seasonality'] = dfprophet['ds'].apply(is_postcovid_seasonality)#add pre-covid and post-covid seasonality to the model base_model.add_seasonality(name='pre_covid_seasonality', period=7, fourier_order=3, condition_name='pre_covid_seasonality')base_model.add_seasonality(name='post_covid_seasonality', period=7, fourier_order=3, condition_name='post_covid_seasonality') This is probably the best approach to deal with COVID impact in many business scenarios. We will add external regressors such as mobility data here to help the model pick up COVID’s impact. Since those external regressors will greatly absorb COVID impact, it will minimize the impact of COVID on seasonality. Below are some public available indicators you could use. Consumer confidence index (CCI), Google mobility, COVID cases prediction #add a list of external regressorsregressors = ['CCI','google mobility','covid cases']for regressor in regressors: base_model = base_model.add_regressor(regressor, prior_scale=1, standardize='auto', mode='multiplicative') One thing to be aware of is that some of these indicators may only be temporarily available such as google mobility data, also it doesn’t provide forecast data. To leverage it, we may need to do our own predictions of these external regressors. Still, including these indicators will greatly improve model performance. And we may just need to revisit the model when COVID impact subsides and we have more stable time series data. This second topic also gets lots of questions and discussions. You may know that Prophet has two modes for seasonality and regressors, one is the additive mode (default), another is the multiplicative mode.With additive mode, seasonality/regressor is constant year over year; While, with multiplicative mode, the magnitude of seasonality/regressor is changing along with trend (see below chart). The formula of Prophet could be written as: df['yhat'] = df['trend'] * (1 + df['multiplicative_terms']) + df['additive_terms'] Since both seasonality and regressors have two modes, there are four combinations: yhat(t) = trend(t) + seasonality(t) + beta * regressor(t)meaning a unit increase in regressor will produce a beta increase in yhat. yhat(t) = trend(t) * (1 + seasonality(t) + beta * regressor(t))meaning a unit increase in regressor will produce a beta * trend increase in yhat. yhat(t) = trend(t) * (1 + beta * regressor) + seasonality(t)meaning a unit increase in regressor will produce a beta * trend increase in yhat. yhat(t) = trend(t) * (1 + beta * seasonality(t)) + regressor(t)meaning a unit increase in regressor will produce a unit increase in yhat. So before choosing additive or multiplicative mode, one question to ask — will one unit change in regressor always have a constant effect? or It will depend on the base of the trend. Normally, it makes more sense to use multiplicative mode, as we would imagine the magnitude of seasonality is aligned with the magnitude of trend. See this for more information. For example, a degree increase in temperature during summer must trigger more ice cream sales than a degree increase in temperature during winter. So under this situation, a multiplicative model makes much more sense. However, the rule is a little different because of COVID... Due to COVID impact, the 2020 number could be very low, so if we use multiplicative seasonality, the model will be misled by the low baseline and thinks that there is a big decrease in the magnitude of seasonality from 2019 to 2020, and then predicts that magnitude of 2021’s seasonality is even smaller than 2020’s. The model predictions could be seriously underestimated by using multiplicative. With the above said, it makes more sense to use additive seasonality during the pandemic so that it’s not biased by 2020’s abnormal baseline, especially when COVID greatly impacts your time series data. When we come out of the pandemic, we may need to revisit the model hyperparameters. Now, you may want to aggregate your data to a weekly or monthly level to offset the fluctuation introduced by COVID. There are many caveats when dealing with non-daily data in Prophet. Below I listed two fundamental ones: Although you have monthly or weekly aggregated data, the Prophet model doesn’t know this and is still fitting a continuous model and treating weekly or monthly data points as if they were single datapoint just on those particular days. Thus, those holidays that don’t fall on the particular dates used in the data will be ignored!!! For example, if you have monthly data, and each month is denoted by the first day of that month (01/01/2021, 02/01/2021, 03/01/2021), then if you want to include Christmas as a holiday event, you need to set Christmas day as of 12/01/2021 rather than 12/25/2021. To deal with this potential issue, we just need to move the holiday to the date that represents the week or month (see below codes). #Convert date to first day of monthdf['First_day_of_the_month'] =df['date'].to_numpy().astype('datetime64[M]')#Convert date to first day of week (sunday)df["First_day_of_the_week"] = df['Date'].apply(lambda x: (x - timedelta(days=x.dayofweek + 1)), axis = 1) In Prophet, you could set priors for trend, seasonality, holidays, and extra regressors. However, choosing the correct range of priors is not an easy task. For example, if the change in data is already captured by extra regressors, then the holiday effect could be simply wrong, e.g. if we use marketing spending as extra regressors to predict demand, we may surprisingly see Black Friday negatively impacting demand. This is because marketing spending already explained the majority variations of demand, which then led to an incorrect (counter-intuitive) effect of holidays. Another example is that if you increase holidays prior and decrease seasonality prior, then the model would prefer to use the holiday to explain the variations in data rather than seasonality. If you indeed want to use seasonality, you could set holidays prior to a very small number such as 0.00001 and set seasonality prior to a much large number such as 0.5. Of course, you could use a grid search method (see below code block) to tune hyperparameters if you aim for short-term accuracy. But in case you also care about explainability, you need to think about which is more impactful to the specific variations or changes, seasonality, holidays, or extra regressors, and relatively increase the prior for that component. # Pythonimport itertoolsparam_grid = { 'changepoint_prior_scale': [0.001, 0.01, 0.1, 0.5], 'seasonality_prior_scale': [0.01, 0.1, 1.0, 10.0],}# Generate all combinations of parametersall_params = [dict(zip(param_grid.keys(), v)) for v in itertools.product(*param_grid.values())]rmses = [] # Store the RMSEs for each params here# Use cross validation to evaluate all parametersfor params in all_params: m = Prophet(**params).fit(df) # Fit model with given params df_cv = cross_validation(m, cutoffs=cutoffs, horizon='30 days', parallel="processes") df_p = performance_metrics(df_cv, rolling_window=1) rmses.append(df_p['rmse'].values[0])# Find the best parameterstuning_results = pd.DataFrame(all_params)tuning_results['rmse'] = rmsesprint(tuning_results) I hope this article could help you gain insights on how to deal with COVID impact, how to choose additive vs multiplicative mode, and how to deal with non-daily data. These three topics have become particularly important and even a must-know when using Prophet after COVID-19. I’m also very interested in how you treat COVID’s impact in your model, feel free to comment below. Stay positive, thanks for reading! Taylor SJ, Letham B. 2017. Forecasting at scale. PeerJ Preprints 5:e3190v2 https://doi.org/10.7287/peerj.preprints.3190v2 Taylor SJ, Letham B. 2017. Forecasting at scale. PeerJ Preprints 5:e3190v2 https://doi.org/10.7287/peerj.preprints.3190v2
[ { "code": null, "e": 553, "s": 171, "text": "Prophet is a procedure for forecasting time series data based on an additive model where non-linear trends are fit with yearly, weekly, and daily seasonality, plus holiday effects. It works best with time series that have strong seasonal effects and several seasons of historical data. Prophet is robust to missing data and shifts in the trend, and typically handles outliers well." }, { "code": null, "e": 641, "s": 553, "text": "By using a decomposable time series model, the Prophet model has three main components:" }, { "code": null, "e": 1001, "s": 641, "text": "y(t) = g(t) + s(t) + h(t) + e(t)g(t): trend functions that models non-periodic changes; s(t): seasonality functions that models periodic changes; i.e. weekly, monthly, yearly seasonality;h(t): holdiay function that represents the effects of potentially irregular scheduled holidays;e(t): error terms that represents changes that are not captured by the model;" }, { "code": null, "e": 1445, "s": 1001, "text": "If you are new to Prophet and would like to learn more details about it, please check these awesome Medium articles (one, two, three) as well as the original publication that can give you a quick and deep start. Assuming you’ve played with Prophet models for a while and understand the fundamentals, this article covers 3 important advanced topics that you may come across sooner or later when modeling time series with Prophet after COVID-19." }, { "code": null, "e": 1478, "s": 1445, "text": "How to deal with COVID’s impact?" }, { "code": null, "e": 1533, "s": 1478, "text": "Additive vs Multiplicative model? which one to choose?" }, { "code": null, "e": 1566, "s": 1533, "text": "How to deal with non-daily data?" }, { "code": null, "e": 1888, "s": 1566, "text": "COVID’s impact has penetrated into every aspect. If you’re dealing with time-series data, you probably have noticed some weird model performance after 2020. This is like to be driven by the impact that COVID has made on the trend and seasonality of your time-series data. There are several ways to deal with this problem." }, { "code": null, "e": 2266, "s": 1888, "text": "Models don’t have emotions. We could do a simple “trick” to let the model treat COVID as an event or “holiday”. The concept is straightforward. Just like during holiday shopping seasons where we will expect increasing shopping mall traffic, the model will treat COVID as a special “holiday” where it estimates decreasing shopping mall traffic. The codes below will do the work." }, { "code": null, "e": 2546, "s": 2266, "text": "COVID_lockdown = pd.DataFrame({ 'holiday': 'covid', 'ds': pd.date_range(start='2020-03-15', end='2020-05-01', freq='D'), 'lower_window': 0, 'upper_window': 0, 'prior_scale': 1 })" }, { "code": null, "e": 2733, "s": 2546, "text": "However, this method is tricky since there are so many external factors (state policy changes) that make the COVID “holiday” effect inconsistent over time and across different scenarios." }, { "code": null, "e": 3197, "s": 2733, "text": "This is the simplest method. Just drop 2020’s data or interpolate 2020’s data based on 2019’s data. However, as you could imagine, this method is very unreliable especially when you have short historical data. We still want to include real 2020 data to help the model learn the seasonalities. However, if your time-series data is generally stable year over year, and you think COVID doesn't play a role in your data anymore, this method is worth to be tested out." }, { "code": null, "e": 3623, "s": 3197, "text": "COVID may create a weekly seasonal pattern that is different during the pandemic/lock-down than it is after the pandemic. This method will allow you to train two separate seasonality patterns, which might be helpful for some time series data. However, during the experiments, I found this method yielded the worst model performance. So think again whether it makes sense to use two different seasonalities to model your data." }, { "code": null, "e": 4267, "s": 3623, "text": "#define pre and post covid perioddef is_postcovid_seasonality(ds): date = pd.to_datetime(ds) return date.date() >= pd.to_datetime('2021-03-15').date()dfprophet['pre_covid_seasonality']=~dfprophet['ds'].apply(is_postcovid_seasonality)dfprophet['post_covid_seasonality'] = dfprophet['ds'].apply(is_postcovid_seasonality)#add pre-covid and post-covid seasonality to the model base_model.add_seasonality(name='pre_covid_seasonality', period=7, fourier_order=3, condition_name='pre_covid_seasonality')base_model.add_seasonality(name='post_covid_seasonality', period=7, fourier_order=3, condition_name='post_covid_seasonality')" }, { "code": null, "e": 4707, "s": 4267, "text": "This is probably the best approach to deal with COVID impact in many business scenarios. We will add external regressors such as mobility data here to help the model pick up COVID’s impact. Since those external regressors will greatly absorb COVID impact, it will minimize the impact of COVID on seasonality. Below are some public available indicators you could use. Consumer confidence index (CCI), Google mobility, COVID cases prediction" }, { "code": null, "e": 5041, "s": 4707, "text": "#add a list of external regressorsregressors = ['CCI','google mobility','covid cases']for regressor in regressors: base_model = base_model.add_regressor(regressor, prior_scale=1, standardize='auto', mode='multiplicative')" }, { "code": null, "e": 5471, "s": 5041, "text": "One thing to be aware of is that some of these indicators may only be temporarily available such as google mobility data, also it doesn’t provide forecast data. To leverage it, we may need to do our own predictions of these external regressors. Still, including these indicators will greatly improve model performance. And we may just need to revisit the model when COVID impact subsides and we have more stable time series data." }, { "code": null, "e": 5867, "s": 5471, "text": "This second topic also gets lots of questions and discussions. You may know that Prophet has two modes for seasonality and regressors, one is the additive mode (default), another is the multiplicative mode.With additive mode, seasonality/regressor is constant year over year; While, with multiplicative mode, the magnitude of seasonality/regressor is changing along with trend (see below chart)." }, { "code": null, "e": 5911, "s": 5867, "text": "The formula of Prophet could be written as:" }, { "code": null, "e": 5994, "s": 5911, "text": "df['yhat'] = df['trend'] * (1 + df['multiplicative_terms']) + df['additive_terms']" }, { "code": null, "e": 6077, "s": 5994, "text": "Since both seasonality and regressors have two modes, there are four combinations:" }, { "code": null, "e": 6209, "s": 6077, "text": "yhat(t) = trend(t) + seasonality(t) + beta * regressor(t)meaning a unit increase in regressor will produce a beta increase in yhat." }, { "code": null, "e": 6355, "s": 6209, "text": "yhat(t) = trend(t) * (1 + seasonality(t) + beta * regressor(t))meaning a unit increase in regressor will produce a beta * trend increase in yhat." }, { "code": null, "e": 6498, "s": 6355, "text": "yhat(t) = trend(t) * (1 + beta * regressor) + seasonality(t)meaning a unit increase in regressor will produce a beta * trend increase in yhat." }, { "code": null, "e": 6636, "s": 6498, "text": "yhat(t) = trend(t) * (1 + beta * seasonality(t)) + regressor(t)meaning a unit increase in regressor will produce a unit increase in yhat." }, { "code": null, "e": 6997, "s": 6636, "text": "So before choosing additive or multiplicative mode, one question to ask — will one unit change in regressor always have a constant effect? or It will depend on the base of the trend. Normally, it makes more sense to use multiplicative mode, as we would imagine the magnitude of seasonality is aligned with the magnitude of trend. See this for more information." }, { "code": null, "e": 7215, "s": 6997, "text": "For example, a degree increase in temperature during summer must trigger more ice cream sales than a degree increase in temperature during winter. So under this situation, a multiplicative model makes much more sense." }, { "code": null, "e": 7275, "s": 7215, "text": "However, the rule is a little different because of COVID..." }, { "code": null, "e": 7673, "s": 7275, "text": "Due to COVID impact, the 2020 number could be very low, so if we use multiplicative seasonality, the model will be misled by the low baseline and thinks that there is a big decrease in the magnitude of seasonality from 2019 to 2020, and then predicts that magnitude of 2021’s seasonality is even smaller than 2020’s. The model predictions could be seriously underestimated by using multiplicative." }, { "code": null, "e": 7960, "s": 7673, "text": "With the above said, it makes more sense to use additive seasonality during the pandemic so that it’s not biased by 2020’s abnormal baseline, especially when COVID greatly impacts your time series data. When we come out of the pandemic, we may need to revisit the model hyperparameters." }, { "code": null, "e": 8182, "s": 7960, "text": "Now, you may want to aggregate your data to a weekly or monthly level to offset the fluctuation introduced by COVID. There are many caveats when dealing with non-daily data in Prophet. Below I listed two fundamental ones:" }, { "code": null, "e": 8515, "s": 8182, "text": "Although you have monthly or weekly aggregated data, the Prophet model doesn’t know this and is still fitting a continuous model and treating weekly or monthly data points as if they were single datapoint just on those particular days. Thus, those holidays that don’t fall on the particular dates used in the data will be ignored!!!" }, { "code": null, "e": 8911, "s": 8515, "text": "For example, if you have monthly data, and each month is denoted by the first day of that month (01/01/2021, 02/01/2021, 03/01/2021), then if you want to include Christmas as a holiday event, you need to set Christmas day as of 12/01/2021 rather than 12/25/2021. To deal with this potential issue, we just need to move the holiday to the date that represents the week or month (see below codes)." }, { "code": null, "e": 9170, "s": 8911, "text": "#Convert date to first day of monthdf['First_day_of_the_month'] =df['date'].to_numpy().astype('datetime64[M]')#Convert date to first day of week (sunday)df[\"First_day_of_the_week\"] = df['Date'].apply(lambda x: (x - timedelta(days=x.dayofweek + 1)), axis = 1)" }, { "code": null, "e": 9326, "s": 9170, "text": "In Prophet, you could set priors for trend, seasonality, holidays, and extra regressors. However, choosing the correct range of priors is not an easy task." }, { "code": null, "e": 9747, "s": 9326, "text": "For example, if the change in data is already captured by extra regressors, then the holiday effect could be simply wrong, e.g. if we use marketing spending as extra regressors to predict demand, we may surprisingly see Black Friday negatively impacting demand. This is because marketing spending already explained the majority variations of demand, which then led to an incorrect (counter-intuitive) effect of holidays." }, { "code": null, "e": 10109, "s": 9747, "text": "Another example is that if you increase holidays prior and decrease seasonality prior, then the model would prefer to use the holiday to explain the variations in data rather than seasonality. If you indeed want to use seasonality, you could set holidays prior to a very small number such as 0.00001 and set seasonality prior to a much large number such as 0.5." }, { "code": null, "e": 10471, "s": 10109, "text": "Of course, you could use a grid search method (see below code block) to tune hyperparameters if you aim for short-term accuracy. But in case you also care about explainability, you need to think about which is more impactful to the specific variations or changes, seasonality, holidays, or extra regressors, and relatively increase the prior for that component." }, { "code": null, "e": 11248, "s": 10471, "text": "# Pythonimport itertoolsparam_grid = { 'changepoint_prior_scale': [0.001, 0.01, 0.1, 0.5], 'seasonality_prior_scale': [0.01, 0.1, 1.0, 10.0],}# Generate all combinations of parametersall_params = [dict(zip(param_grid.keys(), v)) for v in itertools.product(*param_grid.values())]rmses = [] # Store the RMSEs for each params here# Use cross validation to evaluate all parametersfor params in all_params: m = Prophet(**params).fit(df) # Fit model with given params df_cv = cross_validation(m, cutoffs=cutoffs, horizon='30 days', parallel=\"processes\") df_p = performance_metrics(df_cv, rolling_window=1) rmses.append(df_p['rmse'].values[0])# Find the best parameterstuning_results = pd.DataFrame(all_params)tuning_results['rmse'] = rmsesprint(tuning_results)" }, { "code": null, "e": 11525, "s": 11248, "text": "I hope this article could help you gain insights on how to deal with COVID impact, how to choose additive vs multiplicative mode, and how to deal with non-daily data. These three topics have become particularly important and even a must-know when using Prophet after COVID-19." }, { "code": null, "e": 11625, "s": 11525, "text": "I’m also very interested in how you treat COVID’s impact in your model, feel free to comment below." }, { "code": null, "e": 11660, "s": 11625, "text": "Stay positive, thanks for reading!" }, { "code": null, "e": 11782, "s": 11660, "text": "Taylor SJ, Letham B. 2017. Forecasting at scale. PeerJ Preprints 5:e3190v2 https://doi.org/10.7287/peerj.preprints.3190v2" } ]
Simple abstractive text summarization with pretrained T5 — Text-To-Text Transfer Transformer | by Ramsri Goutham | Towards Data Science
T5 is a new transformer model from Google that is trained in an end-to-end manner with text as input and modified text as output. You can read more about it here. It achieves state-of-the-art results on multiple NLP tasks like summarization, question answering, machine translation etc using a text-to-text transformer trained on a large text corpus. Today we will see how we can use huggingface’s transformers library to summarize any given text. T5 is an abstractive summarization algorithm. It means that it will rewrite sentences when necessary than just picking up sentences directly from the original text. Install these libraries in your jupyter notebook or conda environment before you begin : !pip install transformers==2.8.0!pip install torch==1.4.0 The US has "passed the peak" on new coronavirus cases, President Donald Trump said and predicted that some states would reopen this month.The US has over 637,000 confirmed Covid-19 cases and over 30,826 deaths, the highest for any country in the world.At the daily White House coronavirus briefing on Wednesday, Trump said new guidelines to reopen the country would be announced on Thursday after he speaks to governors."We'll be the comeback kids, all of us," he said. "We want to get our country back."The Trump administration has previously fixed May 1 as a possible date to reopen the world's largest economy, but the president said some states may be able to return to normalcy earlier than that. The us has over 637,000 confirmed Covid-19 cases and over 30,826 deaths. President Donald Trump predicts some states will reopen the country in april, he said. "we'll be the comeback kids, all of us," the president says. If you see the algorithm has intelligently summarized with mentioning April although it was never mentioned in the original story. It also replaced he with the president. Cut short and removed the extra information after the comma in the sentence “over 30,826 deaths ....” The same code inline as some users have reported that the Github Gist wasn’t loading : import torchimport json from transformers import T5Tokenizer, T5ForConditionalGeneration, T5Configmodel = T5ForConditionalGeneration.from_pretrained('t5-small')tokenizer = T5Tokenizer.from_pretrained('t5-small')device = torch.device('cpu')text ="""The US has "passed the peak" on new coronavirus cases, President Donald Trump said and predicted that some states would reopen this month.The US has over 637,000 confirmed Covid-19 cases and over 30,826 deaths, the highest for any country in the world.At the daily White House coronavirus briefing on Wednesday, Trump said new guidelines to reopen the country would be announced on Thursday after he speaks to governors."We'll be the comeback kids, all of us," he said. "We want to get our country back."The Trump administration has previously fixed May 1 as a possible date to reopen the world's largest economy, but the president said some states may be able to return to normalcy earlier than that."""preprocess_text = text.strip().replace("\n","")t5_prepared_Text = "summarize: "+preprocess_textprint ("original text preprocessed: \n", preprocess_text)tokenized_text = tokenizer.encode(t5_prepared_Text, return_tensors="pt").to(device)# summmarize summary_ids = model.generate(tokenized_text, num_beams=4, no_repeat_ngram_size=2, min_length=30, max_length=100, early_stopping=True)output = tokenizer.decode(summary_ids[0], skip_special_tokens=True)print ("\n\nSummarized text: \n",output)# Summarized output from above ::::::::::# the us has over 637,000 confirmed Covid-19 cases and over 30,826 deaths. # president Donald Trump predicts some states will reopen the country in april, he said. # "we'll be the comeback kids, all of us," the president says. The summarized output as mentioned above is - The us has over 637,000 confirmed Covid-19 cases and over 30,826 deaths. President Donald Trump predicts some states will reopen the country in april, he said. "we'll be the comeback kids, all of us," the president says. The key point to note in the code above is that we prepend our text with “summarize: ” before passing it to the T5 summarizer. If you look in the paper, all we need to do for other tasks is to prepend our text with their corresponding string eg: “translate English to German: ” for translation task. I am running a 4-week cohort-based course on “Practical Introduction to NLP” with Maven, the world’s best platform for cohort-based learning. If you wish to transform yourself from a Python developer to a junior NLP developer with practical project experience in 4 weeks, grab your spot now! I launched a very interesting Udemy course titled “Question generation using NLP” expanding on some of the techniques discussed in this blog post. If you would like to take a look at it, here is the link.
[ { "code": null, "e": 335, "s": 172, "text": "T5 is a new transformer model from Google that is trained in an end-to-end manner with text as input and modified text as output. You can read more about it here." }, { "code": null, "e": 523, "s": 335, "text": "It achieves state-of-the-art results on multiple NLP tasks like summarization, question answering, machine translation etc using a text-to-text transformer trained on a large text corpus." }, { "code": null, "e": 785, "s": 523, "text": "Today we will see how we can use huggingface’s transformers library to summarize any given text. T5 is an abstractive summarization algorithm. It means that it will rewrite sentences when necessary than just picking up sentences directly from the original text." }, { "code": null, "e": 874, "s": 785, "text": "Install these libraries in your jupyter notebook or conda environment before you begin :" }, { "code": null, "e": 932, "s": 874, "text": "!pip install transformers==2.8.0!pip install torch==1.4.0" }, { "code": null, "e": 1634, "s": 932, "text": "The US has \"passed the peak\" on new coronavirus cases, President Donald Trump said and predicted that some states would reopen this month.The US has over 637,000 confirmed Covid-19 cases and over 30,826 deaths, the highest for any country in the world.At the daily White House coronavirus briefing on Wednesday, Trump said new guidelines to reopen the country would be announced on Thursday after he speaks to governors.\"We'll be the comeback kids, all of us,\" he said. \"We want to get our country back.\"The Trump administration has previously fixed May 1 as a possible date to reopen the world's largest economy, but the president said some states may be able to return to normalcy earlier than that." }, { "code": null, "e": 1855, "s": 1634, "text": "The us has over 637,000 confirmed Covid-19 cases and over 30,826 deaths. President Donald Trump predicts some states will reopen the country in april, he said. \"we'll be the comeback kids, all of us,\" the president says." }, { "code": null, "e": 2128, "s": 1855, "text": "If you see the algorithm has intelligently summarized with mentioning April although it was never mentioned in the original story. It also replaced he with the president. Cut short and removed the extra information after the comma in the sentence “over 30,826 deaths ....”" }, { "code": null, "e": 2215, "s": 2128, "text": "The same code inline as some users have reported that the Github Gist wasn’t loading :" }, { "code": null, "e": 4098, "s": 2215, "text": "import torchimport json from transformers import T5Tokenizer, T5ForConditionalGeneration, T5Configmodel = T5ForConditionalGeneration.from_pretrained('t5-small')tokenizer = T5Tokenizer.from_pretrained('t5-small')device = torch.device('cpu')text =\"\"\"The US has \"passed the peak\" on new coronavirus cases, President Donald Trump said and predicted that some states would reopen this month.The US has over 637,000 confirmed Covid-19 cases and over 30,826 deaths, the highest for any country in the world.At the daily White House coronavirus briefing on Wednesday, Trump said new guidelines to reopen the country would be announced on Thursday after he speaks to governors.\"We'll be the comeback kids, all of us,\" he said. \"We want to get our country back.\"The Trump administration has previously fixed May 1 as a possible date to reopen the world's largest economy, but the president said some states may be able to return to normalcy earlier than that.\"\"\"preprocess_text = text.strip().replace(\"\\n\",\"\")t5_prepared_Text = \"summarize: \"+preprocess_textprint (\"original text preprocessed: \\n\", preprocess_text)tokenized_text = tokenizer.encode(t5_prepared_Text, return_tensors=\"pt\").to(device)# summmarize summary_ids = model.generate(tokenized_text, num_beams=4, no_repeat_ngram_size=2, min_length=30, max_length=100, early_stopping=True)output = tokenizer.decode(summary_ids[0], skip_special_tokens=True)print (\"\\n\\nSummarized text: \\n\",output)# Summarized output from above ::::::::::# the us has over 637,000 confirmed Covid-19 cases and over 30,826 deaths. # president Donald Trump predicts some states will reopen the country in april, he said. # \"we'll be the comeback kids, all of us,\" the president says." }, { "code": null, "e": 4144, "s": 4098, "text": "The summarized output as mentioned above is -" }, { "code": null, "e": 4365, "s": 4144, "text": "The us has over 637,000 confirmed Covid-19 cases and over 30,826 deaths. President Donald Trump predicts some states will reopen the country in april, he said. \"we'll be the comeback kids, all of us,\" the president says." }, { "code": null, "e": 4492, "s": 4365, "text": "The key point to note in the code above is that we prepend our text with “summarize: ” before passing it to the T5 summarizer." }, { "code": null, "e": 4665, "s": 4492, "text": "If you look in the paper, all we need to do for other tasks is to prepend our text with their corresponding string eg: “translate English to German: ” for translation task." }, { "code": null, "e": 4957, "s": 4665, "text": "I am running a 4-week cohort-based course on “Practical Introduction to NLP” with Maven, the world’s best platform for cohort-based learning. If you wish to transform yourself from a Python developer to a junior NLP developer with practical project experience in 4 weeks, grab your spot now!" } ]
ASP.NET MVC - Data Model
In this chapter, we will discuss about building models in an ASP.NET MVC Framework application. A model stores data that is retrieved according to the commands from the Controller and displayed in the View. Model is a collection of classes wherein you will be working with data and business logic. Hence, basically models are business domain-specific containers. It is used to interact with database. It can also be used to manipulate the data to implement the business logic. Let’s take a look at a simple example of Model by creating a new ASP.Net MVC project. Step 1 − Open the Visual Studio. Click File → New → Project menu option. A new Project dialog opens. Step 2 − From the left pane, select Templates → Visual C# → Web. Step 3 − In the middle pane, select ASP.NET Web Application. Step 4 − Enter the project name ‘MVCSimpleApp’ in the Name field and click Ok to continue. You will see the following dialog which asks you to set the initial content for the ASP.NET project. Step 5 − To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add folders and core references for’ section and click Ok. It will create a basic MVC project with minimal predefined content. We need to add a controller now. Step 6 − Right-click on the controller folder in the solution explorer and select Add → Controller. It will display the Add Scaffold dialog. Step 7 − Select the MVC 5 Controller – with read/write actions option. This template will create an Index method with default action for Controller. This will also list other methods like Edit/Delete/Create as well. Step 8 − Click ‘Add’ button and Add Controller dialog will appear. Step 9 − Set the name to EmployeeController and click the ‘Add’ button. Step 10 − You will see a new C# file ‘EmployeeController.cs’ in the Controllers folder, which is open for editing in Visual Studio with some default actions. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCSimpleApp.Controllers { public class EmployeeController : Controller{ // GET: Employee public ActionResult Index(){ return View(); } // GET: Employee/Details/5 public ActionResult Details(int id){ return View(); } // GET: Employee/Create public ActionResult Create(){ return View(); } // POST: Employee/Create [HttpPost] public ActionResult Create(FormCollection collection){ try{ // TODO: Add insert logic here return RedirectToAction("Index"); }catch{ return View(); } } // GET: Employee/Edit/5 public ActionResult Edit(int id){ return View(); } // POST: Employee/Edit/5 [HttpPost] public ActionResult Edit(int id, FormCollection collection){ try{ // TODO: Add update logic here return RedirectToAction("Index"); }catch{ return View(); } } // GET: Employee/Delete/5 public ActionResult Delete(int id){ return View(); } // POST: Employee/Delete/5 [HttpPost] public ActionResult Delete(int id, FormCollection collection){ try{ // TODO: Add delete logic here return RedirectToAction("Index"); }catch{ return View(); } } } } Let’s add a model. Step 11 − Right-click on the Models folder in the solution explorer and select Add → Class. You will see the Add New Item dialog. Step 12 − Select Class in the middle pan and enter Employee.cs in the name field. Step 13 − Add some properties to Employee class using the following code. using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MVCSimpleApp.Models { public class Employee{ public int ID { get; set; } public string Name { get; set; } public DateTime JoiningDate { get; set; } public int Age { get; set; } } } Let’s update the EmployeeController.cs file by adding one more method, which will return the list of employee. [NonAction] public List<Employee> GetEmployeeList(){ return new List<Employee>{ new Employee{ ID = 1, Name = "Allan", JoiningDate = DateTime.Parse(DateTime.Today.ToString()), Age = 23 }, new Employee{ ID = 2, Name = "Carson", JoiningDate = DateTime.Parse(DateTime.Today.ToString()), Age = 45 }, new Employee{ ID = 3, Name = "Carson", JoiningDate = DateTime.Parse(DateTime.Today.ToString()), Age = 37 }, new Employee{ ID = 4, Name = "Laura", JoiningDate = DateTime.Parse(DateTime.Today.ToString()), Age = 26 }, }; } Step 14 − Update the index action method as shown in the following code. public ActionResult Index(){ var employees = from e in GetEmployeeList() orderby e.ID select e; return View(employees); } Step 15 − Run this application and append /employee to the URL in the browser and press Enter. You will see the following output. As seen in the above screenshot, there is an error and this error is actually quite descriptive which tells us it can't find the Index view. Step 16 − Hence to add a view, right-click inside the Index action and select Add view. It will display the Add View dialog and it is going to add the default name. Step 17 − Select the List from the Template dropdown and Employee in Model class dropdown and also uncheck the ‘Use a layout page’ checkbox and click ‘Add’ button. It will add some default code for you in this view. @model IEnumerable<MVCSimpleApp.Models.Employee> @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name = "viewport" content = "width = device-width" /> <title>Index</title> </head> <body> <p>@Html.ActionLink("Create New", "Create")</p> <table class = "table"> <tr> <th> @Html.DisplayNameFor(model => model.Name) </th> <th> @Html.DisplayNameFor(model => model.JoiningDate) </th> <th> @Html.DisplayNameFor(model => model.Age) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.JoiningDate) </td> <td> @Html.DisplayFor(modelItem => item.Age) </td> <td> @Html.ActionLink("Edit", "Edit", new { id = item.ID }) | @Html.ActionLink("Details", "Details", new { id = item.ID }) | @Html.ActionLink("Delete", "Delete", new { id = item.ID }) </td> </tr> } </table> </body> </html> Step 18 − Run this application and you will receive the following output. A list of employees will be displayed. 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2476, "s": 2269, "text": "In this chapter, we will discuss about building models in an ASP.NET MVC Framework application. A model stores data that is retrieved according to the commands from the Controller and displayed in the View." }, { "code": null, "e": 2746, "s": 2476, "text": "Model is a collection of classes wherein you will be working with data and business logic. Hence, basically models are business domain-specific containers. It is used to interact with database. It can also be used to manipulate the data to implement the business logic." }, { "code": null, "e": 2832, "s": 2746, "text": "Let’s take a look at a simple example of Model by creating a new ASP.Net MVC project." }, { "code": null, "e": 2905, "s": 2832, "text": "Step 1 − Open the Visual Studio. Click File → New → Project menu option." }, { "code": null, "e": 2933, "s": 2905, "text": "A new Project dialog opens." }, { "code": null, "e": 2998, "s": 2933, "text": "Step 2 − From the left pane, select Templates → Visual C# → Web." }, { "code": null, "e": 3059, "s": 2998, "text": "Step 3 − In the middle pane, select ASP.NET Web Application." }, { "code": null, "e": 3251, "s": 3059, "text": "Step 4 − Enter the project name ‘MVCSimpleApp’ in the Name field and click Ok to continue. You will see the following dialog which asks you to set the initial content for the ASP.NET project." }, { "code": null, "e": 3401, "s": 3251, "text": "Step 5 − To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add folders and core references for’ section and click Ok." }, { "code": null, "e": 3469, "s": 3401, "text": "It will create a basic MVC project with minimal predefined content." }, { "code": null, "e": 3502, "s": 3469, "text": "We need to add a controller now." }, { "code": null, "e": 3602, "s": 3502, "text": "Step 6 − Right-click on the controller folder in the solution explorer and select Add → Controller." }, { "code": null, "e": 3643, "s": 3602, "text": "It will display the Add Scaffold dialog." }, { "code": null, "e": 3859, "s": 3643, "text": "Step 7 − Select the MVC 5 Controller – with read/write actions option. This template will create an Index method with default action for Controller. This will also list other methods like Edit/Delete/Create as well." }, { "code": null, "e": 3926, "s": 3859, "text": "Step 8 − Click ‘Add’ button and Add Controller dialog will appear." }, { "code": null, "e": 3998, "s": 3926, "text": "Step 9 − Set the name to EmployeeController and click the ‘Add’ button." }, { "code": null, "e": 4156, "s": 3998, "text": "Step 10 − You will see a new C# file ‘EmployeeController.cs’ in the Controllers folder, which is open for editing in Visual Studio with some default actions." }, { "code": null, "e": 5724, "s": 4156, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCSimpleApp.Controllers {\n public class EmployeeController : Controller{\n // GET: Employee\n public ActionResult Index(){\n return View();\n }\n\t\t\n // GET: Employee/Details/5\n public ActionResult Details(int id){\n return View();\n }\n\t\t\n // GET: Employee/Create\n public ActionResult Create(){\n return View();\n }\n\t\t\n // POST: Employee/Create\n [HttpPost]\n public ActionResult Create(FormCollection collection){\n try{\n // TODO: Add insert logic here\n return RedirectToAction(\"Index\");\n }catch{\n return View();\n }\n }\n\t\t\n // GET: Employee/Edit/5\n public ActionResult Edit(int id){\n return View();\n }\n\t\t\n // POST: Employee/Edit/5\n [HttpPost]\n public ActionResult Edit(int id, FormCollection collection){\n try{\n // TODO: Add update logic here\n return RedirectToAction(\"Index\");\n }catch{\n return View();\n }\n }\n\t\t\n // GET: Employee/Delete/5\n public ActionResult Delete(int id){\n return View();\n }\n\t\t\n // POST: Employee/Delete/5\n [HttpPost]\n public ActionResult Delete(int id, FormCollection collection){\n try{\n // TODO: Add delete logic here\n return RedirectToAction(\"Index\");\n }catch{\n return View();\n }\n }\n }\n}" }, { "code": null, "e": 5743, "s": 5724, "text": "Let’s add a model." }, { "code": null, "e": 5835, "s": 5743, "text": "Step 11 − Right-click on the Models folder in the solution explorer and select Add → Class." }, { "code": null, "e": 5873, "s": 5835, "text": "You will see the Add New Item dialog." }, { "code": null, "e": 5955, "s": 5873, "text": "Step 12 − Select Class in the middle pan and enter Employee.cs in the name field." }, { "code": null, "e": 6029, "s": 5955, "text": "Step 13 − Add some properties to Employee class using the following code." }, { "code": null, "e": 6336, "s": 6029, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\n\nnamespace MVCSimpleApp.Models {\n public class Employee{\n public int ID { get; set; }\n public string Name { get; set; }\n public DateTime JoiningDate { get; set; }\n public int Age { get; set; }\n }\n}" }, { "code": null, "e": 6447, "s": 6336, "text": "Let’s update the EmployeeController.cs file by adding one more method, which will return the list of employee." }, { "code": null, "e": 7169, "s": 6447, "text": "[NonAction]\npublic List<Employee> GetEmployeeList(){\n return new List<Employee>{\n new Employee{\n ID = 1,\n Name = \"Allan\",\n JoiningDate = DateTime.Parse(DateTime.Today.ToString()),\n Age = 23\n },\n\t\t\n new Employee{\n ID = 2,\n Name = \"Carson\",\n JoiningDate = DateTime.Parse(DateTime.Today.ToString()),\n Age = 45\n },\n\t\t\n new Employee{\n ID = 3,\n Name = \"Carson\",\n JoiningDate = DateTime.Parse(DateTime.Today.ToString()),\n Age = 37\n },\n\t\t\n new Employee{\n ID = 4,\n Name = \"Laura\",\n JoiningDate = DateTime.Parse(DateTime.Today.ToString()),\n Age = 26\n },\n };\n}" }, { "code": null, "e": 7242, "s": 7169, "text": "Step 14 − Update the index action method as shown in the following code." }, { "code": null, "e": 7376, "s": 7242, "text": "public ActionResult Index(){\n var employees = from e in GetEmployeeList()\n orderby e.ID\n select e;\n return View(employees);\n}" }, { "code": null, "e": 7506, "s": 7376, "text": "Step 15 − Run this application and append /employee to the URL in the browser and press Enter. You will see the following output." }, { "code": null, "e": 7647, "s": 7506, "text": "As seen in the above screenshot, there is an error and this error is actually quite descriptive which tells us it can't find the Index view." }, { "code": null, "e": 7735, "s": 7647, "text": "Step 16 − Hence to add a view, right-click inside the Index action and select Add view." }, { "code": null, "e": 7812, "s": 7735, "text": "It will display the Add View dialog and it is going to add the default name." }, { "code": null, "e": 7976, "s": 7812, "text": "Step 17 − Select the List from the Template dropdown and Employee in Model class dropdown and also uncheck the ‘Use a layout page’ checkbox and click ‘Add’ button." }, { "code": null, "e": 8028, "s": 7976, "text": "It will add some default code for you in this view." }, { "code": null, "e": 9417, "s": 8028, "text": "@model IEnumerable<MVCSimpleApp.Models.Employee>\n@{\n Layout = null;\n}\n\n<!DOCTYPE html>\n<html>\n <head>\n <meta name = \"viewport\" content = \"width = device-width\" />\n <title>Index</title>\n </head>\n\t\n <body>\n <p>@Html.ActionLink(\"Create New\", \"Create\")</p>\n <table class = \"table\">\n <tr>\n <th>\n @Html.DisplayNameFor(model => model.Name)\n </th>\n\t\t\t\t\n <th>\n @Html.DisplayNameFor(model => model.JoiningDate)\n </th>\n\t\t\t\t\n <th>\n @Html.DisplayNameFor(model => model.Age)\n </th>\n\t\t\t\t\n <th></th>\n </tr>\n\t\t\t\n @foreach (var item in Model) {\n <tr>\n <td>\n @Html.DisplayFor(modelItem => item.Name)\n </td>\n\t\t\t\t\t\n <td>\n @Html.DisplayFor(modelItem => item.JoiningDate)\n </td>\n\t\t\t\t\t\n <td>\n @Html.DisplayFor(modelItem => item.Age)\n </td>\n\t\t\t\t\t\n <td>\n @Html.ActionLink(\"Edit\", \"Edit\", new { id = item.ID }) |\n @Html.ActionLink(\"Details\", \"Details\", new { id = item.ID }) |\n @Html.ActionLink(\"Delete\", \"Delete\", new { id = item.ID })\n </td>\n\t\t\t\t\t\n </tr>\n }\n\t\t\t\n </table>\n </body>\n</html>" }, { "code": null, "e": 9491, "s": 9417, "text": "Step 18 − Run this application and you will receive the following output." }, { "code": null, "e": 9530, "s": 9491, "text": "A list of employees will be displayed." }, { "code": null, "e": 9565, "s": 9530, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9579, "s": 9565, "text": " Anadi Sharma" }, { "code": null, "e": 9614, "s": 9579, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9637, "s": 9614, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 9671, "s": 9637, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 9691, "s": 9671, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 9726, "s": 9691, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 9743, "s": 9726, "text": " University Code" }, { "code": null, "e": 9778, "s": 9743, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9795, "s": 9778, "text": " University Code" }, { "code": null, "e": 9829, "s": 9795, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 9844, "s": 9829, "text": " Bhrugen Patel" }, { "code": null, "e": 9851, "s": 9844, "text": " Print" }, { "code": null, "e": 9862, "s": 9851, "text": " Add Notes" } ]
COBOL - Data Layout
COBOL layout is the description of use of each field and the values present in it. Following are the data description entries used in COBOL − Redefines Clause Renames Clause Usage Clause Copybooks Redefines clause is used to define a storage with different data description. If one or more data items are not used simultaneously, then the same storage can be utilized for another data item. So the same storage can be referred with different data items. Following is the syntax for Redefines clause − 01 WS-OLD PIC X(10). 01 WS-NEW1 REDEFINES WS-OLD PIC 9(8). 01 WS-NEW2 REDEFINES WS-OLD PIC A(10). Following are the details of the used parameters − WS-OLD is Redefined Item WS-NEW1 and WS-NEW2 are Redefining Item Level numbers of redefined item and redefining item must be the same and it cannot be 66 or 88 level number. Do not use VALUE clause with a redefining item. In File Section, do not use a redefines clause with 01 level number. Redefines definition must be the next data description you want to redefine. A redefining item will always have the same value as a redefined item. Example IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-DESCRIPTION. 05 WS-DATE1 VALUE '20140831'. 10 WS-YEAR PIC X(4). 10 WS-MONTH PIC X(2). 10 WS-DATE PIC X(2). 05 WS-DATE2 REDEFINES WS-DATE1 PIC 9(8). PROCEDURE DIVISION. DISPLAY "WS-DATE1 : "WS-DATE1. DISPLAY "WS-DATE2 : "WS-DATE2. STOP RUN. JCL to execute the above COBOL program − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program it produces the following result − WS-DATE1 : 20140831 WS-DATE2 : 20140831 Renames clause is used to give different names to existing data items. It is used to re-group the data names and give a new name to them. The new data names can rename across groups or elementary items. Level number 66 is reserved for renames. Syntax Following is the syntax for Renames clause − 01 WS-OLD. 10 WS-A PIC 9(12). 10 WS-B PIC X(20). 10 WS-C PIC A(25). 10 WS-D PIC X(12). 66 WS-NEW RENAMES WS-A THRU WS-C. Renaming is possible at same level only. In the above example, WS-A, WS-B, and WS-C are at the same level. Renames definition must be the next data description you want to rename. Do not use Renames with the level numbers 01 or, 77. The data names used for renames must come in sequence. Data items with occur clause cannot be renamed. Example IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-DESCRIPTION. 05 WS-NUM. 10 WS-NUM1 PIC 9(2) VALUE 20. 10 WS-NUM2 PIC 9(2) VALUE 56. 05 WS-CHAR. 10 WS-CHAR1 PIC X(2) VALUE 'AA'. 10 WS-CHAR2 PIC X(2) VALUE 'BB'. 66 WS-RENAME RENAMES WS-NUM2 THRU WS-CHAR2. PROCEDURE DIVISION. DISPLAY "WS-RENAME : " WS-RENAME. STOP RUN. JCL to execute the above COBOL program − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result − WS-RENAME : 56AABB Usage clause specifies the operating system in which the format data is stored. It cannot be used with level numbers 66 or 88. If usage clause is specified on a group, then all the elementary items will have the same usage clause. The different options available with Usage clause are as follows − Data item is stored in ASCII format and each character will take 1 byte. It is default usage. The following example calculates the number of bytes required − 01 WS-NUM PIC S9(5)V9(3) USAGE IS DISPLAY. It requires 8 bytes as sign and decimal doesn't require any byte. 01 WS-NUM PIC 9(5) USAGE IS DISPLAY. It requires 5 bytes as sign. Data item is stored in binary format. Here, data items must be integer. The following example calculates the number of bytes required − 01 WS-NUM PIC S9(n) USAGE IS COMP. If 'n' = 1 to 4, it takes 2 bytes. If 'n' = 5 to 9, it takes 4 bytes. If 'n' = 10 to 18, it takes 8 bytes. Data item is similar to Real or Float and is represented as a single precision floating point number. Internally, data is stored in hexadecimal format. COMP-1 does not accept PIC clause. Here 1 word is equal to 4 bytes. Data item is similar to Long or Double and is represented as double precision floating point number. Internally, data is stored in hexadecimal format. COMP-2 does not specify PIC clause. Here 2 word is equal to 8 bytes. Data item is stored in packed decimal format. Each digit occupies half a byte (1 nibble) and the sign is stored at the rightmost nibble. The following example calculates the number of bytes required − 01 WS-NUM PIC 9(n) USAGE IS COMP. Number of bytes = n/2 (If n is even) Number of bytes = n/2 + 1(If n is odd, consider only integer part) 01 WS-NUM PIC 9(4) USAGE IS COMP-3 VALUE 21. It requires 2 bytes of storage as each digit occupies half a byte. 01 WS-NUM PIC 9(5) USAGE IS COMP-3 VALUE 21. It requires 3 bytes of storage as each digit occupies half a byte. A COBOL copybook is a selection of code that defines data structures. If a particular data structure is used in many programs, then instead of writing the same data structure again, we can use copybooks. We use the COPY statement to include a copybook in a program. COPY statement is used in the WorkingStorage Section. The following example includes a copybook inside a COBOL program − DATA DIVISION. WORKING-STORAGE SECTION. COPY ABC. Here ABC is the copybook name. The following data items in ABC copybook can be used inside a program. 01 WS-DESCRIPTION. 05 WS-NUM. 10 WS-NUM1 PIC 9(2) VALUE 20. 10 WS-NUM2 PIC 9(2) VALUE 56. 05 WS-CHAR. 10 WS-CHAR1 PIC X(2) VALUE 'AA'. 10 WS-CHAR2 PIC X(2) VALUE 'BB'. 12 Lectures 2.5 hours Nishant Malik 33 Lectures 3.5 hours Craig Kenneth Kaercher Print Add Notes Bookmark this page
[ { "code": null, "e": 2164, "s": 2022, "text": "COBOL layout is the description of use of each field and the values present in it. Following are the data description entries used in COBOL −" }, { "code": null, "e": 2181, "s": 2164, "text": "Redefines Clause" }, { "code": null, "e": 2196, "s": 2181, "text": "Renames Clause" }, { "code": null, "e": 2209, "s": 2196, "text": "Usage Clause" }, { "code": null, "e": 2219, "s": 2209, "text": "Copybooks" }, { "code": null, "e": 2476, "s": 2219, "text": "Redefines clause is used to define a storage with different data description. If one or more data items are not used simultaneously, then the same storage can be utilized for another data item. So the same storage can be referred with different data items." }, { "code": null, "e": 2523, "s": 2476, "text": "Following is the syntax for Redefines clause −" }, { "code": null, "e": 2622, "s": 2523, "text": "01 WS-OLD PIC X(10).\n01 WS-NEW1 REDEFINES WS-OLD PIC 9(8).\n01 WS-NEW2 REDEFINES WS-OLD PIC A(10).\n" }, { "code": null, "e": 2673, "s": 2622, "text": "Following are the details of the used parameters −" }, { "code": null, "e": 2698, "s": 2673, "text": "WS-OLD is Redefined Item" }, { "code": null, "e": 2738, "s": 2698, "text": "WS-NEW1 and WS-NEW2 are Redefining Item" }, { "code": null, "e": 3112, "s": 2738, "text": "Level numbers of redefined item and redefining item must be the same and it cannot be 66 or 88 level number. Do not use VALUE clause with a redefining item. In File Section, do not use a redefines clause with 01 level number. Redefines definition must be the next data description you want to redefine. A redefining item will always have the same value as a redefined item." }, { "code": null, "e": 3120, "s": 3112, "text": "Example" }, { "code": null, "e": 3480, "s": 3120, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-DESCRIPTION.\n 05 WS-DATE1 VALUE '20140831'.\n 10 WS-YEAR PIC X(4).\n 10 WS-MONTH PIC X(2).\n 10 WS-DATE PIC X(2).\n 05 WS-DATE2 REDEFINES WS-DATE1 PIC 9(8).\n\nPROCEDURE DIVISION.\n DISPLAY \"WS-DATE1 : \"WS-DATE1.\n DISPLAY \"WS-DATE2 : \"WS-DATE2.\n\nSTOP RUN." }, { "code": null, "e": 3521, "s": 3480, "text": "JCL to execute the above COBOL program −" }, { "code": null, "e": 3598, "s": 3521, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" }, { "code": null, "e": 3680, "s": 3598, "text": "When you compile and execute the above program it produces the following result −" }, { "code": null, "e": 3721, "s": 3680, "text": "WS-DATE1 : 20140831\nWS-DATE2 : 20140831\n" }, { "code": null, "e": 3965, "s": 3721, "text": "Renames clause is used to give different names to existing data items. It is used to re-group the data names and give a new name to them. The new data names can rename across groups or elementary items. Level number 66 is reserved for renames." }, { "code": null, "e": 3972, "s": 3965, "text": "Syntax" }, { "code": null, "e": 4017, "s": 3972, "text": "Following is the syntax for Renames clause −" }, { "code": null, "e": 4139, "s": 4017, "text": "01 WS-OLD.\n10 WS-A PIC 9(12).\n10 WS-B PIC X(20).\n10 WS-C PIC A(25).\n10 WS-D PIC X(12).\n66 WS-NEW RENAMES WS-A THRU WS-C.\n" }, { "code": null, "e": 4475, "s": 4139, "text": "Renaming is possible at same level only. In the above example, WS-A, WS-B, and WS-C are at the same level. Renames definition must be the next data description you want to rename. Do not use Renames with the level numbers 01 or, 77. The data names used for renames must come in sequence. Data items with occur clause cannot be renamed." }, { "code": null, "e": 4483, "s": 4475, "text": "Example" }, { "code": null, "e": 4879, "s": 4483, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-DESCRIPTION.\n 05 WS-NUM.\n 10 WS-NUM1 PIC 9(2) VALUE 20.\n 10 WS-NUM2 PIC 9(2) VALUE 56.\n 05 WS-CHAR.\n 10 WS-CHAR1 PIC X(2) VALUE 'AA'.\n 10 WS-CHAR2 PIC X(2) VALUE 'BB'.\n 66 WS-RENAME RENAMES WS-NUM2 THRU WS-CHAR2.\n\nPROCEDURE DIVISION.\n DISPLAY \"WS-RENAME : \" WS-RENAME.\n \nSTOP RUN." }, { "code": null, "e": 4920, "s": 4879, "text": "JCL to execute the above COBOL program −" }, { "code": null, "e": 4997, "s": 4920, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" }, { "code": null, "e": 5080, "s": 4997, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 5100, "s": 5080, "text": "WS-RENAME : 56AABB\n" }, { "code": null, "e": 5398, "s": 5100, "text": "Usage clause specifies the operating system in which the format data is stored. It cannot be used with level numbers 66 or 88. If usage clause is specified on a group, then all the elementary items will have the same usage clause. The different options available with Usage clause are as follows −" }, { "code": null, "e": 5492, "s": 5398, "text": "Data item is stored in ASCII format and each character will take 1 byte. It is default usage." }, { "code": null, "e": 5556, "s": 5492, "text": "The following example calculates the number of bytes required −" }, { "code": null, "e": 5732, "s": 5556, "text": "01 WS-NUM PIC S9(5)V9(3) USAGE IS DISPLAY.\nIt requires 8 bytes as sign and decimal doesn't require any byte.\n\n01 WS-NUM PIC 9(5) USAGE IS DISPLAY.\nIt requires 5 bytes as sign." }, { "code": null, "e": 5804, "s": 5732, "text": "Data item is stored in binary format. Here, data items must be integer." }, { "code": null, "e": 5868, "s": 5804, "text": "The following example calculates the number of bytes required −" }, { "code": null, "e": 6011, "s": 5868, "text": "01 WS-NUM PIC S9(n) USAGE IS COMP.\n\nIf 'n' = 1 to 4, it takes 2 bytes.\nIf 'n' = 5 to 9, it takes 4 bytes.\nIf 'n' = 10 to 18, it takes 8 bytes." }, { "code": null, "e": 6231, "s": 6011, "text": "Data item is similar to Real or Float and is represented as a single precision floating point number. Internally, data is stored in hexadecimal format. COMP-1 does not accept PIC clause. Here 1 word is equal to 4 bytes." }, { "code": null, "e": 6452, "s": 6231, "text": "Data item is similar to Long or Double and is represented as double precision floating point number. Internally, data is stored in hexadecimal format. COMP-2 does not specify PIC clause. Here 2 word is equal to 8 bytes." }, { "code": null, "e": 6589, "s": 6452, "text": "Data item is stored in packed decimal format. Each digit occupies half a byte (1 nibble) and the sign is stored at the rightmost nibble." }, { "code": null, "e": 6653, "s": 6589, "text": "The following example calculates the number of bytes required −" }, { "code": null, "e": 7017, "s": 6653, "text": "01 WS-NUM PIC 9(n) USAGE IS COMP.\nNumber of bytes = n/2 (If n is even)\nNumber of bytes = n/2 + 1(If n is odd, consider only integer part)\n\n01 WS-NUM PIC 9(4) USAGE IS COMP-3 VALUE 21.\nIt requires 2 bytes of storage as each digit occupies half a byte.\n\n01 WS-NUM PIC 9(5) USAGE IS COMP-3 VALUE 21.\nIt requires 3 bytes of storage as each digit occupies half a byte." }, { "code": null, "e": 7337, "s": 7017, "text": "A COBOL copybook is a selection of code that defines data structures. If a particular data structure is used in many programs, then instead of writing the same data structure again, we can use copybooks. We use the COPY statement to include a copybook in a program. COPY statement is used in the WorkingStorage Section." }, { "code": null, "e": 7404, "s": 7337, "text": "The following example includes a copybook inside a COBOL program −" }, { "code": null, "e": 7454, "s": 7404, "text": "DATA DIVISION.\nWORKING-STORAGE SECTION.\nCOPY ABC." }, { "code": null, "e": 7556, "s": 7454, "text": "Here ABC is the copybook name. The following data items in ABC copybook can be used inside a program." }, { "code": null, "e": 7754, "s": 7556, "text": "01 WS-DESCRIPTION.\n 05 WS-NUM.\n 10 WS-NUM1 PIC 9(2) VALUE 20.\n 10 WS-NUM2 PIC 9(2) VALUE 56.\n 05 WS-CHAR.\n 10 WS-CHAR1 PIC X(2) VALUE 'AA'.\n 10 WS-CHAR2 PIC X(2) VALUE 'BB'." }, { "code": null, "e": 7789, "s": 7754, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7804, "s": 7789, "text": " Nishant Malik" }, { "code": null, "e": 7839, "s": 7804, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7863, "s": 7839, "text": " Craig Kenneth Kaercher" }, { "code": null, "e": 7870, "s": 7863, "text": " Print" }, { "code": null, "e": 7881, "s": 7870, "text": " Add Notes" } ]
Dividing two lists in Python
The elements in tow lists can be involved in a division operation for some data manipulation activity using python. In this article we will see how this can be achieved. The zip function can pair up the two given lists element wise. The we apply the division mathematical operator to each pair of these elements. Storing the result into a new list. Live Demo # Given lists list1 = [12,4,0,24] list2 = [6,3,8,-3] # Given lists print("Given list 1 : " + str(list1)) print("Given list 2 : " + str(list2)) # Use zip res = [i / j for i, j in zip(list1, list2)] print(res) Running the above code gives us the following result − Given list 1 : [12, 4, 0, 24] Given list 2 : [6, 3, 8, -3] [2.0, 1.3333333333333333, 0.0, -8.0] The truediv operator is a part of python standard library called operator. It performs the true division between the numbers. We also use the map function to apply the division operator iteratively for each pair of elements in the list. Live Demo from operator import truediv # Given lists list1 = [12,4,0,24] list2 = [6,3,8,-3] # Given lists print("Given list 1 : " + str(list1)) print("Given list 2 : " + str(list2)) # Use zip res = list(map(truediv, list1, list2)) print(res) Running the above code gives us the following result − Given list 1 : [12, 4, 0, 24] Given list 2 : [6, 3, 8, -3] [2.0, 1.3333333333333333, 0.0, -8.0]
[ { "code": null, "e": 1232, "s": 1062, "text": "The elements in tow lists can be involved in a division operation for some data manipulation activity using python. In this article we will see how this can be achieved." }, { "code": null, "e": 1411, "s": 1232, "text": "The zip function can pair up the two given lists element wise. The we apply the division mathematical operator to each pair of these elements. Storing the result into a new list." }, { "code": null, "e": 1422, "s": 1411, "text": " Live Demo" }, { "code": null, "e": 1633, "s": 1422, "text": "# Given lists\nlist1 = [12,4,0,24]\nlist2 = [6,3,8,-3]\n\n# Given lists\nprint(\"Given list 1 : \" + str(list1))\nprint(\"Given list 2 : \" + str(list2))\n\n# Use zip\nres = [i / j for i, j in zip(list1, list2)]\n\nprint(res)" }, { "code": null, "e": 1688, "s": 1633, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1784, "s": 1688, "text": "Given list 1 : [12, 4, 0, 24]\nGiven list 2 : [6, 3, 8, -3]\n[2.0, 1.3333333333333333, 0.0, -8.0]" }, { "code": null, "e": 2021, "s": 1784, "text": "The truediv operator is a part of python standard library called operator. It performs the true division between the numbers. We also use the map function to apply the division operator iteratively for each pair of elements in the list." }, { "code": null, "e": 2032, "s": 2021, "text": " Live Demo" }, { "code": null, "e": 2267, "s": 2032, "text": "from operator import truediv\n# Given lists\nlist1 = [12,4,0,24]\nlist2 = [6,3,8,-3]\n\n# Given lists\nprint(\"Given list 1 : \" + str(list1))\nprint(\"Given list 2 : \" + str(list2))\n\n# Use zip\nres = list(map(truediv, list1, list2))\n\nprint(res)" }, { "code": null, "e": 2322, "s": 2267, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2418, "s": 2322, "text": "Given list 1 : [12, 4, 0, 24]\nGiven list 2 : [6, 3, 8, -3]\n[2.0, 1.3333333333333333, 0.0, -8.0]" } ]
With JavaScript how to change the width of a table border?
To change the width of a table border, use the DOM border property. You can try to run the following code to change the width of a table border in JavaScript − <!DOCTYPE html> <html> <head> <script> function borderFunc(x) { document.getElementById(x).style.border = "5px dashed blue"; } </script> </head> <body> <table style = "border:2px solid black" id = "newtable"> <tr> <td>One</td> <td>Two</td> </tr> <tr> <td>Three</td> <td>Four</td> </tr> <tr> <td>Five</td> <td>Six</td> </tr> </table> <p> <input type = "button" onclick = "borderFunc('newtable')" value = "Change Border Width"> </p> </body> </html>
[ { "code": null, "e": 1222, "s": 1062, "text": "To change the width of a table border, use the DOM border property. You can try to run the following code to change the width of a table border in JavaScript −" }, { "code": null, "e": 1893, "s": 1222, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function borderFunc(x) {\n document.getElementById(x).style.border = \"5px dashed blue\";\n }\n </script>\n </head>\n \n <body>\n <table style = \"border:2px solid black\" id = \"newtable\">\n <tr>\n <td>One</td>\n <td>Two</td>\n </tr>\n <tr>\n <td>Three</td>\n <td>Four</td>\n </tr>\n <tr>\n <td>Five</td>\n <td>Six</td>\n </tr>\n </table>\n <p>\n <input type = \"button\" onclick = \"borderFunc('newtable')\"\n value = \"Change Border Width\">\n </p>\n </body>\n</html>" } ]
CSS | Shorthand Properties - GeeksforGeeks
27 Apr, 2020 Shorthand properties allow us to write multiple properties in a single line and in a compact way. They are useful as they provide clean code and also decrease the LOC (Line of Code). The Shorthand properties we will be covering: BackgroundFontBorderOutlineMarginPaddingList Background Font Border Outline Margin Padding List Background: The CSS Background property is used to set the background on a web page. The background can be applied to any element like the body, h1, p, div, etc. There are many properties available with a background such as color, image, position, etc. Some of them are used in the below code. Longhand way:background-color:#000;background-image: url(images/bg.png);background-repeat: no-repeat;background-position:left top; background-color:#000;background-image: url(images/bg.png);background-repeat: no-repeat;background-position:left top; Shorthand way:background:#000 url(images/bg.png) no-repeat left top; background:#000 url(images/bg.png) no-repeat left top; Example:<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { background: #000 url(images/bg.png) no-repeat left top; } </style></head> <body></body> </html> <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { background: #000 url(images/bg.png) no-repeat left top; } </style></head> <body></body> </html> Output: Font: The CSS font property is used to apply different fonts to the text on the webpage. The various attributes that can be set using the font are font-family, font-size, font-weight, etc. Some of them are used in the below code. Longhand way:font-style:italic;font-weight:bold;font-size:18px;line-height:150%;font-family:Arial,sans-serif; font-style:italic;font-weight:bold;font-size:18px;line-height:150%;font-family:Arial,sans-serif; Shorthand way:font: italic bold 18px/150% Arial, sans-serif; font: italic bold 18px/150% Arial, sans-serif; Example:<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> h1 { font: italic bold 18px/150% Arial, sans-serif; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html> <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> h1 { font: italic bold 18px/150% Arial, sans-serif; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html> Output: Border: The CSS border property is used to apply a border to different elements of a web page. There are many attributes of the border like width, style, color, etc. Longhand way:border-width: 1px;border-style: solid;border-color: #000; border-width: 1px;border-style: solid;border-color: #000; Shorthand way:border: 1px solid #000; border: 1px solid #000; Example:<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> h1 { border: 1px solid #000; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html> <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> h1 { border: 1px solid #000; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html> Output: Outline: The CSS outline property is used to apply an outline to various elements that are present in a web page. Longhand way:outline-width: 1px;outline-style: solid;outline-color: #000; outline-width: 1px;outline-style: solid;outline-color: #000; Shorthand way:outline: 1px solid #000; outline: 1px solid #000; Example:<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> h1 { outline: 10px solid #000; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html> <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> h1 { outline: 10px solid #000; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html> Output: Margin: The CSS margin properties are used to create space around elements, outside of any defined borders. We can define margin for all 4 sides i.e. top, bottom, left and right. Longhand way:margin-top: 10px;margin-right: 5px;margin-bottom: 10px;margin-left :5px; margin-top: 10px;margin-right: 5px;margin-bottom: 10px;margin-left :5px; Shorthand way:margin : 10px 5px 10px 5px; margin : 10px 5px 10px 5px; Example:<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> h1 { margin: 100px 50px 100px 50px; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html> <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> h1 { margin: 100px 50px 100px 50px; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html> Output: Padding: The CSS padding properties are used to generate space around an element’s content, inside of any defined borders. Padding can also be applied as top, bottom, left and right padding. Longhand way:padding-top: 10px;padding-right: 5px;padding-bottom: 10px;padding-left :5px; padding-top: 10px;padding-right: 5px;padding-bottom: 10px;padding-left :5px; Shorthand way:padding : 10px 5px 10px 5px; padding : 10px 5px 10px 5px; Example:<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> h1 { padding: 100px 50px 100px 50px; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html> <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> h1 { padding: 100px 50px 100px 50px; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html> Output: List: There are mainly two types of list in CSS:1. Ordered list<ol>2. Unordered list <ul>UnOrdered lists have bullet points while ordered lists have numbers. Longhand way:list-style-type: disc;list-style-position: inside;list-style-image: url(disc.png); list-style-type: disc;list-style-position: inside;list-style-image: url(disc.png); Shorthand way:list-style: disc inside url(disc.png); list-style: disc inside url(disc.png); Example:<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> li { list-style: disc inside url(assets/hole.png); } </style></head> <body> <li>GeeksforGeeks</li></body> </html> <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> li { list-style: disc inside url(assets/hole.png); } </style></head> <body> <li>GeeksforGeeks</li></body> </html> Output: CSS-Properties CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? 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 How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 25376, "s": 25348, "text": "\n27 Apr, 2020" }, { "code": null, "e": 25559, "s": 25376, "text": "Shorthand properties allow us to write multiple properties in a single line and in a compact way. They are useful as they provide clean code and also decrease the LOC (Line of Code)." }, { "code": null, "e": 25605, "s": 25559, "text": "The Shorthand properties we will be covering:" }, { "code": null, "e": 25650, "s": 25605, "text": "BackgroundFontBorderOutlineMarginPaddingList" }, { "code": null, "e": 25661, "s": 25650, "text": "Background" }, { "code": null, "e": 25666, "s": 25661, "text": "Font" }, { "code": null, "e": 25673, "s": 25666, "text": "Border" }, { "code": null, "e": 25681, "s": 25673, "text": "Outline" }, { "code": null, "e": 25688, "s": 25681, "text": "Margin" }, { "code": null, "e": 25696, "s": 25688, "text": "Padding" }, { "code": null, "e": 25701, "s": 25696, "text": "List" }, { "code": null, "e": 25995, "s": 25701, "text": "Background: The CSS Background property is used to set the background on a web page. The background can be applied to any element like the body, h1, p, div, etc. There are many properties available with a background such as color, image, position, etc. Some of them are used in the below code." }, { "code": null, "e": 26126, "s": 25995, "text": "Longhand way:background-color:#000;background-image: url(images/bg.png);background-repeat: no-repeat;background-position:left top;" }, { "code": "background-color:#000;background-image: url(images/bg.png);background-repeat: no-repeat;background-position:left top;", "e": 26244, "s": 26126, "text": null }, { "code": null, "e": 26313, "s": 26244, "text": "Shorthand way:background:#000 url(images/bg.png) no-repeat left top;" }, { "code": "background:#000 url(images/bg.png) no-repeat left top;", "e": 26368, "s": 26313, "text": null }, { "code": null, "e": 26702, "s": 26368, "text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title> <style> body { background: #000 url(images/bg.png) no-repeat left top; } </style></head> <body></body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title> <style> body { background: #000 url(images/bg.png) no-repeat left top; } </style></head> <body></body> </html>", "e": 27028, "s": 26702, "text": null }, { "code": null, "e": 27036, "s": 27028, "text": "Output:" }, { "code": null, "e": 27266, "s": 27036, "text": "Font: The CSS font property is used to apply different fonts to the text on the webpage. The various attributes that can be set using the font are font-family, font-size, font-weight, etc. Some of them are used in the below code." }, { "code": null, "e": 27376, "s": 27266, "text": "Longhand way:font-style:italic;font-weight:bold;font-size:18px;line-height:150%;font-family:Arial,sans-serif;" }, { "code": "font-style:italic;font-weight:bold;font-size:18px;line-height:150%;font-family:Arial,sans-serif;", "e": 27473, "s": 27376, "text": null }, { "code": null, "e": 27534, "s": 27473, "text": "Shorthand way:font: italic bold 18px/150% Arial, sans-serif;" }, { "code": "font: italic bold 18px/150% Arial, sans-serif;", "e": 27581, "s": 27534, "text": null }, { "code": null, "e": 27957, "s": 27581, "text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title> <style> h1 { font: italic bold 18px/150% Arial, sans-serif; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title> <style> h1 { font: italic bold 18px/150% Arial, sans-serif; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html>", "e": 28325, "s": 27957, "text": null }, { "code": null, "e": 28333, "s": 28325, "text": "Output:" }, { "code": null, "e": 28499, "s": 28333, "text": "Border: The CSS border property is used to apply a border to different elements of a web page. There are many attributes of the border like width, style, color, etc." }, { "code": null, "e": 28571, "s": 28499, "text": "Longhand way:border-width: 1px;border-style: solid;border-color: #000; " }, { "code": "border-width: 1px;border-style: solid;border-color: #000; ", "e": 28630, "s": 28571, "text": null }, { "code": null, "e": 28668, "s": 28630, "text": "Shorthand way:border: 1px solid #000;" }, { "code": "border: 1px solid #000;", "e": 28692, "s": 28668, "text": null }, { "code": null, "e": 29034, "s": 28692, "text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title> <style> h1 { border: 1px solid #000; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title> <style> h1 { border: 1px solid #000; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html>", "e": 29368, "s": 29034, "text": null }, { "code": null, "e": 29376, "s": 29368, "text": "Output:" }, { "code": null, "e": 29490, "s": 29376, "text": "Outline: The CSS outline property is used to apply an outline to various elements that are present in a web page." }, { "code": null, "e": 29564, "s": 29490, "text": "Longhand way:outline-width: 1px;outline-style: solid;outline-color: #000;" }, { "code": "outline-width: 1px;outline-style: solid;outline-color: #000;", "e": 29625, "s": 29564, "text": null }, { "code": null, "e": 29664, "s": 29625, "text": "Shorthand way:outline: 1px solid #000;" }, { "code": "outline: 1px solid #000;", "e": 29689, "s": 29664, "text": null }, { "code": null, "e": 30042, "s": 29689, "text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title> <style> h1 { outline: 10px solid #000; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title> <style> h1 { outline: 10px solid #000; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html>", "e": 30387, "s": 30042, "text": null }, { "code": null, "e": 30395, "s": 30387, "text": "Output:" }, { "code": null, "e": 30574, "s": 30395, "text": "Margin: The CSS margin properties are used to create space around elements, outside of any defined borders. We can define margin for all 4 sides i.e. top, bottom, left and right." }, { "code": null, "e": 30660, "s": 30574, "text": "Longhand way:margin-top: 10px;margin-right: 5px;margin-bottom: 10px;margin-left :5px;" }, { "code": "margin-top: 10px;margin-right: 5px;margin-bottom: 10px;margin-left :5px;", "e": 30733, "s": 30660, "text": null }, { "code": null, "e": 30775, "s": 30733, "text": "Shorthand way:margin : 10px 5px 10px 5px;" }, { "code": "margin : 10px 5px 10px 5px;", "e": 30803, "s": 30775, "text": null }, { "code": null, "e": 31152, "s": 30803, "text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title> <style> h1 { margin: 100px 50px 100px 50px; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title> <style> h1 { margin: 100px 50px 100px 50px; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html>", "e": 31493, "s": 31152, "text": null }, { "code": null, "e": 31501, "s": 31493, "text": "Output:" }, { "code": null, "e": 31692, "s": 31501, "text": "Padding: The CSS padding properties are used to generate space around an element’s content, inside of any defined borders. Padding can also be applied as top, bottom, left and right padding." }, { "code": null, "e": 31782, "s": 31692, "text": "Longhand way:padding-top: 10px;padding-right: 5px;padding-bottom: 10px;padding-left :5px;" }, { "code": "padding-top: 10px;padding-right: 5px;padding-bottom: 10px;padding-left :5px;", "e": 31859, "s": 31782, "text": null }, { "code": null, "e": 31902, "s": 31859, "text": "Shorthand way:padding : 10px 5px 10px 5px;" }, { "code": "padding : 10px 5px 10px 5px;", "e": 31931, "s": 31902, "text": null }, { "code": null, "e": 32281, "s": 31931, "text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title> <style> h1 { padding: 100px 50px 100px 50px; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title> <style> h1 { padding: 100px 50px 100px 50px; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html>", "e": 32623, "s": 32281, "text": null }, { "code": null, "e": 32631, "s": 32623, "text": "Output:" }, { "code": null, "e": 32789, "s": 32631, "text": "List: There are mainly two types of list in CSS:1. Ordered list<ol>2. Unordered list <ul>UnOrdered lists have bullet points while ordered lists have numbers." }, { "code": null, "e": 32885, "s": 32789, "text": "Longhand way:list-style-type: disc;list-style-position: inside;list-style-image: url(disc.png);" }, { "code": "list-style-type: disc;list-style-position: inside;list-style-image: url(disc.png);", "e": 32968, "s": 32885, "text": null }, { "code": null, "e": 33021, "s": 32968, "text": "Shorthand way:list-style: disc inside url(disc.png);" }, { "code": "list-style: disc inside url(disc.png);", "e": 33060, "s": 33021, "text": null }, { "code": null, "e": 33421, "s": 33060, "text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title> <style> li { list-style: disc inside url(assets/hole.png); } </style></head> <body> <li>GeeksforGeeks</li></body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title> <style> li { list-style: disc inside url(assets/hole.png); } </style></head> <body> <li>GeeksforGeeks</li></body> </html>", "e": 33774, "s": 33421, "text": null }, { "code": null, "e": 33782, "s": 33774, "text": "Output:" }, { "code": null, "e": 33797, "s": 33782, "text": "CSS-Properties" }, { "code": null, "e": 33801, "s": 33797, "text": "CSS" }, { "code": null, "e": 33818, "s": 33801, "text": "Web Technologies" }, { "code": null, "e": 33916, "s": 33818, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33925, "s": 33916, "text": "Comments" }, { "code": null, "e": 33938, "s": 33925, "text": "Old Comments" }, { "code": null, "e": 33975, "s": 33938, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 34004, "s": 33975, "text": "Form validation using jQuery" }, { "code": null, "e": 34043, "s": 34004, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 34085, "s": 34043, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 34120, "s": 34085, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 34162, "s": 34120, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 34195, "s": 34162, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34238, "s": 34195, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 34283, "s": 34238, "text": "Convert a string to an integer in JavaScript" } ]
Breadth First Search on Matrix in Python
In a given matrix, there are four objects to analyze the element position: left, right, bottom, and top. Breadth First Search is nothing but finding the shortest distance between the two elements of a given 2-D Matrix. Thus, in each cell, there are four operations we can perform which can be expressed in four numerals such as, '2' describes that the cell in the matrix is Source. '3' describes that the cell in the matrix is Destination. '1' describes that the cell can be moved further in a direction. '0' describes that the cell in the matrix can not be moved in any direction. On the basis of adobe justification, we can perform a Breadth First Search Operation on a given Matrix. The algorithm to traverse the whole matrix and find the minimum or shortest distance between any cell using BFS is as follows: First take input of row and column. Initialize a matrix with the given row and column. An integer function shortestDist(int row, int col, int mat[][col]) takes the row, column and matrix as the input and returns the shortest distance between the elements of the matrix. Initialize the variable source and destination to find out the source as well as the destination element. If the element is '3', then mark it as destination and if the element is '2', then mark it as the source element. Now initialize queue data structure to implement Breadth First Search on the given matrix. Insert the row and column of the matrix in the queue as pairs. Now move in the cell and find out if it is a destination cell or not. If the destination cell is having a distance minimum or less than the current cell, then update the distance. Again move to another direction to find out the minimum distance of the cell from the current cell. Return the minimum distance as the output. Live Demo import queue INF = 10000 class Node: def __init__(self, i, j): self.row_num = i self.col_num = j def findDistance(row, col, mat): source_i = 0 source_j = 0 destination_i = 0 destination_j = 0 for i in range(0, row): for j in range(0, col): if mat[i][j] == 2 : source_i = i source_j = j if mat[i][j] == 3 : destination_i = i destination_j = j dist = [] for i in range(0, row): sublist = [] for j in range(0, col): sublist.append(INF) dist.append(sublist) # initialise queue to start BFS on matrix q = queue.Queue() source = Node(source_i, source_j) q.put(source) dist[source_i][source_j] = 0 # modified BFS by add constraint checks while (not q.empty()): # extract and remove the node from the front of queue temp = q.get() x = temp.row_num y = temp.col_num # If move towards left is allowed or it is the destnation cell if y - 1 >= 0 and (mat[x][y - 1] == 1 or mat[x][y - 1] == 3) : # if distance to reach the cell to the left is less than the computed previous path distance, update it if dist[x][y] + 1 < dist[x][y - 1] : dist[x][y - 1] = dist[x][y] + 1 next = Node(x, y - 1) q.put(next) # If move towards right is allowed or it is the destination cell if y + 1 < col and (mat[x][y + 1] == 1 or mat[x][y + 1] == 3) : # if distance to reach the cell to the right is less than the computed previous path distance, update it if dist[x][y] + 1 < dist[x][y + 1] : dist[x][y + 1] = dist[x][y] + 1 next = Node(x, y + 1) q.put(next); # If move towards up is allowed or it is the destination cell if x - 1 >= 0 and (mat[x - 1][y] == 1 or mat[x-1][y] == 3) : # if distance to reach the cell to the up is less than the computed previous path distance, update it if dist[x][y] + 1 < dist[x - 1][y] : dist[x - 1][y] = dist[x][y] + 1 next = Node(x - 1, y) q.put(next) # If move towards down is allowed or it is the destination cell if x + 1 < row and (mat[x + 1][y] == 1 or mat[x+1][y] == 3) : # if distance to reach the cell to the down is less than the computed previous path distance, update it if dist[x][y] + 1 < dist[x + 1][y] : dist[x + 1][y] = dist[x][y] + 1 next = Node(x + 1, y) q.put(next) return dist[destination_i][destination_j] row = 5 col = 5 mat = [ [1, 0, 0, 2, 1], [1, 0, 2, 1, 1], [0, 1, 1, 1, 0], [3, 2, 0, 0, 1], [3, 1, 0, 0, 1] ] answer = findDistance(row, col, mat); if answer == INF : print("No Path Found") else: print("The Shortest Distance between Source and Destination is:") print(answer) The Shortest Distance between Source and Destination is:2
[ { "code": null, "e": 1167, "s": 1062, "text": "In a given matrix, there are four objects to analyze the element position: left, right, bottom, and top." }, { "code": null, "e": 1391, "s": 1167, "text": "Breadth First Search is nothing but finding the shortest distance between the two elements of a given 2-D Matrix. Thus, in each cell, there are four operations we can perform which can be expressed in four numerals such as," }, { "code": null, "e": 1444, "s": 1391, "text": "'2' describes that the cell in the matrix is Source." }, { "code": null, "e": 1502, "s": 1444, "text": "'3' describes that the cell in the matrix is Destination." }, { "code": null, "e": 1567, "s": 1502, "text": "'1' describes that the cell can be moved further in a direction." }, { "code": null, "e": 1644, "s": 1567, "text": "'0' describes that the cell in the matrix can not be moved in any direction." }, { "code": null, "e": 1748, "s": 1644, "text": "On the basis of adobe justification, we can perform a Breadth First Search Operation on a given Matrix." }, { "code": null, "e": 1875, "s": 1748, "text": "The algorithm to traverse the whole matrix and find the minimum or shortest distance between any cell using BFS is as follows:" }, { "code": null, "e": 1911, "s": 1875, "text": "First take input of row and column." }, { "code": null, "e": 1962, "s": 1911, "text": "Initialize a matrix with the given row and column." }, { "code": null, "e": 2145, "s": 1962, "text": "An integer function shortestDist(int row, int col, int mat[][col]) takes the row, column and matrix as the input and returns the shortest distance between the elements of the matrix." }, { "code": null, "e": 2251, "s": 2145, "text": "Initialize the variable source and destination to find out the source as well as the destination element." }, { "code": null, "e": 2365, "s": 2251, "text": "If the element is '3', then mark it as destination and if the element is '2', then mark it as the source element." }, { "code": null, "e": 2456, "s": 2365, "text": "Now initialize queue data structure to implement Breadth First Search on the given matrix." }, { "code": null, "e": 2699, "s": 2456, "text": "Insert the row and column of the matrix in the queue as pairs. Now move in the cell and find out if it is a destination cell or not. If the destination cell is having a distance minimum or less than the current cell, then update the distance." }, { "code": null, "e": 2799, "s": 2699, "text": "Again move to another direction to find out the minimum distance of the cell from the current cell." }, { "code": null, "e": 2842, "s": 2799, "text": "Return the minimum distance as the output." }, { "code": null, "e": 2852, "s": 2842, "text": "Live Demo" }, { "code": null, "e": 5744, "s": 2852, "text": "import queue\nINF = 10000\nclass Node:\n def __init__(self, i, j):\n self.row_num = i\n self.col_num = j\ndef findDistance(row, col, mat):\n source_i = 0\n source_j = 0\n destination_i = 0\n destination_j = 0\n for i in range(0, row):\n for j in range(0, col):\n if mat[i][j] == 2 :\n source_i = i\n source_j = j\n if mat[i][j] == 3 :\n destination_i = i\n destination_j = j\n dist = []\n for i in range(0, row):\n sublist = []\n for j in range(0, col):\n sublist.append(INF)\n dist.append(sublist)\n # initialise queue to start BFS on matrix\n q = queue.Queue()\n source = Node(source_i, source_j)\n q.put(source)\n dist[source_i][source_j] = 0\n\n # modified BFS by add constraint checks\n while (not q.empty()):\n # extract and remove the node from the front of queue\n temp = q.get()\n x = temp.row_num\n y = temp.col_num\n\n # If move towards left is allowed or it is the destnation cell\n if y - 1 >= 0 and (mat[x][y - 1] == 1 or mat[x][y - 1] == 3) :\n # if distance to reach the cell to the left is less than the computed previous path distance, update it\n if dist[x][y] + 1 < dist[x][y - 1] :\n dist[x][y - 1] = dist[x][y] + 1\n next = Node(x, y - 1)\n q.put(next)\n\n # If move towards right is allowed or it is the destination cell\n if y + 1 < col and (mat[x][y + 1] == 1 or mat[x][y + 1] == 3) :\n # if distance to reach the cell to the right is less than the computed previous path distance, update it\n if dist[x][y] + 1 < dist[x][y + 1] :\n dist[x][y + 1] = dist[x][y] + 1\n next = Node(x, y + 1)\n q.put(next);\n\n # If move towards up is allowed or it is the destination cell\n if x - 1 >= 0 and (mat[x - 1][y] == 1 or mat[x-1][y] == 3) :\n # if distance to reach the cell to the up is less than the computed previous path distance, update it\n if dist[x][y] + 1 < dist[x - 1][y] :\n dist[x - 1][y] = dist[x][y] + 1\n next = Node(x - 1, y)\n q.put(next)\n\n # If move towards down is allowed or it is the destination cell\n if x + 1 < row and (mat[x + 1][y] == 1 or mat[x+1][y] == 3) :\n # if distance to reach the cell to the down is less than the computed previous path distance, update it\n if dist[x][y] + 1 < dist[x + 1][y] :\n dist[x + 1][y] = dist[x][y] + 1\n next = Node(x + 1, y)\n q.put(next)\n return dist[destination_i][destination_j]\n\nrow = 5\ncol = 5\nmat = [ [1, 0, 0, 2, 1],\n [1, 0, 2, 1, 1],\n [0, 1, 1, 1, 0],\n [3, 2, 0, 0, 1],\n [3, 1, 0, 0, 1] ]\n\nanswer = findDistance(row, col, mat);\nif answer == INF :\n print(\"No Path Found\")\nelse:\n print(\"The Shortest Distance between Source and Destination is:\")\n print(answer)" }, { "code": null, "e": 5802, "s": 5744, "text": "The Shortest Distance between Source and Destination is:2" } ]
VBA - Space
The Space function fills a string with a specific number of spaces. space(number) Number − A required parameter. The number of spaces that we want to add to the given string. Private Sub Constant_demo_Click() Dim var1 as Variant var1 = "Microsoft" Dim var2 as Variant var2 = "VBScript" msgbox(var1 & Space(2)& var2) End Sub When you execute the above function, it produces the following output. Microsoft VBScript 101 Lectures 6 hours Pavan Lalwani 41 Lectures 3 hours Arnold Higuit 80 Lectures 5.5 hours Prashant Panchal 25 Lectures 2 hours Prashant Panchal 26 Lectures 2 hours Arnold Higuit 92 Lectures 10.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2003, "s": 1935, "text": "The Space function fills a string with a specific number of spaces." }, { "code": null, "e": 2018, "s": 2003, "text": "space(number)\n" }, { "code": null, "e": 2111, "s": 2018, "text": "Number − A required parameter. The number of spaces that we want to add to the given string." }, { "code": null, "e": 2283, "s": 2111, "text": "Private Sub Constant_demo_Click()\n Dim var1 as Variant\n \n var1 = \"Microsoft\"\n Dim var2 as Variant\n \n var2 = \"VBScript\"\n msgbox(var1 & Space(2)& var2)\nEnd Sub" }, { "code": null, "e": 2354, "s": 2283, "text": "When you execute the above function, it produces the following output." }, { "code": null, "e": 2374, "s": 2354, "text": "Microsoft VBScript\n" }, { "code": null, "e": 2408, "s": 2374, "text": "\n 101 Lectures \n 6 hours \n" }, { "code": null, "e": 2423, "s": 2408, "text": " Pavan Lalwani" }, { "code": null, "e": 2456, "s": 2423, "text": "\n 41 Lectures \n 3 hours \n" }, { "code": null, "e": 2471, "s": 2456, "text": " Arnold Higuit" }, { "code": null, "e": 2506, "s": 2471, "text": "\n 80 Lectures \n 5.5 hours \n" }, { "code": null, "e": 2524, "s": 2506, "text": " Prashant Panchal" }, { "code": null, "e": 2557, "s": 2524, "text": "\n 25 Lectures \n 2 hours \n" }, { "code": null, "e": 2575, "s": 2557, "text": " Prashant Panchal" }, { "code": null, "e": 2608, "s": 2575, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 2623, "s": 2608, "text": " Arnold Higuit" }, { "code": null, "e": 2659, "s": 2623, "text": "\n 92 Lectures \n 10.5 hours \n" }, { "code": null, "e": 2687, "s": 2659, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 2694, "s": 2687, "text": " Print" }, { "code": null, "e": 2705, "s": 2694, "text": " Add Notes" } ]
ES6 - Classes
Object Orientation is a software development paradigm that follows real-world modelling. Object Orientation, considers a program as a collection of objects that communicates with each other via mechanism called methods. ES6 supports these object-oriented components too. To begin with, let us understand Object − An object is a real-time representation of any entity. According to Grady Brooch, every object is said to have 3 features − State − Described by the attributes of an object. Behavior − Describes how the object will act. Identity − A unique value that distinguishes an object from a set of similar such objects. Object − An object is a real-time representation of any entity. According to Grady Brooch, every object is said to have 3 features − State − Described by the attributes of an object. State − Described by the attributes of an object. Behavior − Describes how the object will act. Behavior − Describes how the object will act. Identity − A unique value that distinguishes an object from a set of similar such objects. Identity − A unique value that distinguishes an object from a set of similar such objects. Class − A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object. Class − A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object. Method − Methods facilitate communication between objects. Method − Methods facilitate communication between objects. Let us translate these Object-Oriented concepts to the ones in the real world. For example: A car is an object that has data (make, model, number of doors, Vehicle Number, etc.) and functionality (accelerate, shift, open doors, turn on headlights, etc.) Prior to ES6, creating a class was a fussy affair. Classes can be created using the class keyword in ES6. Classes can be included in the code either by declaring them or by using class expressions. class Class_name { } var var_name = new Class_name { } The class keyword is followed by the class name. The rules for identifiers (already discussed) must be considered while naming a class. A class definition can include the following − Constructors − Responsible for allocating memory for the objects of the class. Constructors − Responsible for allocating memory for the objects of the class. Functions − Functions represent actions an object can take. They are also at times referred to as methods. Functions − Functions represent actions an object can take. They are also at times referred to as methods. These components put together are termed as the data members of the class. Note − A class body can only contain methods, but not data properties. class Polygon { constructor(height, width) { this.height = height; this.width = width; } } var Polygon = class { constructor(height, width) { this.height = height; this.width = width; } } The above code snippet represents an unnamed class expression. A named class expression can be written as. var Polygon = class Polygon { constructor(height, width) { this.height = height; this.width = width; } } Note − Unlike variables and functions, classes cannot be hoisted. To create an instance of the class, use the new keyword followed by the class name. Following is the syntax for the same. var object_name= new class_name([ arguments ]) Where, The new keyword is responsible for instantiation. The new keyword is responsible for instantiation. The right hand side of the expression invokes the constructor. The constructor should be passed values if it is parameterized. The right hand side of the expression invokes the constructor. The constructor should be passed values if it is parameterized. var obj = new Polygon(10,12) A class’s attributes and functions can be accessed through the object. Use the ‘.’ dot notation (called as the period) to access the data members of a class. //accessing a function obj.function_name() 'use strict' class Polygon { constructor(height, width) { this.h = height; this.w = width; } test() { console.log("The height of the polygon: ", this.h) console.log("The width of the polygon: ",this. w) } } //creating an instance var polyObj = new Polygon(10,20); polyObj.test(); The Example given above declares a class ‘Polygon’. The class’s constructor takes two arguments - height and width respectively. The ‘this’ keyword refers to the current instance of the class. In other words, the constructor above initializes two variables h and w with the parameter values passed to the constructor. The test () function in the class, prints the values of the height and width. To make the script functional, an object of the class Polygon is created. The object is referred to by the polyObj variable. The function is then called via this object. The following output is displayed on successful execution of the above code. The height of the polygon: 10 The width of the polygon: 20 A setter function is invoked when there is an attempt to set the value of a property. The set keyword is used to define a setter function. The syntax for defining a setter function is given below − {set prop(val) { . . . }} {set [expression](val) { . . . }} prop is the name of the property to bind to the given function. val is an alias for the variable that holds the value attempted to be assigned to property. expression with ES6, can be used as a property name to bind to the given function. <script> class Student { constructor(rno,fname,lname){ this.rno = rno this.fname = fname this.lname = lname console.log('inside constructor') } set rollno(newRollno){ console.log("inside setter") this.rno = newRollno } } let s1 = new Student(101,'Sachin','Tendulkar') console.log(s1) //setter is called s1.rollno = 201 console.log(s1) </script> The above example defines a class Student with three properties namely rno, fname and lname. A setter function rollno() is used to set the value for the rno property. The output of the above code will be as shown below − inside constructor Student {rno: 101, fname: "Sachin", lname: "Tendulkar"} inside setter Student {rno: 201, fname: "Sachin", lname: "Tendulkar"} The following example shows how to use an expression as a property name with a setter function. <script> let expr = 'name'; let obj = { fname: 'Sachin', set [expr](v) { this.fname = v; } }; console.log(obj.fname); obj.name = 'John'; console.log(obj.fname); </script> The output of the above code will be as mentioned below − Sachin John A getter function is invoked when there is an attempt to fetch the value of a property. The get keyword is used to define a getter function. The syntax for defining a getter function is given below − {get prop() { ... } } {get [expression]() { ... } } prop is the name of the property to bind to the given function. expression − Starting with ES6, you can also use expressions as a property name to bind to the given function. <script> class Student { constructor(rno,fname,lname){ this.rno = rno this.fname = fname this.lname = lname console.log('inside constructor') } get fullName(){ console.log('inside getter') return this.fname + " - "+this.lname } } let s1 = new Student(101,'Sachin','Tendulkar') console.log(s1) //getter is called console.log(s1.fullName) </script> The above example defines a class Student with three properties namely rno, fname and lname. The getter function fullName() concatenates the fname and lname and returns a new string. The output of the above code will be as given below − inside constructor Student {rno: 101, fname: "Sachin", lname: "Tendulkar"} inside getter Sachin - Tendulkar The following example shows how to use an expression as a property name with a getter function − <script> let expr = 'name'; let obj = { get [expr]() { return 'Sachin'; } }; console.log(obj.name); </script> The output of the above code will be as mentioned below − Sachin The static keyword can be applied to functions in a class. Static members are referenced by the class name. 'use strict' class StaticMem { static disp() { console.log("Static Function called") } } StaticMem.disp() //invoke the static metho Note − It is not mandatory to include a constructor definition. Every class by default has a constructor by default. The following output is displayed on successful execution of the above code. Static Function called The instanceof operator returns true if the object belongs to the specified type. 'use strict' class Person{ } var obj = new Person() var isPerson = obj instanceof Person; console.log(" obj is an instance of Person " + isPerson); The following output is displayed on successful execution of the above code. obj is an instance of Person True ES6 supports the concept of Inheritance. Inheritance is the ability of a program to create new entities from an existing entity - here a class. The class that is extended to create newer classes is called the parent class/super class. The newly created classes are called the child/sub classes. A class inherits from another class using the ‘extends’ keyword. Child classes inherit all properties and methods except constructors from the parent class. Following is the syntax for the same. class child_class_name extends parent_class_name 'use strict' class Shape { constructor(a) { this.Area = a } } class Circle extends Shape { disp() { console.log("Area of the circle: "+this.Area) } } var obj = new Circle(223); obj.disp() The above example declares a class Shape. The class is extended by the Circle class. Since, there is an inheritance relationship between the classes, the child class i.e., the class Circle gets an implicit access to its parent class attribute i.e., area. The following output is displayed on successful execution of the above code. Area of Circle: 223 Inheritance can be classified as − Single − Every class can at the most extend from one parent class. Single − Every class can at the most extend from one parent class. Multiple − A class can inherit from multiple classes. ES6 doesn’t support multiple inheritance. Multiple − A class can inherit from multiple classes. ES6 doesn’t support multiple inheritance. Multi-level − Consider the following example. Multi-level − Consider the following example. 'use strict' class Root { test() { console.log("call from parent class") } } class Child extends Root {} class Leaf extends Child //indirectly inherits from Root by virtue of inheritance {} var obj = new Leaf(); obj.test() The class Leaf derives the attributes from the Root and the Child classes by virtue of multilevel inheritance. The following output is displayed on successful execution of the above code. call from parent class Method Overriding is a mechanism by which the child class redefines the superclass method. The following example illustrates the same − 'use strict' ; class PrinterClass { doPrint() { console.log("doPrint() from Parent called... "); } } class StringPrinter extends PrinterClass { doPrint() { console.log("doPrint() is printing a string..."); } } var obj = new StringPrinter(); obj.doPrint(); In the above Example, the child class has changed the superclass function’s implementation. The following output is displayed on successful execution of the above code. doPrint() is printing a string... ES6 enables a child class to invoke its parent class data member. This is achieved by using the super keyword. The super keyword is used to refer to the immediate parent of a class. Consider the following example − 'use strict' class PrinterClass { doPrint() { console.log("doPrint() from Parent called...") } } class StringPrinter extends PrinterClass { doPrint() { super.doPrint() console.log("doPrint() is printing a string...") } } var obj = new StringPrinter() obj.doPrint() The doPrint() redefinition in the class StringWriter, issues a call to its parent class version. In other words, the super keyword is used to invoke the doPrint() function definition in the parent class - PrinterClass. The following output is displayed on successful execution of the above code. doPrint() from Parent called. doPrint() is printing a string. 32 Lectures 3.5 hours Sharad Kumar 40 Lectures 5 hours Richa Maheshwari 16 Lectures 1 hours Anadi Sharma 50 Lectures 6.5 hours Gowthami Swarna 14 Lectures 1 hours Deepti Trivedi 31 Lectures 1.5 hours Shweta Print Add Notes Bookmark this page
[ { "code": null, "e": 2548, "s": 2277, "text": "Object Orientation is a software development paradigm that follows real-world modelling. Object Orientation, considers a program as a collection of objects that communicates with each other via mechanism called methods. ES6 supports these object-oriented components too." }, { "code": null, "e": 2581, "s": 2548, "text": "To begin with, let us understand" }, { "code": null, "e": 2904, "s": 2581, "text": "Object − An object is a real-time representation of any entity. According to Grady Brooch, every object is said to have 3 features −\n\nState − Described by the attributes of an object.\nBehavior − Describes how the object will act.\nIdentity − A unique value that distinguishes an object from a set of similar such objects.\n\n" }, { "code": null, "e": 3037, "s": 2904, "text": "Object − An object is a real-time representation of any entity. According to Grady Brooch, every object is said to have 3 features −" }, { "code": null, "e": 3087, "s": 3037, "text": "State − Described by the attributes of an object." }, { "code": null, "e": 3137, "s": 3087, "text": "State − Described by the attributes of an object." }, { "code": null, "e": 3183, "s": 3137, "text": "Behavior − Describes how the object will act." }, { "code": null, "e": 3229, "s": 3183, "text": "Behavior − Describes how the object will act." }, { "code": null, "e": 3320, "s": 3229, "text": "Identity − A unique value that distinguishes an object from a set of similar such objects." }, { "code": null, "e": 3411, "s": 3320, "text": "Identity − A unique value that distinguishes an object from a set of similar such objects." }, { "code": null, "e": 3522, "s": 3411, "text": "Class − A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object." }, { "code": null, "e": 3633, "s": 3522, "text": "Class − A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object." }, { "code": null, "e": 3692, "s": 3633, "text": "Method − Methods facilitate communication between objects." }, { "code": null, "e": 3751, "s": 3692, "text": "Method − Methods facilitate communication between objects." }, { "code": null, "e": 4005, "s": 3751, "text": "Let us translate these Object-Oriented concepts to the ones in the real world. For example: A car is an object that has data (make, model, number of doors, Vehicle Number, etc.) and functionality (accelerate, shift, open doors, turn on headlights, etc.)" }, { "code": null, "e": 4111, "s": 4005, "text": "Prior to ES6, creating a class was a fussy affair. Classes can be created using the class keyword in ES6." }, { "code": null, "e": 4203, "s": 4111, "text": "Classes can be included in the code either by declaring them or by using class expressions." }, { "code": null, "e": 4227, "s": 4203, "text": "class Class_name { \n}\n" }, { "code": null, "e": 4265, "s": 4227, "text": "var var_name = new Class_name { \n} \n" }, { "code": null, "e": 4401, "s": 4265, "text": "The class keyword is followed by the class name. The rules for identifiers (already discussed) must be considered while naming a class." }, { "code": null, "e": 4448, "s": 4401, "text": "A class definition can include the following −" }, { "code": null, "e": 4527, "s": 4448, "text": "Constructors − Responsible for allocating memory for the objects of the class." }, { "code": null, "e": 4606, "s": 4527, "text": "Constructors − Responsible for allocating memory for the objects of the class." }, { "code": null, "e": 4713, "s": 4606, "text": "Functions − Functions represent actions an object can take. They are also at times referred to as methods." }, { "code": null, "e": 4820, "s": 4713, "text": "Functions − Functions represent actions an object can take. They are also at times referred to as methods." }, { "code": null, "e": 4895, "s": 4820, "text": "These components put together are termed as the data members of the class." }, { "code": null, "e": 4966, "s": 4895, "text": "Note − A class body can only contain methods, but not data properties." }, { "code": null, "e": 5080, "s": 4966, "text": "class Polygon { \n constructor(height, width) { \n this.height = height; \n this.width = width; \n } \n}" }, { "code": null, "e": 5200, "s": 5080, "text": "var Polygon = class { \n constructor(height, width) { \n this.height = height; \n this.width = width; \n } \n}" }, { "code": null, "e": 5307, "s": 5200, "text": "The above code snippet represents an unnamed class expression. A named class expression can be written as." }, { "code": null, "e": 5435, "s": 5307, "text": "var Polygon = class Polygon { \n constructor(height, width) { \n this.height = height; \n this.width = width; \n } \n}" }, { "code": null, "e": 5501, "s": 5435, "text": "Note − Unlike variables and functions, classes cannot be hoisted." }, { "code": null, "e": 5623, "s": 5501, "text": "To create an instance of the class, use the new keyword followed by the class name. Following is the syntax for the same." }, { "code": null, "e": 5672, "s": 5623, "text": "var object_name= new class_name([ arguments ]) \n" }, { "code": null, "e": 5679, "s": 5672, "text": "Where," }, { "code": null, "e": 5729, "s": 5679, "text": "The new keyword is responsible for instantiation." }, { "code": null, "e": 5779, "s": 5729, "text": "The new keyword is responsible for instantiation." }, { "code": null, "e": 5906, "s": 5779, "text": "The right hand side of the expression invokes the constructor. The constructor should be passed values if it is parameterized." }, { "code": null, "e": 6033, "s": 5906, "text": "The right hand side of the expression invokes the constructor. The constructor should be passed values if it is parameterized." }, { "code": null, "e": 6062, "s": 6033, "text": "var obj = new Polygon(10,12)" }, { "code": null, "e": 6220, "s": 6062, "text": "A class’s attributes and functions can be accessed through the object. Use the ‘.’ dot notation (called as the period) to access the data members of a class." }, { "code": null, "e": 6265, "s": 6220, "text": "//accessing a function \nobj.function_name()\n" }, { "code": null, "e": 6601, "s": 6265, "text": "'use strict' \nclass Polygon { \n constructor(height, width) { \n this.h = height; \n this.w = width;\n } \n test() { \n console.log(\"The height of the polygon: \", this.h) \n console.log(\"The width of the polygon: \",this. w) \n } \n} \n\n//creating an instance \nvar polyObj = new Polygon(10,20); \npolyObj.test(); " }, { "code": null, "e": 6997, "s": 6601, "text": "The Example given above declares a class ‘Polygon’. The class’s constructor takes two arguments - height and width respectively. The ‘this’ keyword refers to the current instance of the class. In other words, the constructor above initializes two variables h and w with the parameter values passed to the constructor. The test () function in the class, prints the values of the height and width." }, { "code": null, "e": 7167, "s": 6997, "text": "To make the script functional, an object of the class Polygon is created. The object is referred to by the polyObj variable. The function is then called via this object." }, { "code": null, "e": 7244, "s": 7167, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 7308, "s": 7244, "text": "The height of the polygon: 10 \nThe width of the polygon: 20 \n" }, { "code": null, "e": 7506, "s": 7308, "text": "A setter function is invoked when there is an attempt to set the value of a property. The set keyword is used to define a setter function. The syntax for defining a setter function is given below −" }, { "code": null, "e": 7567, "s": 7506, "text": "{set prop(val) { . . . }}\n{set [expression](val) { . . . }}\n" }, { "code": null, "e": 7806, "s": 7567, "text": "prop is the name of the property to bind to the given function. val is an alias for the variable that holds the value attempted to be assigned to property. expression with ES6, can be used as a property name to bind to the given function." }, { "code": null, "e": 8250, "s": 7806, "text": "<script>\n class Student {\n constructor(rno,fname,lname){\n this.rno = rno\n this.fname = fname\n this.lname = lname\n console.log('inside constructor')\n }\n set rollno(newRollno){\n console.log(\"inside setter\")\n this.rno = newRollno\n }\n }\n let s1 = new Student(101,'Sachin','Tendulkar')\n console.log(s1)\n //setter is called\n s1.rollno = 201\n console.log(s1)\n</script>" }, { "code": null, "e": 8417, "s": 8250, "text": "The above example defines a class Student with three properties namely rno, fname and lname. A setter function rollno() is used to set the value for the rno property." }, { "code": null, "e": 8471, "s": 8417, "text": "The output of the above code will be as shown below −" }, { "code": null, "e": 8617, "s": 8471, "text": "inside constructor\nStudent {rno: 101, fname: \"Sachin\", lname: \"Tendulkar\"}\ninside setter\nStudent {rno: 201, fname: \"Sachin\", lname: \"Tendulkar\"}\n" }, { "code": null, "e": 8713, "s": 8617, "text": "The following example shows how to use an expression as a property name with a setter function." }, { "code": null, "e": 8917, "s": 8713, "text": "<script>\n let expr = 'name';\n let obj = {\n fname: 'Sachin',\n set [expr](v) { this.fname = v; }\n };\n console.log(obj.fname);\n obj.name = 'John';\n console.log(obj.fname);\n</script>" }, { "code": null, "e": 8975, "s": 8917, "text": "The output of the above code will be as mentioned below −" }, { "code": null, "e": 8988, "s": 8975, "text": "Sachin\nJohn\n" }, { "code": null, "e": 9188, "s": 8988, "text": "A getter function is invoked when there is an attempt to fetch the value of a property. The get keyword is used to define a getter function. The syntax for defining a getter function is given below −" }, { "code": null, "e": 9241, "s": 9188, "text": "{get prop() { ... } }\n{get [expression]() { ... } }\n" }, { "code": null, "e": 9305, "s": 9241, "text": "prop is the name of the property to bind to the given function." }, { "code": null, "e": 9416, "s": 9305, "text": "expression − Starting with ES6, you can also use expressions as a property name to bind to the given function." }, { "code": null, "e": 9859, "s": 9416, "text": "<script>\n class Student {\n constructor(rno,fname,lname){\n this.rno = rno\n this.fname = fname\n this.lname = lname\n console.log('inside constructor')\n }\n get fullName(){\n console.log('inside getter')\n return this.fname + \" - \"+this.lname\n }\n }\n let s1 = new Student(101,'Sachin','Tendulkar')\n console.log(s1)\n //getter is called\n console.log(s1.fullName)\n</script>" }, { "code": null, "e": 10042, "s": 9859, "text": "The above example defines a class Student with three properties namely rno, fname and lname. The getter function fullName() concatenates the fname and lname and returns a new string." }, { "code": null, "e": 10096, "s": 10042, "text": "The output of the above code will be as given below −" }, { "code": null, "e": 10205, "s": 10096, "text": "inside constructor\nStudent {rno: 101, fname: \"Sachin\", lname: \"Tendulkar\"}\ninside getter\nSachin - Tendulkar\n" }, { "code": null, "e": 10302, "s": 10205, "text": "The following example shows how to use an expression as a property name with a getter function −" }, { "code": null, "e": 10430, "s": 10302, "text": "<script>\n let expr = 'name';\n let obj = {\n get [expr]() { return 'Sachin'; }\n };\n console.log(obj.name);\n</script>" }, { "code": null, "e": 10488, "s": 10430, "text": "The output of the above code will be as mentioned below −" }, { "code": null, "e": 10496, "s": 10488, "text": "Sachin\n" }, { "code": null, "e": 10604, "s": 10496, "text": "The static keyword can be applied to functions in a class. Static members are referenced by the class name." }, { "code": null, "e": 10754, "s": 10604, "text": "'use strict' \nclass StaticMem { \n static disp() { \n console.log(\"Static Function called\") \n } \n} \nStaticMem.disp() //invoke the static metho" }, { "code": null, "e": 10871, "s": 10754, "text": "Note − It is not mandatory to include a constructor definition. Every class by default has a constructor by default." }, { "code": null, "e": 10948, "s": 10871, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 10972, "s": 10948, "text": "Static Function called\n" }, { "code": null, "e": 11054, "s": 10972, "text": "The instanceof operator returns true if the object belongs to the specified type." }, { "code": null, "e": 11207, "s": 11054, "text": "'use strict' \nclass Person{ } \nvar obj = new Person() \nvar isPerson = obj instanceof Person; \nconsole.log(\" obj is an instance of Person \" + isPerson); " }, { "code": null, "e": 11284, "s": 11207, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 11320, "s": 11284, "text": "obj is an instance of Person True \n" }, { "code": null, "e": 11615, "s": 11320, "text": "ES6 supports the concept of Inheritance. Inheritance is the ability of a program to create new entities from an existing entity - here a class. The class that is extended to create newer classes is called the parent class/super class. The newly created classes are called the child/sub classes." }, { "code": null, "e": 11772, "s": 11615, "text": "A class inherits from another class using the ‘extends’ keyword. Child classes inherit all properties and methods except constructors from the parent class." }, { "code": null, "e": 11810, "s": 11772, "text": "Following is the syntax for the same." }, { "code": null, "e": 11860, "s": 11810, "text": "class child_class_name extends parent_class_name\n" }, { "code": null, "e": 12085, "s": 11860, "text": "'use strict' \nclass Shape { \n constructor(a) { \n this.Area = a\n } \n} \nclass Circle extends Shape { \n disp() { \n console.log(\"Area of the circle: \"+this.Area) \n } \n} \nvar obj = new Circle(223); \nobj.disp() " }, { "code": null, "e": 12340, "s": 12085, "text": "The above example declares a class Shape. The class is extended by the Circle class. Since, there is an inheritance relationship between the classes, the child class i.e., the class Circle gets an implicit access to its parent class attribute i.e., area." }, { "code": null, "e": 12417, "s": 12340, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 12438, "s": 12417, "text": "Area of Circle: 223\n" }, { "code": null, "e": 12473, "s": 12438, "text": "Inheritance can be classified as −" }, { "code": null, "e": 12540, "s": 12473, "text": "Single − Every class can at the most extend from one parent class." }, { "code": null, "e": 12607, "s": 12540, "text": "Single − Every class can at the most extend from one parent class." }, { "code": null, "e": 12704, "s": 12607, "text": "Multiple − A class can inherit from multiple classes. ES6 doesn’t support multiple inheritance." }, { "code": null, "e": 12801, "s": 12704, "text": "Multiple − A class can inherit from multiple classes. ES6 doesn’t support multiple inheritance." }, { "code": null, "e": 12847, "s": 12801, "text": "Multi-level − Consider the following example." }, { "code": null, "e": 12893, "s": 12847, "text": "Multi-level − Consider the following example." }, { "code": null, "e": 13141, "s": 12893, "text": "'use strict' \nclass Root { \n test() { \n console.log(\"call from parent class\") \n } \n} \nclass Child extends Root {} \nclass Leaf extends Child \n\n//indirectly inherits from Root by virtue of inheritance {} \nvar obj = new Leaf();\nobj.test() " }, { "code": null, "e": 13252, "s": 13141, "text": "The class Leaf derives the attributes from the Root and the Child classes by virtue of multilevel inheritance." }, { "code": null, "e": 13329, "s": 13252, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 13353, "s": 13329, "text": "call from parent class\n" }, { "code": null, "e": 13489, "s": 13353, "text": "Method Overriding is a mechanism by which the child class redefines the superclass method. The following example illustrates the same −" }, { "code": null, "e": 13777, "s": 13489, "text": "'use strict' ;\nclass PrinterClass { \n doPrint() { \n console.log(\"doPrint() from Parent called... \");\n }\n}\nclass StringPrinter extends PrinterClass { \n doPrint() { \n console.log(\"doPrint() is printing a string...\"); \n } \n} \nvar obj = new StringPrinter(); \nobj.doPrint();" }, { "code": null, "e": 13869, "s": 13777, "text": "In the above Example, the child class has changed the superclass function’s implementation." }, { "code": null, "e": 13946, "s": 13869, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 13982, "s": 13946, "text": "doPrint() is printing a string... \n" }, { "code": null, "e": 14164, "s": 13982, "text": "ES6 enables a child class to invoke its parent class data member. This is achieved by using the super keyword. The super keyword is used to refer to the immediate parent of a class." }, { "code": null, "e": 14197, "s": 14164, "text": "Consider the following example −" }, { "code": null, "e": 14505, "s": 14197, "text": "'use strict' \nclass PrinterClass { \n doPrint() {\n console.log(\"doPrint() from Parent called...\") \n } \n} \nclass StringPrinter extends PrinterClass { \n doPrint() { \n super.doPrint() \n console.log(\"doPrint() is printing a string...\") \n } \n} \nvar obj = new StringPrinter() \nobj.doPrint()" }, { "code": null, "e": 14724, "s": 14505, "text": "The doPrint() redefinition in the class StringWriter, issues a call to its parent class version. In other words, the super keyword is used to invoke the doPrint() function definition in the parent class - PrinterClass." }, { "code": null, "e": 14801, "s": 14724, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 14866, "s": 14801, "text": "doPrint() from Parent called. \ndoPrint() is printing a string. \n" }, { "code": null, "e": 14901, "s": 14866, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 14915, "s": 14901, "text": " Sharad Kumar" }, { "code": null, "e": 14948, "s": 14915, "text": "\n 40 Lectures \n 5 hours \n" }, { "code": null, "e": 14966, "s": 14948, "text": " Richa Maheshwari" }, { "code": null, "e": 14999, "s": 14966, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 15013, "s": 14999, "text": " Anadi Sharma" }, { "code": null, "e": 15048, "s": 15013, "text": "\n 50 Lectures \n 6.5 hours \n" }, { "code": null, "e": 15065, "s": 15048, "text": " Gowthami Swarna" }, { "code": null, "e": 15098, "s": 15065, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 15114, "s": 15098, "text": " Deepti Trivedi" }, { "code": null, "e": 15149, "s": 15114, "text": "\n 31 Lectures \n 1.5 hours \n" }, { "code": null, "e": 15157, "s": 15149, "text": " Shweta" }, { "code": null, "e": 15164, "s": 15157, "text": " Print" }, { "code": null, "e": 15175, "s": 15164, "text": " Add Notes" } ]
Real-time Object Detection Without Machine Learning | by Jamie Bullock | Towards Data Science
Earlier this year Nick Bourdakos, a software developer at IBM posted a series of videos demoing real-time object detection in a web browser. One of his early videos went viral, receiving over 16,000 likes and 900+ comments on LinkedIn. Here’s the original post: www.linkedin.com The video shows three bottles (Coke, Pepsi, and Mountain Dew) being recognised by the computer in real-time as they are held up to the camera. When each bottle is detected, it is given a text label and a bounding box is drawn around it. If more than one bottle is held up, the system will correctly label the different bottles. Nick’s system has now evolved into IBM cloud annotations, but the demo above used TensorFlow.js along with the COCO-SSD deep learning model. SSD, or Single Shot MultiBox Detector, is a widely used technique for detecting multiple sub-images in a frame, described in detail here. This is a task deep learning excels at and these techniques are now so widespread, you probably have a deep learning network in your pocket, running your phone’s object detection for photos or social networking apps. Inspired by Nick’s post, I decided to challenge myself to explore if similar results could be achieved without the use of machine learning. It struck me that the bottles used in the original demo could be detected based on their colour or other characteristics along with some simple matching rules. This is known as an heuristic approach to problem solving. Potential advantages of this include: Ease of development and conceptualisation Lower CPU and memory use Fewer dependencies In terms of CPU and memory, on my i5 MacBook Pro, the IBM Cloud Annotations demo uses over 100% CPU and more than 1.5 Gigabytes of RAM. It also relies on a web browser and some heavy dependencies including Tensorflow, React.js, node.js and COCO-SSD itself. The rules I set myself are: Coke, Pepsi and Mountain Dew bottles must be labelled correctlyA rectangle should be drawn around each bottle as it movesMinimal codeNo machine learning techniques! Coke, Pepsi and Mountain Dew bottles must be labelled correctly A rectangle should be drawn around each bottle as it moves Minimal code No machine learning techniques! The original demo claims to use only 10 lines of code, however including boilerplate, the current demo is 107 lines of JavaScript. I think under 100 lines is a good aim for this task. Firstly, I decided to base my project in OpenCV since I have previously used it for work projects, it has relatively easy setup and is designed specifically for computer vision. OpenCV is written in C++ and has bindings in Python and JavaScript. I decided to go with the Python version for convenience. I started with just recognising a Coke bottle. For this, a naïve solution would be to analyse the colours in a video frame and place a label where coke red is found. One problem here is that depending on the lighting conditions and camera colour accuracy, the bottle label is unlikely to be exactly RGB 244 0 0. To solve this, we can use a HSV colour representation along with cv::inRange to find colours within the image that are within a given range. Think “shades of red”. This gives us an image mask with all the red coloured areas white and everything else black. We can then use cv::findContours to supply a list of points that define each “red area” within the frame. The basic code will look something like this: mask = cv2.inRange(hsv, colour.lower, colour.upper)conts, heirarchy = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)biggest = sorted(conts, key=cv2.contourArea, reverse=True)[0] The third line of code sorts the detected “red” contours and returns the largest one. Done! ...right? Well unfortunately not. Left like this, the program often finds Coke in the image even when there is none. To deal with this we need an additional heuristic. I found simply excluding any contour smaller than 50×50 worked well enough. if w < 50 or h < 50: continue Finally, for our detection system to work well, we need to exclude colours that are found “inside” other colours. For example both the Pepsi and Mountain Dew labels contain red, which will get detected as Coke unless we exclude it. So we add a special heuristic for Coke that ignores detection if it is within the vertical bounds of another bottle. if name == "Coke": if any([contains_vertical(rects[n], rect) for n in rects]): continue Putting it all together, here is a working demonstration of the final system. Clip ID: 374957292 Delivery:application/vnd.vimeo.dash+json Embed Size:692×389 Separate AV:true Dropped Frames:0 / 0 - 0 Playhead / Buffer:0 / 0 / 0 Bandwidth:0(0 Kbps0 Kbps) On my i5 MacBook Pro this runs smoothly at around 45% CPU with just over 50MB RAM. The full source code comes to 85 lines and is available here. One of the limitations of this colour-based approach is that it doesn’t place the bounding box around the bottle but only the coloured area. We could define additional rules to consider the colour above or below the detected region, or attempt to guess where the bounding box should be, but the code would quickly become complicated. Another limitation is that whilst our system can recognise a Coke and a Pepsi bottle at the same time, it can’t detect two Coke bottles. We could add further heuristics to deal with this but I would question if an heuristic approach is the right choice if so much complexity needs to be added. I have shown that it’s straightforward to build a heuristic detector with accuracy comparable to that of a deep learning-based system for a highly constrained task. Furthermore, the heuristic object detector is conceptually simpler, has fewer dependencies, takes significantly less CPU and uses an order-of-magnitude less memory. However, the heuristic approach is not as robust or accurate as using deep learning. A deep learning system can trivially recognise multiple instances of the same object at different scales and rotations, depending on how it is trained. It can also do things like recognise partial objects even if key features are missing. For me, this isn’t a clear win for deep learning and I think there still is a place for an heuristic approach. The more assumptions that can be made about the detection conditions (consistent background and / or scale, constrained object types, distinguishing features such as colour) the more appeal heuristics have. As a developer, I would consider a heuristic based solution if time and resources were tight and the input constraints were clearly defined. If I wanted increased robustness and flexibility, I would opt for machine learning. Both approaches definitely have their place, and it’s a question of choosing the right tool for the job.
[ { "code": null, "e": 434, "s": 172, "text": "Earlier this year Nick Bourdakos, a software developer at IBM posted a series of videos demoing real-time object detection in a web browser. One of his early videos went viral, receiving over 16,000 likes and 900+ comments on LinkedIn. Here’s the original post:" }, { "code": null, "e": 451, "s": 434, "text": "www.linkedin.com" }, { "code": null, "e": 779, "s": 451, "text": "The video shows three bottles (Coke, Pepsi, and Mountain Dew) being recognised by the computer in real-time as they are held up to the camera. When each bottle is detected, it is given a text label and a bounding box is drawn around it. If more than one bottle is held up, the system will correctly label the different bottles." }, { "code": null, "e": 1275, "s": 779, "text": "Nick’s system has now evolved into IBM cloud annotations, but the demo above used TensorFlow.js along with the COCO-SSD deep learning model. SSD, or Single Shot MultiBox Detector, is a widely used technique for detecting multiple sub-images in a frame, described in detail here. This is a task deep learning excels at and these techniques are now so widespread, you probably have a deep learning network in your pocket, running your phone’s object detection for photos or social networking apps." }, { "code": null, "e": 1634, "s": 1275, "text": "Inspired by Nick’s post, I decided to challenge myself to explore if similar results could be achieved without the use of machine learning. It struck me that the bottles used in the original demo could be detected based on their colour or other characteristics along with some simple matching rules. This is known as an heuristic approach to problem solving." }, { "code": null, "e": 1672, "s": 1634, "text": "Potential advantages of this include:" }, { "code": null, "e": 1714, "s": 1672, "text": "Ease of development and conceptualisation" }, { "code": null, "e": 1739, "s": 1714, "text": "Lower CPU and memory use" }, { "code": null, "e": 1758, "s": 1739, "text": "Fewer dependencies" }, { "code": null, "e": 2015, "s": 1758, "text": "In terms of CPU and memory, on my i5 MacBook Pro, the IBM Cloud Annotations demo uses over 100% CPU and more than 1.5 Gigabytes of RAM. It also relies on a web browser and some heavy dependencies including Tensorflow, React.js, node.js and COCO-SSD itself." }, { "code": null, "e": 2043, "s": 2015, "text": "The rules I set myself are:" }, { "code": null, "e": 2208, "s": 2043, "text": "Coke, Pepsi and Mountain Dew bottles must be labelled correctlyA rectangle should be drawn around each bottle as it movesMinimal codeNo machine learning techniques!" }, { "code": null, "e": 2272, "s": 2208, "text": "Coke, Pepsi and Mountain Dew bottles must be labelled correctly" }, { "code": null, "e": 2331, "s": 2272, "text": "A rectangle should be drawn around each bottle as it moves" }, { "code": null, "e": 2344, "s": 2331, "text": "Minimal code" }, { "code": null, "e": 2376, "s": 2344, "text": "No machine learning techniques!" }, { "code": null, "e": 2560, "s": 2376, "text": "The original demo claims to use only 10 lines of code, however including boilerplate, the current demo is 107 lines of JavaScript. I think under 100 lines is a good aim for this task." }, { "code": null, "e": 2863, "s": 2560, "text": "Firstly, I decided to base my project in OpenCV since I have previously used it for work projects, it has relatively easy setup and is designed specifically for computer vision. OpenCV is written in C++ and has bindings in Python and JavaScript. I decided to go with the Python version for convenience." }, { "code": null, "e": 3176, "s": 2863, "text": "I started with just recognising a Coke bottle. For this, a naïve solution would be to analyse the colours in a video frame and place a label where coke red is found. One problem here is that depending on the lighting conditions and camera colour accuracy, the bottle label is unlikely to be exactly RGB 244 0 0." }, { "code": null, "e": 3585, "s": 3176, "text": "To solve this, we can use a HSV colour representation along with cv::inRange to find colours within the image that are within a given range. Think “shades of red”. This gives us an image mask with all the red coloured areas white and everything else black. We can then use cv::findContours to supply a list of points that define each “red area” within the frame. The basic code will look something like this:" }, { "code": null, "e": 3788, "s": 3585, "text": "mask = cv2.inRange(hsv, colour.lower, colour.upper)conts, heirarchy = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)biggest = sorted(conts, key=cv2.contourArea, reverse=True)[0]" }, { "code": null, "e": 3997, "s": 3788, "text": "The third line of code sorts the detected “red” contours and returns the largest one. Done! ...right? Well unfortunately not. Left like this, the program often finds Coke in the image even when there is none." }, { "code": null, "e": 4124, "s": 3997, "text": "To deal with this we need an additional heuristic. I found simply excluding any contour smaller than 50×50 worked well enough." }, { "code": null, "e": 4157, "s": 4124, "text": "if w < 50 or h < 50: continue" }, { "code": null, "e": 4506, "s": 4157, "text": "Finally, for our detection system to work well, we need to exclude colours that are found “inside” other colours. For example both the Pepsi and Mountain Dew labels contain red, which will get detected as Coke unless we exclude it. So we add a special heuristic for Coke that ignores detection if it is within the vertical bounds of another bottle." }, { "code": null, "e": 4604, "s": 4506, "text": "if name == \"Coke\": if any([contains_vertical(rects[n], rect) for n in rects]): continue" }, { "code": null, "e": 4682, "s": 4604, "text": "Putting it all together, here is a working demonstration of the final system." }, { "code": null, "e": 4701, "s": 4682, "text": "Clip ID: 374957292" }, { "code": null, "e": 4742, "s": 4701, "text": "Delivery:application/vnd.vimeo.dash+json" }, { "code": null, "e": 4762, "s": 4742, "text": "Embed Size:692×389 " }, { "code": null, "e": 4779, "s": 4762, "text": "Separate AV:true" }, { "code": null, "e": 4804, "s": 4779, "text": "Dropped Frames:0 / 0 - 0" }, { "code": null, "e": 4832, "s": 4804, "text": "Playhead / Buffer:0 / 0 / 0" }, { "code": null, "e": 4858, "s": 4832, "text": "Bandwidth:0(0 Kbps0 Kbps)" }, { "code": null, "e": 5003, "s": 4858, "text": "On my i5 MacBook Pro this runs smoothly at around 45% CPU with just over 50MB RAM. The full source code comes to 85 lines and is available here." }, { "code": null, "e": 5337, "s": 5003, "text": "One of the limitations of this colour-based approach is that it doesn’t place the bounding box around the bottle but only the coloured area. We could define additional rules to consider the colour above or below the detected region, or attempt to guess where the bounding box should be, but the code would quickly become complicated." }, { "code": null, "e": 5631, "s": 5337, "text": "Another limitation is that whilst our system can recognise a Coke and a Pepsi bottle at the same time, it can’t detect two Coke bottles. We could add further heuristics to deal with this but I would question if an heuristic approach is the right choice if so much complexity needs to be added." }, { "code": null, "e": 5961, "s": 5631, "text": "I have shown that it’s straightforward to build a heuristic detector with accuracy comparable to that of a deep learning-based system for a highly constrained task. Furthermore, the heuristic object detector is conceptually simpler, has fewer dependencies, takes significantly less CPU and uses an order-of-magnitude less memory." }, { "code": null, "e": 6285, "s": 5961, "text": "However, the heuristic approach is not as robust or accurate as using deep learning. A deep learning system can trivially recognise multiple instances of the same object at different scales and rotations, depending on how it is trained. It can also do things like recognise partial objects even if key features are missing." } ]
Java Program to convert String to Double
To convert String to Double in Java, you can use the following three examples. Two of them are using in-built methods parseDouble() and valueOf(). However, one of the method isn’t using a method. Let us work through them one by one. The following is an example to convert String to Double without using a method − Live Demo public class Demo { public static void main(String args[]) { Double val = new Double("88.77"); System.out.println(val); } } 88.77 The following is another example to convert String to Double. Here, we will use parseDouble() method − Live Demo public class Demo { public static void main(String args[]) { double val = Double.parseDouble("11.89"); System.out.println(val); } } 11.89 Let us see an example to convert String to Double using valueOf() method − Live Demo public class Demo { public static void main(String args[]) { Double val = Double.valueOf("299.9"); System.out.println(val); } } 299.9
[ { "code": null, "e": 1258, "s": 1062, "text": "To convert String to Double in Java, you can use the following three examples. Two of them are using in-built methods parseDouble() and valueOf(). However, one of the method isn’t using a method." }, { "code": null, "e": 1295, "s": 1258, "text": "Let us work through them one by one." }, { "code": null, "e": 1376, "s": 1295, "text": "The following is an example to convert String to Double without using a method −" }, { "code": null, "e": 1387, "s": 1376, "text": " Live Demo" }, { "code": null, "e": 1533, "s": 1387, "text": "public class Demo {\n public static void main(String args[]) {\n Double val = new Double(\"88.77\");\n System.out.println(val);\n }\n}" }, { "code": null, "e": 1539, "s": 1533, "text": "88.77" }, { "code": null, "e": 1642, "s": 1539, "text": "The following is another example to convert String to Double. Here, we will use parseDouble() method −" }, { "code": null, "e": 1653, "s": 1642, "text": " Live Demo" }, { "code": null, "e": 1807, "s": 1653, "text": "public class Demo {\n public static void main(String args[]) {\n double val = Double.parseDouble(\"11.89\");\n System.out.println(val);\n }\n}" }, { "code": null, "e": 1813, "s": 1807, "text": "11.89" }, { "code": null, "e": 1888, "s": 1813, "text": "Let us see an example to convert String to Double using valueOf() method −" }, { "code": null, "e": 1899, "s": 1888, "text": " Live Demo" }, { "code": null, "e": 2049, "s": 1899, "text": "public class Demo {\n public static void main(String args[]) {\n Double val = Double.valueOf(\"299.9\");\n System.out.println(val);\n }\n}" }, { "code": null, "e": 2055, "s": 2049, "text": "299.9" } ]
Permutation hypothesis test in R. Exploring a powerful simulation... | by Serafim Petrov | Towards Data Science
To compare outcomes in experiments, we often use Student’s t-test. It assumes that data are randomly selected from the population, arrived in large samples (>30), or normally distributed with equal variances between groups.If we do not happen to meet these assumptions, we may use one of the simulation tests. In this article, we will introduce the Permutation Test. Rather than assuming underlying distribution, the permutation test builds its distribution, breaking up the associations between or among groups. Often we are interested in the difference of means or medians between the groups, and the null hypothesis is that there is no difference there. We may ask the question: from all the possible permutations, how extreme our data would look like? All possible permutations would represent a theoretical distribution. In practice, there is no need to perform ALL permutations to build the theoretical distribution, but run a reasonable number of simulations to take a sample from that distribution. Usually, there are 10k or 100k simulations. Suppose we have a chain of 12 retail stores, and we want to test a new sales technique. We may assign or just pick, for instance, 5 stores and try it there. Then compare average sales after a certain period with sales in the rest 7 stores. The data are not randomly collected, presumably not normally distributed; and the sample itself has fewer than 30 observations.In our dataset, we have two columns: treatment — a binary variable indicating whether the store implemented the new approach; outcome — a numeric variable recoding a sales amount at the end of a period. From the boxplot representation, we may see that the groups are fairly different and the variance is approximately equal. The histogram of outcome does not appear normally distributed; however, the Shapiro-Wilk normality test returns a not significant p-value = 0.3654 To find the difference in means between groups, we use build-in commands and save it to a variable original: original <- diff(tapply(outcome, treatment, mean)) The difference is ~37.8 points. Now we ask the question: if we shuffle the data ten thousand times, how often we would observe this or more extreme difference? We run a simulation drawing 10k shaffles without replacement, and record the difference in means for each permutation. Then we perform a two-sided test computing the number of records the absolute value of whose exceeded absolute values of original difference. The function returns the simulated distribution and the p-value. If we plot the distribution, we may observe that our original difference is not particularly extreme, with an exact p-value of 0.1822818 In many research projects, this would indicate that there is no statistically significant difference between groups: however, in this business case, I would pick the option that there is some evidence that the sales approach affects the outcome. If we run the Welch t-test, we would get a similar p-value of 0.1815. The Shapiro-Wilk normality test indicated that the data were presumably obtained from the Normal Distribution, but it is not a general case. R also has several libraries to run permutation tests. One of them is library(coin), which performs an independence test. It also returns a similar p-value of 0.1858. The Permutation test is a powerful tool in measuring effects in experiments. It is easy to implement, and it does not rely on many assumptions as other tests do. It has not been widely popular until the simulation on computers became routinely implemented. It is closely related to the other simulation test: the bootstrapping hypothesis test, where the samples are drawn with replacement. Connect on LinkedIn
[ { "code": null, "e": 539, "s": 172, "text": "To compare outcomes in experiments, we often use Student’s t-test. It assumes that data are randomly selected from the population, arrived in large samples (>30), or normally distributed with equal variances between groups.If we do not happen to meet these assumptions, we may use one of the simulation tests. In this article, we will introduce the Permutation Test." }, { "code": null, "e": 1223, "s": 539, "text": "Rather than assuming underlying distribution, the permutation test builds its distribution, breaking up the associations between or among groups. Often we are interested in the difference of means or medians between the groups, and the null hypothesis is that there is no difference there. We may ask the question: from all the possible permutations, how extreme our data would look like? All possible permutations would represent a theoretical distribution. In practice, there is no need to perform ALL permutations to build the theoretical distribution, but run a reasonable number of simulations to take a sample from that distribution. Usually, there are 10k or 100k simulations." }, { "code": null, "e": 1463, "s": 1223, "text": "Suppose we have a chain of 12 retail stores, and we want to test a new sales technique. We may assign or just pick, for instance, 5 stores and try it there. Then compare average sales after a certain period with sales in the rest 7 stores." }, { "code": null, "e": 1793, "s": 1463, "text": "The data are not randomly collected, presumably not normally distributed; and the sample itself has fewer than 30 observations.In our dataset, we have two columns: treatment — a binary variable indicating whether the store implemented the new approach; outcome — a numeric variable recoding a sales amount at the end of a period." }, { "code": null, "e": 1915, "s": 1793, "text": "From the boxplot representation, we may see that the groups are fairly different and the variance is approximately equal." }, { "code": null, "e": 2062, "s": 1915, "text": "The histogram of outcome does not appear normally distributed; however, the Shapiro-Wilk normality test returns a not significant p-value = 0.3654" }, { "code": null, "e": 2171, "s": 2062, "text": "To find the difference in means between groups, we use build-in commands and save it to a variable original:" }, { "code": null, "e": 2222, "s": 2171, "text": "original <- diff(tapply(outcome, treatment, mean))" }, { "code": null, "e": 2382, "s": 2222, "text": "The difference is ~37.8 points. Now we ask the question: if we shuffle the data ten thousand times, how often we would observe this or more extreme difference?" }, { "code": null, "e": 2643, "s": 2382, "text": "We run a simulation drawing 10k shaffles without replacement, and record the difference in means for each permutation. Then we perform a two-sided test computing the number of records the absolute value of whose exceeded absolute values of original difference." }, { "code": null, "e": 2708, "s": 2643, "text": "The function returns the simulated distribution and the p-value." }, { "code": null, "e": 2845, "s": 2708, "text": "If we plot the distribution, we may observe that our original difference is not particularly extreme, with an exact p-value of 0.1822818" }, { "code": null, "e": 3091, "s": 2845, "text": "In many research projects, this would indicate that there is no statistically significant difference between groups: however, in this business case, I would pick the option that there is some evidence that the sales approach affects the outcome." }, { "code": null, "e": 3302, "s": 3091, "text": "If we run the Welch t-test, we would get a similar p-value of 0.1815. The Shapiro-Wilk normality test indicated that the data were presumably obtained from the Normal Distribution, but it is not a general case." }, { "code": null, "e": 3469, "s": 3302, "text": "R also has several libraries to run permutation tests. One of them is library(coin), which performs an independence test. It also returns a similar p-value of 0.1858." }, { "code": null, "e": 3726, "s": 3469, "text": "The Permutation test is a powerful tool in measuring effects in experiments. It is easy to implement, and it does not rely on many assumptions as other tests do. It has not been widely popular until the simulation on computers became routinely implemented." }, { "code": null, "e": 3859, "s": 3726, "text": "It is closely related to the other simulation test: the bootstrapping hypothesis test, where the samples are drawn with replacement." } ]
What are Closures in Lua Programming?
In Lua, any function is a closure. In a narrower sense, a closure is an anonymous function like the returned function in your example. Closures are first-class: they can be assigned to variables, passed to functions and returned from them. They can be both keys and values in Lua tables. Unlike C++ or PHP, closures in Lua have access to all variables in local scope— upvalues with no need to declare upvalues explicitly. Upvalues survive when code execution leaves the block where they were set. Now that we know what a closure is and why it is useful, let’s take an example and see how it works. Consider the example shown below − Live Demo function simpleCounter() local i = 0 return function () -- anonymous function i = i + 1 return i end end c1 = simpleCounter() print(c1()) --> 1 print(c1()) --> 2 c2 = simpleCounter() print(c2()) --> 1 print(c1()) --> 3 print(c2()) --> 2 1 2 1 3 2
[ { "code": null, "e": 1197, "s": 1062, "text": "In Lua, any function is a closure. In a narrower sense, a closure is an anonymous function like the returned function in your example." }, { "code": null, "e": 1350, "s": 1197, "text": "Closures are first-class: they can be assigned to variables, passed to functions and returned from them. They can be both keys and values in Lua tables." }, { "code": null, "e": 1559, "s": 1350, "text": "Unlike C++ or PHP, closures in Lua have access to all variables in local scope— upvalues with no need to declare upvalues explicitly. Upvalues survive when code execution leaves the block where they were set." }, { "code": null, "e": 1660, "s": 1559, "text": "Now that we know what a closure is and why it is useful, let’s take an example and see how it works." }, { "code": null, "e": 1695, "s": 1660, "text": "Consider the example shown below −" }, { "code": null, "e": 1706, "s": 1695, "text": " Live Demo" }, { "code": null, "e": 1988, "s": 1706, "text": "function simpleCounter()\n local i = 0\n return function () -- anonymous function\n i = i + 1\n return i\n end\n end\nc1 = simpleCounter()\n print(c1()) --> 1\n print(c1()) --> 2\nc2 = simpleCounter()\n print(c2()) --> 1\n print(c1()) --> 3\n print(c2()) --> 2" }, { "code": null, "e": 1998, "s": 1988, "text": "1\n2\n1\n3\n2" } ]
Binary literals in C++14 with Examples - GeeksforGeeks
28 Jan, 2021 In this article, we will discuss Binary literals in C++14. While writing programs which involve mathematical evaluations or various types of number, we usually like to specify each digit type with specific prefix i.e., For Hexadecimal number use the prefix ‘0x’ and for Octal number use the prefix ‘0’. Below is the program to illustrate the same: Program 1: C++14 // C++ program to illustrate the// Hexadecimal and Octal number// using literals#include <iostream>using namespace std; // Driver Codeint main(){ // Hexadecimal number with // prefix '0x' int h = 0x13ac; // Octal number with prefix '0' int o = 0117; // Print the number of the // hexadecimal form cout << h << endl; // Print the number of the // octal form cout << o; return 0;} 5036 79 Binary Literals: In the above way like in hexadecimal and octal numbers, now we can directly write binary literals (of the form 0’s and 1’s) in C++14. The binary number can be expressed as 0b or 0B as the prefix. Below is the program to illustrate the same: Program 2: C++14 // C++ program to illustrate the// binary number using literals#include <iostream>using namespace std; // Driver Codeint main(){ // Binary literal with prefix '0b' int a = 0b00001111; cout << a << '\n'; // Binary literal with prefix '0B' int b = 0B00001111; cout << b; return 0;} 15 15 Technical Scripter 2020 C++ C++ Programs Technical Scripter CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Iterators in C++ STL Sorting a vector in C++ Header files in C/C++ and its uses C++ Program for QuickSort How to return multiple values from a function in C or C++? Program to print ASCII Value of a character CSV file management using C++
[ { "code": null, "e": 24124, "s": 24096, "text": "\n28 Jan, 2021" }, { "code": null, "e": 24183, "s": 24124, "text": "In this article, we will discuss Binary literals in C++14." }, { "code": null, "e": 24472, "s": 24183, "text": "While writing programs which involve mathematical evaluations or various types of number, we usually like to specify each digit type with specific prefix i.e., For Hexadecimal number use the prefix ‘0x’ and for Octal number use the prefix ‘0’. Below is the program to illustrate the same:" }, { "code": null, "e": 24483, "s": 24472, "text": "Program 1:" }, { "code": null, "e": 24489, "s": 24483, "text": "C++14" }, { "code": "// C++ program to illustrate the// Hexadecimal and Octal number// using literals#include <iostream>using namespace std; // Driver Codeint main(){ // Hexadecimal number with // prefix '0x' int h = 0x13ac; // Octal number with prefix '0' int o = 0117; // Print the number of the // hexadecimal form cout << h << endl; // Print the number of the // octal form cout << o; return 0;}", "e": 24913, "s": 24489, "text": null }, { "code": null, "e": 24922, "s": 24913, "text": "5036\n79\n" }, { "code": null, "e": 25180, "s": 24922, "text": "Binary Literals: In the above way like in hexadecimal and octal numbers, now we can directly write binary literals (of the form 0’s and 1’s) in C++14. The binary number can be expressed as 0b or 0B as the prefix. Below is the program to illustrate the same:" }, { "code": null, "e": 25191, "s": 25180, "text": "Program 2:" }, { "code": null, "e": 25197, "s": 25191, "text": "C++14" }, { "code": "// C++ program to illustrate the// binary number using literals#include <iostream>using namespace std; // Driver Codeint main(){ // Binary literal with prefix '0b' int a = 0b00001111; cout << a << '\\n'; // Binary literal with prefix '0B' int b = 0B00001111; cout << b; return 0;}", "e": 25505, "s": 25197, "text": null }, { "code": null, "e": 25512, "s": 25505, "text": "15\n15\n" }, { "code": null, "e": 25536, "s": 25512, "text": "Technical Scripter 2020" }, { "code": null, "e": 25540, "s": 25536, "text": "C++" }, { "code": null, "e": 25553, "s": 25540, "text": "C++ Programs" }, { "code": null, "e": 25572, "s": 25553, "text": "Technical Scripter" }, { "code": null, "e": 25576, "s": 25572, "text": "CPP" }, { "code": null, "e": 25674, "s": 25576, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25683, "s": 25674, "text": "Comments" }, { "code": null, "e": 25696, "s": 25683, "text": "Old Comments" }, { "code": null, "e": 25724, "s": 25696, "text": "Operator Overloading in C++" }, { "code": null, "e": 25744, "s": 25724, "text": "Polymorphism in C++" }, { "code": null, "e": 25777, "s": 25744, "text": "Friend class and function in C++" }, { "code": null, "e": 25798, "s": 25777, "text": "Iterators in C++ STL" }, { "code": null, "e": 25822, "s": 25798, "text": "Sorting a vector in C++" }, { "code": null, "e": 25857, "s": 25822, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 25883, "s": 25857, "text": "C++ Program for QuickSort" }, { "code": null, "e": 25942, "s": 25883, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 25986, "s": 25942, "text": "Program to print ASCII Value of a character" } ]
NewYork Taxi demand forecasting with SARIMAX using weather data | by Abdelkader BOUREGAG | Towards Data Science
Taxi demands prediction has become extremely important for taxi-hailing (and e-haling) companies as a way to understand their demand and to optimize their fleet management. In this article, we will present a method for predicting the number of taxi pickups in a certain region of NewYork. We will perform spatiotemporal time series analysis then we will apply the well-known statistical method SARIMAX on the aggregated data that includes the weather data. · We will be using NewYork Taxi demand public data available on: https://www1.nyc.gov/site/tlc/about/tlc-trip-record-data.page · Here we will use data from January 2015 to February 2016. · To quickly download the large Data from NYC dataset website to your google drive account you can follow my tutorial via this link. · For weather data, we will use data from the Visual Crossing provider: https://visualcrossing.com/weather-data Time-series forecasting is one of the hot research topics in the field of data science. Various models and approaches have been tested from statistical methods to deep neural networks. Machine learning enthusiast tend to jump directly to machine learning models when it comes to times series prediction avoiding statistical methods which, in a lot of cases, has shown better performance across both accuracy measures and for all forecasting horizons especially for univariate time series, let’s first get an idea on how to classify a time series problem. Dr Jason Brownlee in his book introduced a framework to classify a times series problem as follows: Inputs: Historical data provided to the model in order to make a single forecast. Outputs: Prediction or forecast for a future time step beyond the data provided as input. Endogenous: Input variables that are influenced by other variables in the system and on which the output variable depends. Exogenous: Input variables that are not influenced by other variables in the system and on which the output variable depends Forecast a numerical quantity vs Classify as one of two or more labels. One or multiple variables measured over time Forecast the next time step vs forecast more than one future time steps. fit the model once and used to make predictions vs fit the model on newly available data prior to each prediction Observations made are uniform vs observations are not uniform. Now that you got an idea about the type of time series problem we are in front of, let’s introduce the SARIMAX model: SARIMA stands for (Seasonal Autoregressive Integrated Moving Average) a variation of ARIMA model, a model used in univariate time series prediction, which supports the seasonal component of the series. It supports an autoregressive and a moving average component. It has three hyperparameters to specify the autoregression (AR), differencing (I),and moving average (MA) for the seasonal component of the series, as well as an additional parameter for the period of the seasonality. X stands for including Exogenous variables. · p: Trend autoregression order. · d: Trend difference order. · q: Trend moving average order. P: Seasonal autoregressive order. D: Seasonal difference order. Q: Seasonal moving average order. m: The number of time steps for a single seasonal period. Enough theory, let’s now get into the code ! Data cleaning/preprocessing is a very important step in any machine learning project, yet it’s a tiring step, if you are more interested in applying the SARIMAX method than cleaning the data you can skip this part since I will provide you structured and cleaned data via a drive folder, But it’s important to understand how the data was cleaned and structured. PS: Find the link to the cleaned data folder down in the section (Cleaned Data folder link) data_Jan_2015 = dd.read_csv("/content/drive/My Drive/nyc-data/yellow_tripdata_2015-01.csv")data_Jan_2015.head() We import the data of the first month of 2015 on dask dataframe, the data contains a lot of features, but I will present only the ones we’ll need for cleaning the data: tpep_pickup_datetime: the date and time of pickup tpep_dropoff_datetime: the date and time of dropoff pickup_longitude: longitude of the pickup pickup_latitude: latitude of the pickup dropoff_longitude: longitude of the dropoff dropoff_latitude: latitude of the dropoff trip_distance: the trip distance First, we select only the needed columns, calculate the trip_duration and speed to use it in the data cleaning processes. After preparing the data frame, we will process to remove the erroneous values by analyzing the quartiles graphs of each column: After printing the quartiles & percentiles we observe the 99.9th percentile of trip distance is 22.58miles, however, 100th percentile value is 15420004.9miles, which is very high. So, we are removing all the data points where trip distance is greater than 23miles. Doing the same process on other quantitative variables (ِCheck the GitHub repo for code) By visualizing some of the pickups and dropoff out of NewYork, some are in the ocean, these will be deleted from the data. After cleaning the demands out of NewYork, we proceed with clustering the demands by pickups using Kmeans algorithm. we divide it by 30 clusters. #Clustering pickupscoord = new_data_Jan_2015[["pickup_latitude", "pickup_longitude"]].valuesregions = MiniBatchKMeans(n_clusters = 30, batch_size = 10000).fit(coord)cluster_column = regions.predict(new_data_Jan_2015[["pickup_latitude", "pickup_longitude"]])new_data_Jan_2015["pickup_cluster"] = cluster_column Next, we will group demands by region. #Grouping the mounthly data by regionnew_data_Jan_2015.rename(columns={'tpep_pickup_datetime':'time','trip_distance':'demand',},inplace=True)new_data_Jan_2015['time'] = pd.to_datetime(new_data_Jan_2015['time'])grouped_new_data_Jan_2015 = new_data_Jan_2015[["pickup_cluster", "time", "demand"]].groupby(by = ["pickup_cluster", "time"]).count() Let’s visualise the regions: Finally, we prepare the demands of each cluster by adding weather components and resampling the demands by a time step of 1 hour. #Cluster examplecluster = grouped_new_data_Jan_2015.loc[0]#Resampling Data in region j into one hour stepcluster = cluster.resample('1h').sum()#Feature Engineeringcluster['Date time'] = cluster.indexcluster['Date time'] = pd.to_datetime(cluster['Date time'].dt.strftime('%Y-%m-%d %H'))cluster['hour']=cluster['Date time'].dt.hourcluster['day']=cluster['Date time'].dt.daycluster['dayofweek']=cluster['Date time'].dt.dayofweek#Merging with weather datadf_merge_col = pd.merge(cluster, weather_data, on='Date time')cluster['temperature'] = df_merge_col.Temperature.valuescluster['wind_speed'] = df_merge_col['Wind Speed'].valuescluster = cluster[['hour','day','dayofweek','temperature','wind_speed','demand']] The cluster (region) will look like this: This represents the time serie of demands in one region that we will feed to our model to predict future demands. Each region will be saved in a separate file. We will do the same steps to prepare the data of the other months ( preprocessing, cleaning, clustering, adding weather features, saving each region’s demands in the correspondent file) I am making available the cleaned data via this drive folder, Here you can find all the NewYork data cleaned and clustered by regions, we will use these files to train and test our model. Now we will start working on the prediction problem, we remind you that this is a time series forecasting problem, we need to test the stationarity of the time series to be able to apply SARIMAX model. From the decomposition plot, we can detect a seasonality of one day (24 hours) #Stationarity testimport statsmodels.tsa.stattools as stsdftest = sts.adfuller(train.iloc[:,:].demand)print('ADF Statistic: %f' % dftest[0])print('p-value: %f' % dftest[1])print('Critical Values:')for key, value in dftest[4].items(): print('\t%s: %.3f' % (key, value)) Augmented Dickey-Fuller test: Null Hypothesis (H0): It suggests the time series has a unit root, meaning it is non-stationary. It has some time-dependent structure. Alternate Hypothesis (H1): It suggests the time series does not have a unit root, meaning it is stationary. It does not have a time-dependent structure. p-value > 0.05: Accept the null hypothesis (H0), the data has a unit root and is non-stationary. p-value <= 0.05: Reject the null hypothesis (H0), the data does not have a unit root and is stationary. Here we have the p-value <= 0.05 which means that the data is stationarity. Now we confirmed that our process is stationary, we will read each regions demands and split the available data between train and test sets. We have data from January 2015 to February 2016. Train data: From January 2015 to December 2015 Test data: January and February 2016 split_date = pd.Timestamp('2016-01-01')train = cluster_cleaned.loc[:split_date]test = cluster_cleaned.loc[split_date:] Visualizing the test set we can observe a strange behaviour of the data around Jan 24. this points will affect the results of the model so we will take this into consideration. Quick google research we can find that this behaviour is due the Bizzard that happened on the week of Jan 24, 2016, in USA and NYC especially that closed the roads which affected the taxi demand. Source: https://www.nbcnewyork.com/news/local/nyc-new-york-city-blizzard-biggest-ever-january-23-2016/831660/ Now that our data is prepared, let’s get into it, SARIMAX has order and seasonal order hyperparameter that need to be tuned, first will apply hyperparameter tuning on each region demands data to find the best model settings using get_sarima_params function: Next, we apply sarimax model using this function, note that in the get_sarima_params we specified in the seasonal order 24 as seasonality since we detected 24h seasonality in our time series. Without forgetting to ignore the test data between 23 and 26 January 2016, due to the erroneous behaviour of the demand caused by the blizzard in NewYork city. Let’s test the model on the first cluster and evaluate the results with MAE and RMSE metrics. Now we will use Plotly library to visualize the results of the prediction on test set: We can see that the SARIMAX model perform well on detecting the seasonality of the time series, and poorly when it comes to detecting the variations ( trends ) values, this can be explained as anomaly detection in some problems. We can see also the period between 23 and 26 Jan, where the model couldn’t detect the strange behaviour. Find in this drive folder, NewYork taxi demands data cleaned and arranged into 30 clusters, you can copy this folder into your drive and import it to your notebook and apply directly. Happy hacking! github.com I hope that you found this tutorial useful. You started by a motivation for why taxi-hailing and e-halling companies need to predict future demand. This was followed by a taste of the theory behind time series prediction and the SARIMAX model. Then you dived into downloading, exploring and cleaning the demands data. This allowed us better understand the behaviour and construction of a Spatio-temporal prediction problem and to test the seasonality, stationarity of the time series. Finally, we implemented the methods to apply the SARIMAX model on the NewYork data. To improve the results of the SARIMAX model on your data you can try multiple ways, such as: Rearrange the data into smaller time steps ( let’s say 10 minutes) in order for the model to better detect the fluctuations. Tune the SARIMAX model on more values. Clustering the demands into more regions. Introduction to Time Series Forecasting With Python Dr.Jason Brownlee I referred to this repo for some steps of data cleaning.
[ { "code": null, "e": 345, "s": 172, "text": "Taxi demands prediction has become extremely important for taxi-hailing (and e-haling) companies as a way to understand their demand and to optimize their fleet management." }, { "code": null, "e": 629, "s": 345, "text": "In this article, we will present a method for predicting the number of taxi pickups in a certain region of NewYork. We will perform spatiotemporal time series analysis then we will apply the well-known statistical method SARIMAX on the aggregated data that includes the weather data." }, { "code": null, "e": 756, "s": 629, "text": "· We will be using NewYork Taxi demand public data available on: https://www1.nyc.gov/site/tlc/about/tlc-trip-record-data.page" }, { "code": null, "e": 816, "s": 756, "text": "· Here we will use data from January 2015 to February 2016." }, { "code": null, "e": 949, "s": 816, "text": "· To quickly download the large Data from NYC dataset website to your google drive account you can follow my tutorial via this link." }, { "code": null, "e": 1061, "s": 949, "text": "· For weather data, we will use data from the Visual Crossing provider: https://visualcrossing.com/weather-data" }, { "code": null, "e": 1246, "s": 1061, "text": "Time-series forecasting is one of the hot research topics in the field of data science. Various models and approaches have been tested from statistical methods to deep neural networks." }, { "code": null, "e": 1716, "s": 1246, "text": "Machine learning enthusiast tend to jump directly to machine learning models when it comes to times series prediction avoiding statistical methods which, in a lot of cases, has shown better performance across both accuracy measures and for all forecasting horizons especially for univariate time series, let’s first get an idea on how to classify a time series problem. Dr Jason Brownlee in his book introduced a framework to classify a times series problem as follows:" }, { "code": null, "e": 1798, "s": 1716, "text": "Inputs: Historical data provided to the model in order to make a single forecast." }, { "code": null, "e": 1888, "s": 1798, "text": "Outputs: Prediction or forecast for a future time step beyond the data provided as input." }, { "code": null, "e": 2011, "s": 1888, "text": "Endogenous: Input variables that are influenced by other variables in the system and on which the output variable depends." }, { "code": null, "e": 2136, "s": 2011, "text": "Exogenous: Input variables that are not influenced by other variables in the system and on which the output variable depends" }, { "code": null, "e": 2208, "s": 2136, "text": "Forecast a numerical quantity vs Classify as one of two or more labels." }, { "code": null, "e": 2253, "s": 2208, "text": "One or multiple variables measured over time" }, { "code": null, "e": 2326, "s": 2253, "text": "Forecast the next time step vs forecast more than one future time steps." }, { "code": null, "e": 2440, "s": 2326, "text": "fit the model once and used to make predictions vs fit the model on newly available data prior to each prediction" }, { "code": null, "e": 2503, "s": 2440, "text": "Observations made are uniform vs observations are not uniform." }, { "code": null, "e": 2621, "s": 2503, "text": "Now that you got an idea about the type of time series problem we are in front of, let’s introduce the SARIMAX model:" }, { "code": null, "e": 3103, "s": 2621, "text": "SARIMA stands for (Seasonal Autoregressive Integrated Moving Average) a variation of ARIMA model, a model used in univariate time series prediction, which supports the seasonal component of the series. It supports an autoregressive and a moving average component. It has three hyperparameters to specify the autoregression (AR), differencing (I),and moving average (MA) for the seasonal component of the series, as well as an additional parameter for the period of the seasonality." }, { "code": null, "e": 3147, "s": 3103, "text": "X stands for including Exogenous variables." }, { "code": null, "e": 3180, "s": 3147, "text": "· p: Trend autoregression order." }, { "code": null, "e": 3209, "s": 3180, "text": "· d: Trend difference order." }, { "code": null, "e": 3242, "s": 3209, "text": "· q: Trend moving average order." }, { "code": null, "e": 3276, "s": 3242, "text": "P: Seasonal autoregressive order." }, { "code": null, "e": 3306, "s": 3276, "text": "D: Seasonal difference order." }, { "code": null, "e": 3340, "s": 3306, "text": "Q: Seasonal moving average order." }, { "code": null, "e": 3398, "s": 3340, "text": "m: The number of time steps for a single seasonal period." }, { "code": null, "e": 3443, "s": 3398, "text": "Enough theory, let’s now get into the code !" }, { "code": null, "e": 3804, "s": 3443, "text": "Data cleaning/preprocessing is a very important step in any machine learning project, yet it’s a tiring step, if you are more interested in applying the SARIMAX method than cleaning the data you can skip this part since I will provide you structured and cleaned data via a drive folder, But it’s important to understand how the data was cleaned and structured." }, { "code": null, "e": 3896, "s": 3804, "text": "PS: Find the link to the cleaned data folder down in the section (Cleaned Data folder link)" }, { "code": null, "e": 4008, "s": 3896, "text": "data_Jan_2015 = dd.read_csv(\"/content/drive/My Drive/nyc-data/yellow_tripdata_2015-01.csv\")data_Jan_2015.head()" }, { "code": null, "e": 4177, "s": 4008, "text": "We import the data of the first month of 2015 on dask dataframe, the data contains a lot of features, but I will present only the ones we’ll need for cleaning the data:" }, { "code": null, "e": 4227, "s": 4177, "text": "tpep_pickup_datetime: the date and time of pickup" }, { "code": null, "e": 4279, "s": 4227, "text": "tpep_dropoff_datetime: the date and time of dropoff" }, { "code": null, "e": 4321, "s": 4279, "text": "pickup_longitude: longitude of the pickup" }, { "code": null, "e": 4361, "s": 4321, "text": "pickup_latitude: latitude of the pickup" }, { "code": null, "e": 4405, "s": 4361, "text": "dropoff_longitude: longitude of the dropoff" }, { "code": null, "e": 4447, "s": 4405, "text": "dropoff_latitude: latitude of the dropoff" }, { "code": null, "e": 4480, "s": 4447, "text": "trip_distance: the trip distance" }, { "code": null, "e": 4602, "s": 4480, "text": "First, we select only the needed columns, calculate the trip_duration and speed to use it in the data cleaning processes." }, { "code": null, "e": 4731, "s": 4602, "text": "After preparing the data frame, we will process to remove the erroneous values by analyzing the quartiles graphs of each column:" }, { "code": null, "e": 4996, "s": 4731, "text": "After printing the quartiles & percentiles we observe the 99.9th percentile of trip distance is 22.58miles, however, 100th percentile value is 15420004.9miles, which is very high. So, we are removing all the data points where trip distance is greater than 23miles." }, { "code": null, "e": 5085, "s": 4996, "text": "Doing the same process on other quantitative variables (ِCheck the GitHub repo for code)" }, { "code": null, "e": 5208, "s": 5085, "text": "By visualizing some of the pickups and dropoff out of NewYork, some are in the ocean, these will be deleted from the data." }, { "code": null, "e": 5354, "s": 5208, "text": "After cleaning the demands out of NewYork, we proceed with clustering the demands by pickups using Kmeans algorithm. we divide it by 30 clusters." }, { "code": null, "e": 5664, "s": 5354, "text": "#Clustering pickupscoord = new_data_Jan_2015[[\"pickup_latitude\", \"pickup_longitude\"]].valuesregions = MiniBatchKMeans(n_clusters = 30, batch_size = 10000).fit(coord)cluster_column = regions.predict(new_data_Jan_2015[[\"pickup_latitude\", \"pickup_longitude\"]])new_data_Jan_2015[\"pickup_cluster\"] = cluster_column" }, { "code": null, "e": 5703, "s": 5664, "text": "Next, we will group demands by region." }, { "code": null, "e": 6046, "s": 5703, "text": "#Grouping the mounthly data by regionnew_data_Jan_2015.rename(columns={'tpep_pickup_datetime':'time','trip_distance':'demand',},inplace=True)new_data_Jan_2015['time'] = pd.to_datetime(new_data_Jan_2015['time'])grouped_new_data_Jan_2015 = new_data_Jan_2015[[\"pickup_cluster\", \"time\", \"demand\"]].groupby(by = [\"pickup_cluster\", \"time\"]).count()" }, { "code": null, "e": 6075, "s": 6046, "text": "Let’s visualise the regions:" }, { "code": null, "e": 6205, "s": 6075, "text": "Finally, we prepare the demands of each cluster by adding weather components and resampling the demands by a time step of 1 hour." }, { "code": null, "e": 6913, "s": 6205, "text": "#Cluster examplecluster = grouped_new_data_Jan_2015.loc[0]#Resampling Data in region j into one hour stepcluster = cluster.resample('1h').sum()#Feature Engineeringcluster['Date time'] = cluster.indexcluster['Date time'] = pd.to_datetime(cluster['Date time'].dt.strftime('%Y-%m-%d %H'))cluster['hour']=cluster['Date time'].dt.hourcluster['day']=cluster['Date time'].dt.daycluster['dayofweek']=cluster['Date time'].dt.dayofweek#Merging with weather datadf_merge_col = pd.merge(cluster, weather_data, on='Date time')cluster['temperature'] = df_merge_col.Temperature.valuescluster['wind_speed'] = df_merge_col['Wind Speed'].valuescluster = cluster[['hour','day','dayofweek','temperature','wind_speed','demand']]" }, { "code": null, "e": 6955, "s": 6913, "text": "The cluster (region) will look like this:" }, { "code": null, "e": 7069, "s": 6955, "text": "This represents the time serie of demands in one region that we will feed to our model to predict future demands." }, { "code": null, "e": 7115, "s": 7069, "text": "Each region will be saved in a separate file." }, { "code": null, "e": 7301, "s": 7115, "text": "We will do the same steps to prepare the data of the other months ( preprocessing, cleaning, clustering, adding weather features, saving each region’s demands in the correspondent file)" }, { "code": null, "e": 7363, "s": 7301, "text": "I am making available the cleaned data via this drive folder," }, { "code": null, "e": 7489, "s": 7363, "text": "Here you can find all the NewYork data cleaned and clustered by regions, we will use these files to train and test our model." }, { "code": null, "e": 7691, "s": 7489, "text": "Now we will start working on the prediction problem, we remind you that this is a time series forecasting problem, we need to test the stationarity of the time series to be able to apply SARIMAX model." }, { "code": null, "e": 7770, "s": 7691, "text": "From the decomposition plot, we can detect a seasonality of one day (24 hours)" }, { "code": null, "e": 8040, "s": 7770, "text": "#Stationarity testimport statsmodels.tsa.stattools as stsdftest = sts.adfuller(train.iloc[:,:].demand)print('ADF Statistic: %f' % dftest[0])print('p-value: %f' % dftest[1])print('Critical Values:')for key, value in dftest[4].items(): print('\\t%s: %.3f' % (key, value))" }, { "code": null, "e": 8070, "s": 8040, "text": "Augmented Dickey-Fuller test:" }, { "code": null, "e": 8205, "s": 8070, "text": "Null Hypothesis (H0): It suggests the time series has a unit root, meaning it is non-stationary. It has some time-dependent structure." }, { "code": null, "e": 8358, "s": 8205, "text": "Alternate Hypothesis (H1): It suggests the time series does not have a unit root, meaning it is stationary. It does not have a time-dependent structure." }, { "code": null, "e": 8455, "s": 8358, "text": "p-value > 0.05: Accept the null hypothesis (H0), the data has a unit root and is non-stationary." }, { "code": null, "e": 8559, "s": 8455, "text": "p-value <= 0.05: Reject the null hypothesis (H0), the data does not have a unit root and is stationary." }, { "code": null, "e": 8635, "s": 8559, "text": "Here we have the p-value <= 0.05 which means that the data is stationarity." }, { "code": null, "e": 8825, "s": 8635, "text": "Now we confirmed that our process is stationary, we will read each regions demands and split the available data between train and test sets. We have data from January 2015 to February 2016." }, { "code": null, "e": 8872, "s": 8825, "text": "Train data: From January 2015 to December 2015" }, { "code": null, "e": 8909, "s": 8872, "text": "Test data: January and February 2016" }, { "code": null, "e": 9029, "s": 8909, "text": "split_date = pd.Timestamp('2016-01-01')train = cluster_cleaned.loc[:split_date]test = cluster_cleaned.loc[split_date:]" }, { "code": null, "e": 9402, "s": 9029, "text": "Visualizing the test set we can observe a strange behaviour of the data around Jan 24. this points will affect the results of the model so we will take this into consideration. Quick google research we can find that this behaviour is due the Bizzard that happened on the week of Jan 24, 2016, in USA and NYC especially that closed the roads which affected the taxi demand." }, { "code": null, "e": 9512, "s": 9402, "text": "Source: https://www.nbcnewyork.com/news/local/nyc-new-york-city-blizzard-biggest-ever-january-23-2016/831660/" }, { "code": null, "e": 9770, "s": 9512, "text": "Now that our data is prepared, let’s get into it, SARIMAX has order and seasonal order hyperparameter that need to be tuned, first will apply hyperparameter tuning on each region demands data to find the best model settings using get_sarima_params function:" }, { "code": null, "e": 9962, "s": 9770, "text": "Next, we apply sarimax model using this function, note that in the get_sarima_params we specified in the seasonal order 24 as seasonality since we detected 24h seasonality in our time series." }, { "code": null, "e": 10122, "s": 9962, "text": "Without forgetting to ignore the test data between 23 and 26 January 2016, due to the erroneous behaviour of the demand caused by the blizzard in NewYork city." }, { "code": null, "e": 10216, "s": 10122, "text": "Let’s test the model on the first cluster and evaluate the results with MAE and RMSE metrics." }, { "code": null, "e": 10303, "s": 10216, "text": "Now we will use Plotly library to visualize the results of the prediction on test set:" }, { "code": null, "e": 10532, "s": 10303, "text": "We can see that the SARIMAX model perform well on detecting the seasonality of the time series, and poorly when it comes to detecting the variations ( trends ) values, this can be explained as anomaly detection in some problems." }, { "code": null, "e": 10637, "s": 10532, "text": "We can see also the period between 23 and 26 Jan, where the model couldn’t detect the strange behaviour." }, { "code": null, "e": 10836, "s": 10637, "text": "Find in this drive folder, NewYork taxi demands data cleaned and arranged into 30 clusters, you can copy this folder into your drive and import it to your notebook and apply directly. Happy hacking!" }, { "code": null, "e": 10847, "s": 10836, "text": "github.com" }, { "code": null, "e": 11416, "s": 10847, "text": "I hope that you found this tutorial useful. You started by a motivation for why taxi-hailing and e-halling companies need to predict future demand. This was followed by a taste of the theory behind time series prediction and the SARIMAX model. Then you dived into downloading, exploring and cleaning the demands data. This allowed us better understand the behaviour and construction of a Spatio-temporal prediction problem and to test the seasonality, stationarity of the time series. Finally, we implemented the methods to apply the SARIMAX model on the NewYork data." }, { "code": null, "e": 11509, "s": 11416, "text": "To improve the results of the SARIMAX model on your data you can try multiple ways, such as:" }, { "code": null, "e": 11634, "s": 11509, "text": "Rearrange the data into smaller time steps ( let’s say 10 minutes) in order for the model to better detect the fluctuations." }, { "code": null, "e": 11673, "s": 11634, "text": "Tune the SARIMAX model on more values." }, { "code": null, "e": 11715, "s": 11673, "text": "Clustering the demands into more regions." }, { "code": null, "e": 11785, "s": 11715, "text": "Introduction to Time Series Forecasting With Python Dr.Jason Brownlee" } ]
What happens if we re-declare a variable in JavaScript?
On re-declaring a variable in JavaScript, the variable value still remains the same. Let’s see an example. Here, we are declaring the variable age − <html> <body> <script> <!-- var age = 20; var age; if( age > 18 ){ document.write("Qualifies for driving"); } //--> </script> </body> </html>
[ { "code": null, "e": 1147, "s": 1062, "text": "On re-declaring a variable in JavaScript, the variable value still remains the same." }, { "code": null, "e": 1211, "s": 1147, "text": "Let’s see an example. Here, we are declaring the variable age −" }, { "code": null, "e": 1454, "s": 1211, "text": "<html>\n <body>\n <script>\n <!--\n var age = 20;\n var age;\n if( age > 18 ){\n document.write(\"Qualifies for driving\");\n }\n //-->\n </script>\n </body>\n</html>" } ]
Array to Stream in Java - GeeksforGeeks
11 Dec, 2018 Prerequisite : Stream In Java Using Arrays.stream() : Syntax : public static <T> Stream<T> getStream(T[] arr) { return Arrays.stream(arr); } where, T represents generic type. Example 1 : Arrays.stream() to convert string array to stream. // Java code for converting string array// to stream using Arrays.stream()import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Converting String array to stream String[] arr = { "Geeks", "for", "Geeks" }; // Using Arrays.stream to convert an // array into Stream Stream<String> stm = Arrays.stream(arr); // Displaying elements in Stream stm.forEach(str -> System.out.print(str + " ")); }} Geeks for Geeks Example 2 : Arrays.stream() to convert int array to stream. // Java code for converting string array// to stream using Arrays.stream()import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Converting int array to stream int arr[] = { 1, 2, 3, 4, 5 }; IntStream stm = Arrays.stream(arr); stm.forEach(a -> System.out.print(a + " ")); }} 1 2 3 4 5 Example 3 : Arrays.stream() to convert long and double arrays to stream. // Java code for converting string array// to stream using Arrays.stream()import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Converting long array to stream long[] arrL = { 3L, 5L, 6L, 8L, 9L }; LongStream stmL = Arrays.stream(arrL); stmL.forEach(number -> System.out.print(number + " ")); System.out.println(); // Converting double array to stream double[] arrD = { 1, 2, 3, 4, 5 }; DoubleStream stmD = Arrays.stream(arrD); stmD.forEach(d -> System.out.print(d + " ")); }} Output: 3 5 6 8 9 1.0 2.0 3.0 4.0 5.0 Using Stream.of(), IntStream.of(), LongStream.of() & DoubleStream.of() : Syntax : public static <T> Stream<T> getStream(T[] arr) { return Stream.of(arr); } where, T represents generic type. Syntax of other functions is similar Note : For object arrays, Stream.of() internally uses Arrays.stream(). Example 1 : Arrays.stream() to convert string array to stream. // Java code for converting string array// to stream using Stream.of()import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Converting String array to stream String[] arr = { "Geeks", "for", "Geeks" }; // Using Arrays.stream to convert an // array into Stream Stream<String> stm = Stream.of(arr); // Displaying elements in Stream stm.forEach(str -> System.out.print(str + " ")); }} Geeks for Geeks Example 2 : Arrays.stream() to convert int array to stream. // Java code for converting string array// to stream using IntStream.of()import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Converting int array to stream int arr[] = { 1, 2, 3, 4, 5 }; IntStream stm = IntStream.of(arr); stm.forEach(a -> System.out.print(a + " ")); }} 1 2 3 4 5 Example 3 : Arrays.stream() to convert long and double arrays to stream. // Java code for converting string array// to stream using DoubleStream.of()import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Converting long array to stream long[] arrL = { 3L, 5L, 6L, 8L, 9L }; LongStream stmL = LongStream.of(arrL); stmL.forEach(number -> System.out.print(number + " ")); System.out.println(); // Converting double array to stream double[] arrD = { 1, 2, 3, 4, 5 }; DoubleStream stmD = DoubleStream.of(arrD); stmD.forEach(d -> System.out.print(d + " ")); }} Output: 3 5 6 8 9 1.0 2.0 3.0 4.0 5.0 Java - util package Java-Array-Programs Java-Arrays java-stream Java-Stream-programs Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Functional Interfaces in Java Generics in Java Comparator Interface in Java with Examples HashMap get() Method in Java Introduction to Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23948, "s": 23920, "text": "\n11 Dec, 2018" }, { "code": null, "e": 23978, "s": 23948, "text": "Prerequisite : Stream In Java" }, { "code": null, "e": 24002, "s": 23978, "text": "Using Arrays.stream() :" }, { "code": null, "e": 24011, "s": 24002, "text": "Syntax :" }, { "code": null, "e": 24127, "s": 24011, "text": "public static <T> Stream<T> getStream(T[] arr)\n{\n return Arrays.stream(arr);\n}\n\nwhere, T represents generic type.\n" }, { "code": null, "e": 24190, "s": 24127, "text": "Example 1 : Arrays.stream() to convert string array to stream." }, { "code": "// Java code for converting string array// to stream using Arrays.stream()import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Converting String array to stream String[] arr = { \"Geeks\", \"for\", \"Geeks\" }; // Using Arrays.stream to convert an // array into Stream Stream<String> stm = Arrays.stream(arr); // Displaying elements in Stream stm.forEach(str -> System.out.print(str + \" \")); }}", "e": 24694, "s": 24190, "text": null }, { "code": null, "e": 24712, "s": 24694, "text": "Geeks for Geeks \n" }, { "code": null, "e": 24772, "s": 24712, "text": "Example 2 : Arrays.stream() to convert int array to stream." }, { "code": "// Java code for converting string array// to stream using Arrays.stream()import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Converting int array to stream int arr[] = { 1, 2, 3, 4, 5 }; IntStream stm = Arrays.stream(arr); stm.forEach(a -> System.out.print(a + \" \")); }}", "e": 25137, "s": 24772, "text": null }, { "code": null, "e": 25149, "s": 25137, "text": "1 2 3 4 5 \n" }, { "code": null, "e": 25222, "s": 25149, "text": "Example 3 : Arrays.stream() to convert long and double arrays to stream." }, { "code": "// Java code for converting string array// to stream using Arrays.stream()import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Converting long array to stream long[] arrL = { 3L, 5L, 6L, 8L, 9L }; LongStream stmL = Arrays.stream(arrL); stmL.forEach(number -> System.out.print(number + \" \")); System.out.println(); // Converting double array to stream double[] arrD = { 1, 2, 3, 4, 5 }; DoubleStream stmD = Arrays.stream(arrD); stmD.forEach(d -> System.out.print(d + \" \")); }}", "e": 25826, "s": 25222, "text": null }, { "code": null, "e": 25834, "s": 25826, "text": "Output:" }, { "code": null, "e": 25867, "s": 25834, "text": "3 5 6 8 9 \n1.0 2.0 3.0 4.0 5.0 \n" }, { "code": null, "e": 25940, "s": 25867, "text": "Using Stream.of(), IntStream.of(), LongStream.of() & DoubleStream.of() :" }, { "code": null, "e": 25949, "s": 25940, "text": "Syntax :" }, { "code": null, "e": 26099, "s": 25949, "text": "public static <T> Stream<T> getStream(T[] arr)\n{\n return Stream.of(arr);\n}\n\nwhere, T represents generic type.\n\nSyntax of other functions is similar\n" }, { "code": null, "e": 26170, "s": 26099, "text": "Note : For object arrays, Stream.of() internally uses Arrays.stream()." }, { "code": null, "e": 26233, "s": 26170, "text": "Example 1 : Arrays.stream() to convert string array to stream." }, { "code": "// Java code for converting string array// to stream using Stream.of()import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Converting String array to stream String[] arr = { \"Geeks\", \"for\", \"Geeks\" }; // Using Arrays.stream to convert an // array into Stream Stream<String> stm = Stream.of(arr); // Displaying elements in Stream stm.forEach(str -> System.out.print(str + \" \")); }}", "e": 26729, "s": 26233, "text": null }, { "code": null, "e": 26747, "s": 26729, "text": "Geeks for Geeks \n" }, { "code": null, "e": 26807, "s": 26747, "text": "Example 2 : Arrays.stream() to convert int array to stream." }, { "code": "// Java code for converting string array// to stream using IntStream.of()import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Converting int array to stream int arr[] = { 1, 2, 3, 4, 5 }; IntStream stm = IntStream.of(arr); stm.forEach(a -> System.out.print(a + \" \")); }}", "e": 27170, "s": 26807, "text": null }, { "code": null, "e": 27182, "s": 27170, "text": "1 2 3 4 5 \n" }, { "code": null, "e": 27255, "s": 27182, "text": "Example 3 : Arrays.stream() to convert long and double arrays to stream." }, { "code": "// Java code for converting string array// to stream using DoubleStream.of()import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Converting long array to stream long[] arrL = { 3L, 5L, 6L, 8L, 9L }; LongStream stmL = LongStream.of(arrL); stmL.forEach(number -> System.out.print(number + \" \")); System.out.println(); // Converting double array to stream double[] arrD = { 1, 2, 3, 4, 5 }; DoubleStream stmD = DoubleStream.of(arrD); stmD.forEach(d -> System.out.print(d + \" \")); }}", "e": 27864, "s": 27255, "text": null }, { "code": null, "e": 27872, "s": 27864, "text": "Output:" }, { "code": null, "e": 27905, "s": 27872, "text": "3 5 6 8 9 \n1.0 2.0 3.0 4.0 5.0 \n" }, { "code": null, "e": 27925, "s": 27905, "text": "Java - util package" }, { "code": null, "e": 27945, "s": 27925, "text": "Java-Array-Programs" }, { "code": null, "e": 27957, "s": 27945, "text": "Java-Arrays" }, { "code": null, "e": 27969, "s": 27957, "text": "java-stream" }, { "code": null, "e": 27990, "s": 27969, "text": "Java-Stream-programs" }, { "code": null, "e": 27995, "s": 27990, "text": "Java" }, { "code": null, "e": 28000, "s": 27995, "text": "Java" }, { "code": null, "e": 28098, "s": 28000, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28113, "s": 28098, "text": "Stream In Java" }, { "code": null, "e": 28159, "s": 28113, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28180, "s": 28159, "text": "Constructors in Java" }, { "code": null, "e": 28199, "s": 28180, "text": "Exceptions in Java" }, { "code": null, "e": 28229, "s": 28199, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28246, "s": 28229, "text": "Generics in Java" }, { "code": null, "e": 28289, "s": 28246, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 28318, "s": 28289, "text": "HashMap get() Method in Java" }, { "code": null, "e": 28339, "s": 28318, "text": "Introduction to Java" } ]
Find sum of product of number in given series - GeeksforGeeks
26 May, 2021 Given two numbers N and T where, and . The task is to find the value of .Since sum can be large, output it modulo 109+7.Examples: Input : 3 2 Output : 38 2*3 + 3*4 + 4*5 = 38 Input : 4 2 Output : 68 In the Given Sample Case n = 3 and t = 2.sum = 2*3+3*4+4*5. Notice that: So each term is of the form If we multiply and divide by t! it becomes Which is nothing but Therefore, But we know Therefore So final expression comes out to be But since n is so large we can not calculate it directly, we have to Simplify the above expression.On Simplifying we get .Below is the implementation of above approach C++ Java Python3 C# PHP Javascript // C++ program to find sum of product// of number in given series#include <bits/stdc++.h>using namespace std; typedef long long ll;const long long MOD = 1000000007; // function to calculate (a^b)%pll power(ll x, unsigned long long y, ll p){ ll res = 1; // Initialize result // Update x if it is more than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // function to return required answerll sumProd(ll n, ll t){ // modulo inverse of denominator ll dino = power(t + 1, MOD - 2, MOD); // calculating commentator part unsigned long long ans = 1; for (ll i = n + t + 1; i > n; --i) ans = (ans % MOD * i % MOD) % MOD; // calculating t! ll tfact = 1; for (int i = 1; i <= t; ++i) tfact = (tfact * i) % MOD; // accumulating the final answer ans = ans * dino - tfact + MOD; return ans % MOD;}int main(){ ll n = 3, t = 2; // function call to print required sum cout << sumProd(n, t); return 0;} // Java program to find sum of product// of number in given series public class GFG { static long MOD = 1000000007; //function to calculate (a^b)%p static long power(long x, long y, long p) { long res = 1; // Initialize result // Update x if it is more than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1)!= 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } //function to return required answer static long sumProd(long n, long t) { // modulo inverse of denominator long dino = power(t + 1, MOD - 2, MOD); // calculating commentator part long ans = 1; for (long i = n + t + 1; i > n; --i) ans = (ans % MOD * i % MOD) % MOD; // calculating t! long tfact = 1; for (int i = 1; i <= t; ++i) tfact = (tfact * i) % MOD; // accumulating the final answer ans = ans * dino - tfact + MOD; return ans % MOD; } // Driver program public static void main(String[] args) { long n = 3, t = 2; // function call to print required sum System.out.println(sumProd(n, t)); }} # Python 3 program to find sum of product# of number in given series MOD = 1000000007 # function to calculate (a^b)%pdef power(x, y, p) : # Initialize result res = 1 # Update x if it is more than or equal to p x = x % p # If y is odd, multiply x with result while y > 0 : if y & 1 : res = (res * x) % p # y must be even now y = y >> 1 # y = y/2 x = (x * x) % p return res # function to return required answerdef sumProd(n, t) : # modulo inverse of denominator dino = power(t + 1, MOD - 2, MOD) ans = 1 # calculating commentator part for i in range(n + t + 1 , n, -1) : ans = (ans % MOD * i % MOD) % MOD # calculating t! tfact = 1 for i in range(1, t+1) : tfact = (tfact * i) % MOD # accumulating the final answer ans = ans * dino - tfact + MOD return ans % MOD # Driver Codeif __name__ == "__main__" : n, t = 3, 2 # function call to print required sum print(sumProd(n, t)) # This code is contributed by ANKITRAI1 // C# program to find sum of product// of number in given seriesusing System;class GFG{static long MOD = 1000000007; // function to calculate (a^b)%pstatic long power(long x, long y, long p){ long res = 1; // Initialize result // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // function to return required answerstatic long sumProd(long n, long t){ // modulo inverse of denominatorlong dino = power(t + 1, MOD - 2, MOD); // calculating commentator partlong ans = 1;for (long i = n + t + 1; i > n; --i) ans = (ans % MOD * i % MOD) % MOD; // calculating t!long tfact = 1;for (int i = 1; i <= t; ++i) tfact = (tfact * i) % MOD; // accumulating the final answerans = ans * dino - tfact + MOD; return ans % MOD;} // Driver Codepublic static void Main(){ long n = 3, t = 2; // function call to print required sum Console.WriteLine(sumProd(n, t));}} // This code is contributed// by Akanksha Rai(Abby_akku) <?php// PHP program to find sum of product// of number in given series // function to calculate (a^b)%pfunction power($x, $y, $p){ $res = 1; // Initialize result // Update x if it is more // than or equal to p $x = $x % $p; while ($y > 0) { // If y is odd, multiply // x with result if ($y & 1) $res = ($res * $x) % $p; // y must be even now $y = $y >> 1; // y = y/2 $x = ($x * $x) % $p; } return $res;} // function to return required answerfunction sumProd($n, $t){ $MOD = 1000000007; // modulo inverse of denominator $dino = power($t + 1, $MOD - 2, $MOD); // calculating commentator part $ans = 1; for ($i = $n + $t + 1; $i > $n; --$i) $ans = ($ans % $MOD * $i % $MOD) % $MOD; // calculating t! $tfact = 1; for ($i = 1; $i <= $t; ++$i) $tfact = ($tfact * $i) % $MOD; // accumulating the final answer $ans = $ans * $dino - $tfact + $MOD; return $ans % $MOD;} // Driver code$n = 3;$t = 2; // function call to print// required sumecho sumProd($n, $t); // This code is contributed// by Shivi_Aggarwal?> <script> // Javascript program to find sum of product// of number in given seriesvar MOD = 100000007; // function to calculate (a^b)%pfunction power(x, y, p){ var res = 1; // Initialize result // Update x if it is more than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // function to return required answerfunction sumProd(n, t){ // modulo inverse of denominator var dino = power(t + 1, MOD - 2, MOD); // calculating commentator part var ans = 1; for (var i = n + t + 1; i > n; --i) ans = (ans % MOD * i % MOD) % MOD; // calculating t! var tfact = 1; for (var i = 1; i <= t; ++i) tfact = (tfact * i) % MOD; // accumulating the final answer ans = ans * dino - tfact + MOD; return ans % MOD;} var n = 3, t = 2;// function call to print required sumdocument.write( sumProd(n, t)); // This code is contributed by noob2000.</script> Output: 38 Time Complexity: O(T) ankthon ukasp Shivi_Aggarwal Akanksha_Rai noob2000 factorial series series-sum Combinatorial Mathematical Mathematical series Combinatorial factorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Combinations with repetitions Ways to sum to N using Natural Numbers up to K with repetitions allowed Generate all possible combinations of at most X characters from a given array Largest substring with same Characters Number of handshakes such that a person shakes hands only once Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7 Merge two sorted arrays
[ { "code": null, "e": 25452, "s": 25424, "text": "\n26 May, 2021" }, { "code": null, "e": 25584, "s": 25452, "text": "Given two numbers N and T where, and . The task is to find the value of .Since sum can be large, output it modulo 109+7.Examples: " }, { "code": null, "e": 25654, "s": 25584, "text": "Input : 3 2\nOutput : 38\n2*3 + 3*4 + 4*5 = 38\n\nInput : 4 2\nOutput : 68" }, { "code": null, "e": 25732, "s": 25658, "text": "In the Given Sample Case n = 3 and t = 2.sum = 2*3+3*4+4*5. Notice that: " }, { "code": null, "e": 26071, "s": 25732, "text": "So each term is of the form If we multiply and divide by t! it becomes Which is nothing but Therefore, But we know Therefore So final expression comes out to be But since n is so large we can not calculate it directly, we have to Simplify the above expression.On Simplifying we get .Below is the implementation of above approach " }, { "code": null, "e": 26075, "s": 26071, "text": "C++" }, { "code": null, "e": 26080, "s": 26075, "text": "Java" }, { "code": null, "e": 26088, "s": 26080, "text": "Python3" }, { "code": null, "e": 26091, "s": 26088, "text": "C#" }, { "code": null, "e": 26095, "s": 26091, "text": "PHP" }, { "code": null, "e": 26106, "s": 26095, "text": "Javascript" }, { "code": "// C++ program to find sum of product// of number in given series#include <bits/stdc++.h>using namespace std; typedef long long ll;const long long MOD = 1000000007; // function to calculate (a^b)%pll power(ll x, unsigned long long y, ll p){ ll res = 1; // Initialize result // Update x if it is more than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // function to return required answerll sumProd(ll n, ll t){ // modulo inverse of denominator ll dino = power(t + 1, MOD - 2, MOD); // calculating commentator part unsigned long long ans = 1; for (ll i = n + t + 1; i > n; --i) ans = (ans % MOD * i % MOD) % MOD; // calculating t! ll tfact = 1; for (int i = 1; i <= t; ++i) tfact = (tfact * i) % MOD; // accumulating the final answer ans = ans * dino - tfact + MOD; return ans % MOD;}int main(){ ll n = 3, t = 2; // function call to print required sum cout << sumProd(n, t); return 0;}", "e": 27269, "s": 26106, "text": null }, { "code": "// Java program to find sum of product// of number in given series public class GFG { static long MOD = 1000000007; //function to calculate (a^b)%p static long power(long x, long y, long p) { long res = 1; // Initialize result // Update x if it is more than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1)!= 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } //function to return required answer static long sumProd(long n, long t) { // modulo inverse of denominator long dino = power(t + 1, MOD - 2, MOD); // calculating commentator part long ans = 1; for (long i = n + t + 1; i > n; --i) ans = (ans % MOD * i % MOD) % MOD; // calculating t! long tfact = 1; for (int i = 1; i <= t; ++i) tfact = (tfact * i) % MOD; // accumulating the final answer ans = ans * dino - tfact + MOD; return ans % MOD; } // Driver program public static void main(String[] args) { long n = 3, t = 2; // function call to print required sum System.out.println(sumProd(n, t)); }}", "e": 28576, "s": 27269, "text": null }, { "code": "# Python 3 program to find sum of product# of number in given series MOD = 1000000007 # function to calculate (a^b)%pdef power(x, y, p) : # Initialize result res = 1 # Update x if it is more than or equal to p x = x % p # If y is odd, multiply x with result while y > 0 : if y & 1 : res = (res * x) % p # y must be even now y = y >> 1 # y = y/2 x = (x * x) % p return res # function to return required answerdef sumProd(n, t) : # modulo inverse of denominator dino = power(t + 1, MOD - 2, MOD) ans = 1 # calculating commentator part for i in range(n + t + 1 , n, -1) : ans = (ans % MOD * i % MOD) % MOD # calculating t! tfact = 1 for i in range(1, t+1) : tfact = (tfact * i) % MOD # accumulating the final answer ans = ans * dino - tfact + MOD return ans % MOD # Driver Codeif __name__ == \"__main__\" : n, t = 3, 2 # function call to print required sum print(sumProd(n, t)) # This code is contributed by ANKITRAI1", "e": 29637, "s": 28576, "text": null }, { "code": "// C# program to find sum of product// of number in given seriesusing System;class GFG{static long MOD = 1000000007; // function to calculate (a^b)%pstatic long power(long x, long y, long p){ long res = 1; // Initialize result // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // function to return required answerstatic long sumProd(long n, long t){ // modulo inverse of denominatorlong dino = power(t + 1, MOD - 2, MOD); // calculating commentator partlong ans = 1;for (long i = n + t + 1; i > n; --i) ans = (ans % MOD * i % MOD) % MOD; // calculating t!long tfact = 1;for (int i = 1; i <= t; ++i) tfact = (tfact * i) % MOD; // accumulating the final answerans = ans * dino - tfact + MOD; return ans % MOD;} // Driver Codepublic static void Main(){ long n = 3, t = 2; // function call to print required sum Console.WriteLine(sumProd(n, t));}} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 30857, "s": 29637, "text": null }, { "code": "<?php// PHP program to find sum of product// of number in given series // function to calculate (a^b)%pfunction power($x, $y, $p){ $res = 1; // Initialize result // Update x if it is more // than or equal to p $x = $x % $p; while ($y > 0) { // If y is odd, multiply // x with result if ($y & 1) $res = ($res * $x) % $p; // y must be even now $y = $y >> 1; // y = y/2 $x = ($x * $x) % $p; } return $res;} // function to return required answerfunction sumProd($n, $t){ $MOD = 1000000007; // modulo inverse of denominator $dino = power($t + 1, $MOD - 2, $MOD); // calculating commentator part $ans = 1; for ($i = $n + $t + 1; $i > $n; --$i) $ans = ($ans % $MOD * $i % $MOD) % $MOD; // calculating t! $tfact = 1; for ($i = 1; $i <= $t; ++$i) $tfact = ($tfact * $i) % $MOD; // accumulating the final answer $ans = $ans * $dino - $tfact + $MOD; return $ans % $MOD;} // Driver code$n = 3;$t = 2; // function call to print// required sumecho sumProd($n, $t); // This code is contributed// by Shivi_Aggarwal?>", "e": 32021, "s": 30857, "text": null }, { "code": "<script> // Javascript program to find sum of product// of number in given seriesvar MOD = 100000007; // function to calculate (a^b)%pfunction power(x, y, p){ var res = 1; // Initialize result // Update x if it is more than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // function to return required answerfunction sumProd(n, t){ // modulo inverse of denominator var dino = power(t + 1, MOD - 2, MOD); // calculating commentator part var ans = 1; for (var i = n + t + 1; i > n; --i) ans = (ans % MOD * i % MOD) % MOD; // calculating t! var tfact = 1; for (var i = 1; i <= t; ++i) tfact = (tfact * i) % MOD; // accumulating the final answer ans = ans * dino - tfact + MOD; return ans % MOD;} var n = 3, t = 2;// function call to print required sumdocument.write( sumProd(n, t)); // This code is contributed by noob2000.</script>", "e": 33115, "s": 32021, "text": null }, { "code": null, "e": 33124, "s": 33115, "text": "Output: " }, { "code": null, "e": 33127, "s": 33124, "text": "38" }, { "code": null, "e": 33150, "s": 33127, "text": "Time Complexity: O(T) " }, { "code": null, "e": 33158, "s": 33150, "text": "ankthon" }, { "code": null, "e": 33164, "s": 33158, "text": "ukasp" }, { "code": null, "e": 33179, "s": 33164, "text": "Shivi_Aggarwal" }, { "code": null, "e": 33192, "s": 33179, "text": "Akanksha_Rai" }, { "code": null, "e": 33201, "s": 33192, "text": "noob2000" }, { "code": null, "e": 33211, "s": 33201, "text": "factorial" }, { "code": null, "e": 33218, "s": 33211, "text": "series" }, { "code": null, "e": 33229, "s": 33218, "text": "series-sum" }, { "code": null, "e": 33243, "s": 33229, "text": "Combinatorial" }, { "code": null, "e": 33256, "s": 33243, "text": "Mathematical" }, { "code": null, "e": 33269, "s": 33256, "text": "Mathematical" }, { "code": null, "e": 33276, "s": 33269, "text": "series" }, { "code": null, "e": 33290, "s": 33276, "text": "Combinatorial" }, { "code": null, "e": 33300, "s": 33290, "text": "factorial" }, { "code": null, "e": 33398, "s": 33300, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33428, "s": 33398, "text": "Combinations with repetitions" }, { "code": null, "e": 33500, "s": 33428, "text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed" }, { "code": null, "e": 33578, "s": 33500, "text": "Generate all possible combinations of at most X characters from a given array" }, { "code": null, "e": 33617, "s": 33578, "text": "Largest substring with same Characters" }, { "code": null, "e": 33680, "s": 33617, "text": "Number of handshakes such that a person shakes hands only once" }, { "code": null, "e": 33710, "s": 33680, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 33725, "s": 33710, "text": "C++ Data Types" }, { "code": null, "e": 33768, "s": 33725, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 33787, "s": 33768, "text": "Coin Change | DP-7" } ]
Building a Chatbot with Rasa. Getting Started | by Aniruddha Karajgi | Towards Data Science
Chatbots are programs that simulate human conversation. These can range from simple rule-based chatbots, where the user is limited to clicking on buttons or suggested replies that the bot provides, all the way to fully-fledged bots that can handle context, chitchat, and other complex things, which are otherwise very common in human conversation. Quantitatively, there are 5 levels of conversational AI, starting from simple rule-based systems to really adaptive chatbots, who can handle complex scenarios, like when even the user isn’t sure what they want and can reply to users based on the level of detail they want. Table of Contents- Rasa- Intents, Entities, Slots and Responses- Setting up Rasa- Creating training data- Building our bot -- training and testing Rasa is an open-source framework to build text and voice-based chatbots. It's working at Level 3 of conversational AI, where the bot can understand the context. A level 3 conversational agent can handle things like the user changing their mind, handling context and even unexpected queries. Rasa is not the only tool available to you if you’re looking to build a chatbot, but it's one of the best. There are several others, like DialogFlow, though we won’t discuss them in this post. These are the main components of any chatbot conversation. We’ll follow a sample conversation to better understand these terms. Let’s say we’re building a bot to collect user contact info. What the user is implying is called an intent. For example, if a user says one of the following to start the chat: Good Morning! Hi! Hey! Hello. the user is essentially saying a greeting. So we can group these into a single intent called greet . Now, whenever a bot gets a user message that’s similar to other phrases in greet , the bot will classify it as belonging to the greet intent. user: Hi. (bot classifies this message as "greet") Entities are pieces of data that can be extracted from a user message. Continuing our example, after the user greets the bot, the bot asks for their contact information. Something like this: user: Hi. (bot classifies this message as "greet")bot: Hello! Could you please provide your contact information? The user would then enter their details, like their name and their email id. user: Sure. It's John Doe. My email is [email protected]. The message above has two pieces of information — the name and the email. These can be extracted as entities. Your bot will extract them depending on the quality of your training data. Let’s say you have defined two entities for name and email. This is what the bot will extract. name: John Doeemail: [email protected] An important question here is: how does the bot know what to extract? A user could potentially enter any combination of information. All these are valid user inputs: My name is John Doe. email: [email protected] name: John Doe email: [email protected] Yeah sure. I’m John Doe. My email is [email protected]. John Doe, [email protected] Humans can easily extract the names and email ids. But how would a chatbot be able to do that? The answer to this likes in how good our training data is, and we’ll talk about this in a bit. Slots are the bot’s memory. Any information that needs to persist throughout the conversation, like a user’s name or their destination if you were building a flight booking bot, should be stored as slots. Since we already have two entities (name and email), we can create slots with the same names, so when names or email-ids are extracted, they are automatically stored in their respective slots. This is because of two properties that are True by default. auto_fill store_entities_as_slots How we’ll set these slots up, we’ll discuss in a little white. Responses are what the bot says to the user. Naturally, for a bot to give an appropriate response, it has to figure out what the user is trying to say. In our example, when the user greeted the bot, it understand the message as such and responded appropriately by saying hello, and asking for their contact details. Continuing with our sample conversation, after the bot provides their information, let’s say we program the bot to say “thanks” after the user provides their details. user: Hi. (bot classifies this message as "greet")bot: Hello! Could you please provide your contact information?user: Sure. It's John. My email is [email protected]: Thanks John for the info! Install Rasa Opensource using pip install rasa==2.6.2 Install Rasa Opensource using pip install rasa==2.6.2 You can install the latest version, but this post is based on v2.6.2, so any v2.x should work perfectly with what’s covered here. 2. Run rasa init to set up the demo project. Returning to our question of how to create bots that can extract useful information in multiple forms. It's easy for us since we get the semantics of natural languages, but a chatbot can’t do that. A bot doesn’t know what “email” is. Nor does it know that John is probably a name and that emails contain the “@” symbol. Our goal is to provide varied data so the bot can understand some associations between words, like what follows the word “email” is probably going to be an email id, or that words of the form <some_text>@<some_text>.com would be an email. It's, of course, impossible to cover every scenario but we can teach a chatbot the most common ones, making sure we add generic words and phrases that may represent a good portion of messages the bot is likely to see. As you can probably guess, this is more of an iterative process, where we evaluate our bot’s performance in the real world and use that to improve its performance. We’ll go file by file, to make it easier to follow. For the purpose of this post, there are three files that we would be discussing: nlu.yml domain.yml stories.yml Let’s handle the following cases for the supply_contact_info intent. My name is John Doe. email: [email protected] name: John Doe email: [email protected] Yeah sure. I’m John Doe. My email is [email protected]. John Doe, [email protected] Sure. It's John Doe. My email is [email protected]. This training data is called NLU data, and it houses the phrases and dialogues (intents) we expect from a user. Note that this doesn’t include the bot’s responses or how our conversation flows. That’ll exist in a separate part of our project. YAML files are used for this purpose. Next, we’ll give this intent a name. Let’s call it supply_contact_info . Replace the contents of nlu.ymlwith this. Varying the names and email-ids themselves is a good idea so the bot can generalize better. version: "2.0"nlu:- intent: supply_contact_info examples: | - My name is John. email's [email protected] - name: David email: [email protected] - Yeah sure. I’m Barbara. My email is [email protected]. - Susan, [email protected] - Sure. It's Fred. My email is [email protected]. The version key refers to the format of training data that rasa supports. All 2.x versions of Rasa support 2.0 . The NLU data above would give the bot an idea of what kind of things a user could say. But we still haven’t tagged any entities , which as a quick reminder, are key pieces of information that the bot should collect. First, let’s define some entities. Let’s creatively call the entity that would represent customer names as name . Similarly, for email, we’ll use an entity called email . The syntax for tagging an entity is [entity_value](entity_name) . So for the line: My name is John. email's [email protected] we write it as: My name is [John](name). email's [[email protected]](email) This way, we end up with our final NLU data for the supply_contact_info intent. version: "2.0"nlu:- intent: supply_contact_info examples: | - My name is [John](name). email's [[email protected]](email) - name: [David](name) email: [[email protected]](email) - Yeah sure. I'm [Barbara](name). My email is [[email protected]](email) - [Susan](name), [[email protected]](email) - Sure. It's [Fred](name). My email is [[email protected]](email). We also have another intent called the greet intent, which is when the user starts the conversation and says things like “hi” or “hello”. Finally, nlu.yml should look like this. nlu:- intent: greet examples: | - hi - hello- intent: supply_contact_info examples: | - My name is [John](name). email's [[email protected]](email) - name: [David](name) email: [[email protected]](email) - Yeah sure. I'm [Barbara](name). My email is [[email protected]](email) - [Susan](name), [[email protected]](email) - Sure. It's [Fred](name). My email is [[email protected]](email). Now that we have intents and entities, we can add our slots. Head to the file domain.yml . Replace the contents of slots key with this. slots: name: type: text email: type: text Since both name and email are strings, we’ll set the type as text . Just as we have intents to abstract out what the user is trying to say, we have responses to represent what the bot would say. Simple responses are text-based, though Rasa lets you add more complex features like buttons, alternate responses, responses specific to channels, and even custom actions, which we’ll get to later. In our example, after the user greets the bot (intent: greet ), the bot asks the user for their contact info. This can be represented as a bot response or utterance. By convention, we add an “utter” prefix to each bot utterance — something like this: utter_ask_for_contact_info Replace the contents of the responses key in domain.yml with our response. responses:utter_ask_for_contact_info:- text: Hello! Could you please provide your contact information? Similarly, we can add a response after the user has provided their information. Let’s call that: utter_acknowledge_provided_info (in bold, below). responses:utter_ask_for_contact_info:- text: Hello! Could you please provide your contact information?utter_acknowledge_provided_info:- text: Thanks for provided your info! We could make the user experience slightly better here by mentioning the user’s name along with the acknowledgement — something like “Thanks John for the info!” To do this, we’ll modify the utter_acknowledge_provided_info above by adding a placeholder for the name slot like this: utter_acknowledge_provided_info:- text: Thanks {name} for provided your info! Stories give our bot an idea of how the conversation should flow. Returning to our example, where the bot asks the user for their contact details, the conversation went something like this: user: Hi. (bot classifies this message as "greet")bot: Hello! Could you please provide your contact information?user: Sure. It's John. My email is [email protected]: Thanks John for the info! This can be broken down into intents and responses like so: intent: greetaction: utter_ask_for_contact_infointent: supply_contact_infoaction: utter_acknowledge_provided_info Let’s turn this into a syntax rasa can understand. Replace the contents of the file stories.yml with what’ll discuss here. Let’s call the story “user supplies customer info”. Story names do not affect how the bot works. version: "2.0"stories:- story: user supplies customer info steps: - intent: greet - action: utter_ask_for_contact_info - intent: supply_contact_info - action: utter_acknowledge_provided_info But there’s one thing left. We also have to indicate what entities a user intent will likely provide, so it's easier for the bot to figure out how to respond. Under an intent, just list the entities that are likely to appear in that intent. version: "2.0"stories:- story: user supplies customer info steps: - intent: greet - action: utter_ask_for_contact_info - intent: supply_contact_info entities: - name - email - action: utter_acknowledge_provided_info Now that we have our data and stories ready, we’ll have to follow some steps to get our bot running. We made a few changes to the files in our demo bot. Let’s recap. nlu.yml — houses the NLU training data for our model In this file, we keep the tagged data for our two intents: supply_contact_info greet stories.yml— gives the bot an idea of how the conversation should flow Our single story is located here. domain.yml — the complete info of all intents, responses and entities This file is a little more complex than the other two. If you look at the domain.yml file provided in the demo bot (post running rasa init ), you’ll notice keys like intents , actions , responses , entities ,etc. We’ve already added slotsand responses to our domain.yml . All we need to do now is mention our intents and entities. Finally, the file will look like this: version: '2.0'intents:- greet- supply_contact_infoentities:- name- emailslots: name: type: text email: type: textresponses: utter_ask_for_contact_info: - text: Hello! Could you please provide your contact information? utter_acknowledge_provided_info: - text: Thanks {name}, for the info! Validating the data Before training the bot, a good practice is to check for any inconsistencies in the stories and rules, though in a project this simple, it's unlikely to occur. $ rasa data validate The truncated output looks like this. No conflicts were found, so we are good to train our model. The configuration for policies and pipeline was chosen automatically. It was written into the config file at 'config.yml'.2021-09-12 18:36:07 INFO rasa.validator - Validating intents...2021-09-12 18:36:07 INFO rasa.validator - Validating uniqueness of intents and stories... ...2021-09-12 18:36:08 INFO rasa.validator - No story structure conflicts found. Note: You may get the following warning: UserWarning: model_confidence is set to `softmax`. It is recommended to try using `model_confidence=linear_norm` to make it easier to tune fallback thresholds. This is just a recommendation, and can be ignored. Training To train the bot, we simply use the rasa train command. We’ll provide a name to the model for better organization, but it's not necessary. $ rasa train --fixed-model-name contact_bot The output for this is a lot bigger, so I won’t be displaying it here. Note: You may get the following warning: UserWarning: Found a rule-based policy in your pipeline but no rule-based training data. Please add rule-based stories to your training data or remove the rule-based policy (`RulePolicy`) from your your pipeline. We won’t be discussing rules in this post, but they are essentially what they sound like. They require something called a RulePolicy, which is by default, added to your bot pipeline. Can be ignored for now. This will be discussed in a future post. Chatting with our new bot is simple. Open a new terminal window and start a rasa shell. $ rasa shell This will let you chat with your bot in your terminal. But if you want to cleaner UI and a little more info like what intents were identified and what entities were extracted, you can use Rasa X. Just a quick point about Rasa X: It lets you test your bot, fix incorrect responses from your bot, and more importantly, you can share your bot with other people to get a better idea of how it’ll perform in the real world. To use it, install it in local mode. $ pip3 install rasa-x --extra-index-url https://pypi.rasa.com/simple Then, run it. $ rasa x Head to “Talk to Your bot” in the menu on the left, and start conversing with your bot. Below, you can see how our bot performs. In the conversation above, apart from the dialogues, you’ll notice some greyed out information. Below each user message, you can see what intent the user message fell into and with what confidence, along with what entities were extracted. Above each bot message, you can see what action the bot decided to take with what confidence, along with any slots that were set. action_listen is an inbuilt action that means that the chatbot expects user input. All code used in this article is available here: github.com Rasa 5 levels of conversational AI Rasa is a great tool for conversational AI. Its flexibility and depth of customization make it a good choice of tool. In this post, the bot we built was a very simple one. There’s a lot more to it than what I could fit in a single post, like actions, forms, rules, regex, synonyms, interactive learning, config files, pipelines, and so much more. But what has been covered in this post should be enough to get you started. We’ll cover the rest in future posts. I’ll add links to all future posts here. Hope it helped! Part II: Are Slots and Entities the same? Part III: Handling Chatbot Failure Part IV: How do Chatbots understand? 20.3.2022 Add links to the rest of the series
[ { "code": null, "e": 520, "s": 172, "text": "Chatbots are programs that simulate human conversation. These can range from simple rule-based chatbots, where the user is limited to clicking on buttons or suggested replies that the bot provides, all the way to fully-fledged bots that can handle context, chitchat, and other complex things, which are otherwise very common in human conversation." }, { "code": null, "e": 793, "s": 520, "text": "Quantitatively, there are 5 levels of conversational AI, starting from simple rule-based systems to really adaptive chatbots, who can handle complex scenarios, like when even the user isn’t sure what they want and can reply to users based on the level of detail they want." }, { "code": null, "e": 940, "s": 793, "text": "Table of Contents- Rasa- Intents, Entities, Slots and Responses- Setting up Rasa- Creating training data- Building our bot -- training and testing" }, { "code": null, "e": 1231, "s": 940, "text": "Rasa is an open-source framework to build text and voice-based chatbots. It's working at Level 3 of conversational AI, where the bot can understand the context. A level 3 conversational agent can handle things like the user changing their mind, handling context and even unexpected queries." }, { "code": null, "e": 1424, "s": 1231, "text": "Rasa is not the only tool available to you if you’re looking to build a chatbot, but it's one of the best. There are several others, like DialogFlow, though we won’t discuss them in this post." }, { "code": null, "e": 1613, "s": 1424, "text": "These are the main components of any chatbot conversation. We’ll follow a sample conversation to better understand these terms. Let’s say we’re building a bot to collect user contact info." }, { "code": null, "e": 1728, "s": 1613, "text": "What the user is implying is called an intent. For example, if a user says one of the following to start the chat:" }, { "code": null, "e": 1742, "s": 1728, "text": "Good Morning!" }, { "code": null, "e": 1746, "s": 1742, "text": "Hi!" }, { "code": null, "e": 1751, "s": 1746, "text": "Hey!" }, { "code": null, "e": 1758, "s": 1751, "text": "Hello." }, { "code": null, "e": 2001, "s": 1758, "text": "the user is essentially saying a greeting. So we can group these into a single intent called greet . Now, whenever a bot gets a user message that’s similar to other phrases in greet , the bot will classify it as belonging to the greet intent." }, { "code": null, "e": 2052, "s": 2001, "text": "user: Hi. (bot classifies this message as \"greet\")" }, { "code": null, "e": 2123, "s": 2052, "text": "Entities are pieces of data that can be extracted from a user message." }, { "code": null, "e": 2243, "s": 2123, "text": "Continuing our example, after the user greets the bot, the bot asks for their contact information. Something like this:" }, { "code": null, "e": 2359, "s": 2243, "text": "user: Hi. (bot classifies this message as \"greet\")bot: Hello! Could you please provide your contact information?" }, { "code": null, "e": 2436, "s": 2359, "text": "The user would then enter their details, like their name and their email id." }, { "code": null, "e": 2494, "s": 2436, "text": "user: Sure. It's John Doe. My email is [email protected]." }, { "code": null, "e": 2679, "s": 2494, "text": "The message above has two pieces of information — the name and the email. These can be extracted as entities. Your bot will extract them depending on the quality of your training data." }, { "code": null, "e": 2774, "s": 2679, "text": "Let’s say you have defined two entities for name and email. This is what the bot will extract." }, { "code": null, "e": 2813, "s": 2774, "text": "name: John Doeemail: [email protected]" }, { "code": null, "e": 2979, "s": 2813, "text": "An important question here is: how does the bot know what to extract? A user could potentially enter any combination of information. All these are valid user inputs:" }, { "code": null, "e": 3025, "s": 2979, "text": "My name is John Doe. email: [email protected]" }, { "code": null, "e": 3065, "s": 3025, "text": "name: John Doe email: [email protected]" }, { "code": null, "e": 3121, "s": 3065, "text": "Yeah sure. I’m John Doe. My email is [email protected]." }, { "code": null, "e": 3149, "s": 3121, "text": "John Doe, [email protected]" }, { "code": null, "e": 3244, "s": 3149, "text": "Humans can easily extract the names and email ids. But how would a chatbot be able to do that?" }, { "code": null, "e": 3339, "s": 3244, "text": "The answer to this likes in how good our training data is, and we’ll talk about this in a bit." }, { "code": null, "e": 3544, "s": 3339, "text": "Slots are the bot’s memory. Any information that needs to persist throughout the conversation, like a user’s name or their destination if you were building a flight booking bot, should be stored as slots." }, { "code": null, "e": 3797, "s": 3544, "text": "Since we already have two entities (name and email), we can create slots with the same names, so when names or email-ids are extracted, they are automatically stored in their respective slots. This is because of two properties that are True by default." }, { "code": null, "e": 3807, "s": 3797, "text": "auto_fill" }, { "code": null, "e": 3831, "s": 3807, "text": "store_entities_as_slots" }, { "code": null, "e": 3894, "s": 3831, "text": "How we’ll set these slots up, we’ll discuss in a little white." }, { "code": null, "e": 4046, "s": 3894, "text": "Responses are what the bot says to the user. Naturally, for a bot to give an appropriate response, it has to figure out what the user is trying to say." }, { "code": null, "e": 4210, "s": 4046, "text": "In our example, when the user greeted the bot, it understand the message as such and responded appropriately by saying hello, and asking for their contact details." }, { "code": null, "e": 4377, "s": 4210, "text": "Continuing with our sample conversation, after the bot provides their information, let’s say we program the bot to say “thanks” after the user provides their details." }, { "code": null, "e": 4573, "s": 4377, "text": "user: Hi. (bot classifies this message as \"greet\")bot: Hello! Could you please provide your contact information?user: Sure. It's John. My email is [email protected]: Thanks John for the info!" }, { "code": null, "e": 4627, "s": 4573, "text": "Install Rasa Opensource using pip install rasa==2.6.2" }, { "code": null, "e": 4681, "s": 4627, "text": "Install Rasa Opensource using pip install rasa==2.6.2" }, { "code": null, "e": 4811, "s": 4681, "text": "You can install the latest version, but this post is based on v2.6.2, so any v2.x should work perfectly with what’s covered here." }, { "code": null, "e": 4856, "s": 4811, "text": "2. Run rasa init to set up the demo project." }, { "code": null, "e": 4959, "s": 4856, "text": "Returning to our question of how to create bots that can extract useful information in multiple forms." }, { "code": null, "e": 5176, "s": 4959, "text": "It's easy for us since we get the semantics of natural languages, but a chatbot can’t do that. A bot doesn’t know what “email” is. Nor does it know that John is probably a name and that emails contain the “@” symbol." }, { "code": null, "e": 5415, "s": 5176, "text": "Our goal is to provide varied data so the bot can understand some associations between words, like what follows the word “email” is probably going to be an email id, or that words of the form <some_text>@<some_text>.com would be an email." }, { "code": null, "e": 5633, "s": 5415, "text": "It's, of course, impossible to cover every scenario but we can teach a chatbot the most common ones, making sure we add generic words and phrases that may represent a good portion of messages the bot is likely to see." }, { "code": null, "e": 5797, "s": 5633, "text": "As you can probably guess, this is more of an iterative process, where we evaluate our bot’s performance in the real world and use that to improve its performance." }, { "code": null, "e": 5930, "s": 5797, "text": "We’ll go file by file, to make it easier to follow. For the purpose of this post, there are three files that we would be discussing:" }, { "code": null, "e": 5938, "s": 5930, "text": "nlu.yml" }, { "code": null, "e": 5949, "s": 5938, "text": "domain.yml" }, { "code": null, "e": 5961, "s": 5949, "text": "stories.yml" }, { "code": null, "e": 6030, "s": 5961, "text": "Let’s handle the following cases for the supply_contact_info intent." }, { "code": null, "e": 6076, "s": 6030, "text": "My name is John Doe. email: [email protected]" }, { "code": null, "e": 6116, "s": 6076, "text": "name: John Doe email: [email protected]" }, { "code": null, "e": 6172, "s": 6116, "text": "Yeah sure. I’m John Doe. My email is [email protected]." }, { "code": null, "e": 6200, "s": 6172, "text": "John Doe, [email protected]" }, { "code": null, "e": 6252, "s": 6200, "text": "Sure. It's John Doe. My email is [email protected]." }, { "code": null, "e": 6495, "s": 6252, "text": "This training data is called NLU data, and it houses the phrases and dialogues (intents) we expect from a user. Note that this doesn’t include the bot’s responses or how our conversation flows. That’ll exist in a separate part of our project." }, { "code": null, "e": 6533, "s": 6495, "text": "YAML files are used for this purpose." }, { "code": null, "e": 6606, "s": 6533, "text": "Next, we’ll give this intent a name. Let’s call it supply_contact_info ." }, { "code": null, "e": 6740, "s": 6606, "text": "Replace the contents of nlu.ymlwith this. Varying the names and email-ids themselves is a good idea so the bot can generalize better." }, { "code": null, "e": 7024, "s": 6740, "text": "version: \"2.0\"nlu:- intent: supply_contact_info examples: | - My name is John. email's [email protected] - name: David email: [email protected] - Yeah sure. I’m Barbara. My email is [email protected]. - Susan, [email protected] - Sure. It's Fred. My email is [email protected]." }, { "code": null, "e": 7137, "s": 7024, "text": "The version key refers to the format of training data that rasa supports. All 2.x versions of Rasa support 2.0 ." }, { "code": null, "e": 7353, "s": 7137, "text": "The NLU data above would give the bot an idea of what kind of things a user could say. But we still haven’t tagged any entities , which as a quick reminder, are key pieces of information that the bot should collect." }, { "code": null, "e": 7524, "s": 7353, "text": "First, let’s define some entities. Let’s creatively call the entity that would represent customer names as name . Similarly, for email, we’ll use an entity called email ." }, { "code": null, "e": 7607, "s": 7524, "text": "The syntax for tagging an entity is [entity_value](entity_name) . So for the line:" }, { "code": null, "e": 7647, "s": 7607, "text": "My name is John. email's [email protected]" }, { "code": null, "e": 7663, "s": 7647, "text": "we write it as:" }, { "code": null, "e": 7720, "s": 7663, "text": "My name is [John](name). email's [[email protected]](email)" }, { "code": null, "e": 7800, "s": 7720, "text": "This way, we end up with our final NLU data for the supply_contact_info intent." }, { "code": null, "e": 8168, "s": 7800, "text": "version: \"2.0\"nlu:- intent: supply_contact_info examples: | - My name is [John](name). email's [[email protected]](email) - name: [David](name) email: [[email protected]](email) - Yeah sure. I'm [Barbara](name). My email is [[email protected]](email) - [Susan](name), [[email protected]](email) - Sure. It's [Fred](name). My email is [[email protected]](email)." }, { "code": null, "e": 8346, "s": 8168, "text": "We also have another intent called the greet intent, which is when the user starts the conversation and says things like “hi” or “hello”. Finally, nlu.yml should look like this." }, { "code": null, "e": 8747, "s": 8346, "text": "nlu:- intent: greet examples: | - hi - hello- intent: supply_contact_info examples: | - My name is [John](name). email's [[email protected]](email) - name: [David](name) email: [[email protected]](email) - Yeah sure. I'm [Barbara](name). My email is [[email protected]](email) - [Susan](name), [[email protected]](email) - Sure. It's [Fred](name). My email is [[email protected]](email)." }, { "code": null, "e": 8808, "s": 8747, "text": "Now that we have intents and entities, we can add our slots." }, { "code": null, "e": 8883, "s": 8808, "text": "Head to the file domain.yml . Replace the contents of slots key with this." }, { "code": null, "e": 8933, "s": 8883, "text": "slots: name: type: text email: type: text" }, { "code": null, "e": 9001, "s": 8933, "text": "Since both name and email are strings, we’ll set the type as text ." }, { "code": null, "e": 9128, "s": 9001, "text": "Just as we have intents to abstract out what the user is trying to say, we have responses to represent what the bot would say." }, { "code": null, "e": 9326, "s": 9128, "text": "Simple responses are text-based, though Rasa lets you add more complex features like buttons, alternate responses, responses specific to channels, and even custom actions, which we’ll get to later." }, { "code": null, "e": 9577, "s": 9326, "text": "In our example, after the user greets the bot (intent: greet ), the bot asks the user for their contact info. This can be represented as a bot response or utterance. By convention, we add an “utter” prefix to each bot utterance — something like this:" }, { "code": null, "e": 9604, "s": 9577, "text": "utter_ask_for_contact_info" }, { "code": null, "e": 9679, "s": 9604, "text": "Replace the contents of the responses key in domain.yml with our response." }, { "code": null, "e": 9782, "s": 9679, "text": "responses:utter_ask_for_contact_info:- text: Hello! Could you please provide your contact information?" }, { "code": null, "e": 9929, "s": 9782, "text": "Similarly, we can add a response after the user has provided their information. Let’s call that: utter_acknowledge_provided_info (in bold, below)." }, { "code": null, "e": 10102, "s": 9929, "text": "responses:utter_ask_for_contact_info:- text: Hello! Could you please provide your contact information?utter_acknowledge_provided_info:- text: Thanks for provided your info!" }, { "code": null, "e": 10263, "s": 10102, "text": "We could make the user experience slightly better here by mentioning the user’s name along with the acknowledgement — something like “Thanks John for the info!”" }, { "code": null, "e": 10383, "s": 10263, "text": "To do this, we’ll modify the utter_acknowledge_provided_info above by adding a placeholder for the name slot like this:" }, { "code": null, "e": 10461, "s": 10383, "text": "utter_acknowledge_provided_info:- text: Thanks {name} for provided your info!" }, { "code": null, "e": 10651, "s": 10461, "text": "Stories give our bot an idea of how the conversation should flow. Returning to our example, where the bot asks the user for their contact details, the conversation went something like this:" }, { "code": null, "e": 10847, "s": 10651, "text": "user: Hi. (bot classifies this message as \"greet\")bot: Hello! Could you please provide your contact information?user: Sure. It's John. My email is [email protected]: Thanks John for the info!" }, { "code": null, "e": 10907, "s": 10847, "text": "This can be broken down into intents and responses like so:" }, { "code": null, "e": 11021, "s": 10907, "text": "intent: greetaction: utter_ask_for_contact_infointent: supply_contact_infoaction: utter_acknowledge_provided_info" }, { "code": null, "e": 11196, "s": 11021, "text": "Let’s turn this into a syntax rasa can understand. Replace the contents of the file stories.yml with what’ll discuss here. Let’s call the story “user supplies customer info”." }, { "code": null, "e": 11241, "s": 11196, "text": "Story names do not affect how the bot works." }, { "code": null, "e": 11437, "s": 11241, "text": "version: \"2.0\"stories:- story: user supplies customer info steps: - intent: greet - action: utter_ask_for_contact_info - intent: supply_contact_info - action: utter_acknowledge_provided_info" }, { "code": null, "e": 11465, "s": 11437, "text": "But there’s one thing left." }, { "code": null, "e": 11596, "s": 11465, "text": "We also have to indicate what entities a user intent will likely provide, so it's easier for the bot to figure out how to respond." }, { "code": null, "e": 11678, "s": 11596, "text": "Under an intent, just list the entities that are likely to appear in that intent." }, { "code": null, "e": 11908, "s": 11678, "text": "version: \"2.0\"stories:- story: user supplies customer info steps: - intent: greet - action: utter_ask_for_contact_info - intent: supply_contact_info entities: - name - email - action: utter_acknowledge_provided_info" }, { "code": null, "e": 12009, "s": 11908, "text": "Now that we have our data and stories ready, we’ll have to follow some steps to get our bot running." }, { "code": null, "e": 12074, "s": 12009, "text": "We made a few changes to the files in our demo bot. Let’s recap." }, { "code": null, "e": 12127, "s": 12074, "text": "nlu.yml — houses the NLU training data for our model" }, { "code": null, "e": 12186, "s": 12127, "text": "In this file, we keep the tagged data for our two intents:" }, { "code": null, "e": 12206, "s": 12186, "text": "supply_contact_info" }, { "code": null, "e": 12212, "s": 12206, "text": "greet" }, { "code": null, "e": 12283, "s": 12212, "text": "stories.yml— gives the bot an idea of how the conversation should flow" }, { "code": null, "e": 12317, "s": 12283, "text": "Our single story is located here." }, { "code": null, "e": 12387, "s": 12317, "text": "domain.yml — the complete info of all intents, responses and entities" }, { "code": null, "e": 12600, "s": 12387, "text": "This file is a little more complex than the other two. If you look at the domain.yml file provided in the demo bot (post running rasa init ), you’ll notice keys like intents , actions , responses , entities ,etc." }, { "code": null, "e": 12757, "s": 12600, "text": "We’ve already added slotsand responses to our domain.yml . All we need to do now is mention our intents and entities. Finally, the file will look like this:" }, { "code": null, "e": 13057, "s": 12757, "text": "version: '2.0'intents:- greet- supply_contact_infoentities:- name- emailslots: name: type: text email: type: textresponses: utter_ask_for_contact_info: - text: Hello! Could you please provide your contact information? utter_acknowledge_provided_info: - text: Thanks {name}, for the info!" }, { "code": null, "e": 13077, "s": 13057, "text": "Validating the data" }, { "code": null, "e": 13237, "s": 13077, "text": "Before training the bot, a good practice is to check for any inconsistencies in the stories and rules, though in a project this simple, it's unlikely to occur." }, { "code": null, "e": 13258, "s": 13237, "text": "$ rasa data validate" }, { "code": null, "e": 13356, "s": 13258, "text": "The truncated output looks like this. No conflicts were found, so we are good to train our model." }, { "code": null, "e": 13728, "s": 13356, "text": "The configuration for policies and pipeline was chosen automatically. It was written into the config file at 'config.yml'.2021-09-12 18:36:07 INFO rasa.validator - Validating intents...2021-09-12 18:36:07 INFO rasa.validator - Validating uniqueness of intents and stories... ...2021-09-12 18:36:08 INFO rasa.validator - No story structure conflicts found." }, { "code": null, "e": 13769, "s": 13728, "text": "Note: You may get the following warning:" }, { "code": null, "e": 13929, "s": 13769, "text": "UserWarning: model_confidence is set to `softmax`. It is recommended to try using `model_confidence=linear_norm` to make it easier to tune fallback thresholds." }, { "code": null, "e": 13980, "s": 13929, "text": "This is just a recommendation, and can be ignored." }, { "code": null, "e": 13989, "s": 13980, "text": "Training" }, { "code": null, "e": 14128, "s": 13989, "text": "To train the bot, we simply use the rasa train command. We’ll provide a name to the model for better organization, but it's not necessary." }, { "code": null, "e": 14172, "s": 14128, "text": "$ rasa train --fixed-model-name contact_bot" }, { "code": null, "e": 14243, "s": 14172, "text": "The output for this is a lot bigger, so I won’t be displaying it here." }, { "code": null, "e": 14284, "s": 14243, "text": "Note: You may get the following warning:" }, { "code": null, "e": 14497, "s": 14284, "text": "UserWarning: Found a rule-based policy in your pipeline but no rule-based training data. Please add rule-based stories to your training data or remove the rule-based policy (`RulePolicy`) from your your pipeline." }, { "code": null, "e": 14745, "s": 14497, "text": "We won’t be discussing rules in this post, but they are essentially what they sound like. They require something called a RulePolicy, which is by default, added to your bot pipeline. Can be ignored for now. This will be discussed in a future post." }, { "code": null, "e": 14833, "s": 14745, "text": "Chatting with our new bot is simple. Open a new terminal window and start a rasa shell." }, { "code": null, "e": 14846, "s": 14833, "text": "$ rasa shell" }, { "code": null, "e": 15042, "s": 14846, "text": "This will let you chat with your bot in your terminal. But if you want to cleaner UI and a little more info like what intents were identified and what entities were extracted, you can use Rasa X." }, { "code": null, "e": 15265, "s": 15042, "text": "Just a quick point about Rasa X: It lets you test your bot, fix incorrect responses from your bot, and more importantly, you can share your bot with other people to get a better idea of how it’ll perform in the real world." }, { "code": null, "e": 15302, "s": 15265, "text": "To use it, install it in local mode." }, { "code": null, "e": 15371, "s": 15302, "text": "$ pip3 install rasa-x --extra-index-url https://pypi.rasa.com/simple" }, { "code": null, "e": 15385, "s": 15371, "text": "Then, run it." }, { "code": null, "e": 15394, "s": 15385, "text": "$ rasa x" }, { "code": null, "e": 15482, "s": 15394, "text": "Head to “Talk to Your bot” in the menu on the left, and start conversing with your bot." }, { "code": null, "e": 15523, "s": 15482, "text": "Below, you can see how our bot performs." }, { "code": null, "e": 15762, "s": 15523, "text": "In the conversation above, apart from the dialogues, you’ll notice some greyed out information. Below each user message, you can see what intent the user message fell into and with what confidence, along with what entities were extracted." }, { "code": null, "e": 15892, "s": 15762, "text": "Above each bot message, you can see what action the bot decided to take with what confidence, along with any slots that were set." }, { "code": null, "e": 15975, "s": 15892, "text": "action_listen is an inbuilt action that means that the chatbot expects user input." }, { "code": null, "e": 16024, "s": 15975, "text": "All code used in this article is available here:" }, { "code": null, "e": 16035, "s": 16024, "text": "github.com" }, { "code": null, "e": 16040, "s": 16035, "text": "Rasa" }, { "code": null, "e": 16070, "s": 16040, "text": "5 levels of conversational AI" }, { "code": null, "e": 16242, "s": 16070, "text": "Rasa is a great tool for conversational AI. Its flexibility and depth of customization make it a good choice of tool. In this post, the bot we built was a very simple one." }, { "code": null, "e": 16493, "s": 16242, "text": "There’s a lot more to it than what I could fit in a single post, like actions, forms, rules, regex, synonyms, interactive learning, config files, pipelines, and so much more. But what has been covered in this post should be enough to get you started." }, { "code": null, "e": 16588, "s": 16493, "text": "We’ll cover the rest in future posts. I’ll add links to all future posts here. Hope it helped!" }, { "code": null, "e": 16630, "s": 16588, "text": "Part II: Are Slots and Entities the same?" }, { "code": null, "e": 16665, "s": 16630, "text": "Part III: Handling Chatbot Failure" }, { "code": null, "e": 16702, "s": 16665, "text": "Part IV: How do Chatbots understand?" }, { "code": null, "e": 16712, "s": 16702, "text": "20.3.2022" } ]
Computer Programming - Strings
During our discussion about characters, we learnt that character data type deals with a single character and you can assign any character from your keyboard to a character type variable. Now, let's move a little bit ahead and consider a situation where we need to store more than one character in a variable. We have seen that C programming does not allow to store more than one character in a character type variable. So the following statements are invalid in C programming and produce syntax errors − char ch1 = 'ab'; char ch2 = '10'; We have also seen how to use the concept of arrays to store more than one value of similar data type in a variable. Here is the syntax to store and print five numbers in an array of int type − #include <stdio.h> main() { int number[5] = {10, 20, 30, 40, 50}; int i = 0; while( i < 5 ) { printf("number[%d] = %d\n", i, number[i] ); i = i + 1; } } When the above code is compiled and executed, it produces the following result − number[0] = 10 number[1] = 20 number[2] = 30 number[3] = 40 number[4] = 50 Now, let's define an array of five characters in the same way as we did for numbers and try to print them − #include <stdio.h> main() { char ch[5] = {'H', 'e', 'l', 'l', 'o'}; int i = 0; while( i < 5 ) { printf("ch[%d] = %c\n", i, ch[i] ); i = i + 1; } } Here, we used %c to print character value. When the above code is compiled and executed, it produces the following result − ch[0] = H ch[1] = e ch[2] = l ch[3] = l ch[4] = o If you are done with the above example, then I think you understood how strings work in C programming, because strings in C are represented as arrays of characters. C programming simplified the assignment and printing of strings. Let's check the same example once again with a simplified syntax − #include <stdio.h> main() { char ch[5] = "Hello"; int i = 0; /* Print as a complete string */ printf("String = %s\n", ch); /* Print character by character */ while( i < 5 ) { printf("ch[%d] = %c\n", i, ch[i] ); i = i + 1; } } Here, we used %s to print the full string value using array name ch, which is actually the beginning of the memory address holding ch variable as shown below − Although it's not visible from the above examples, a C program internally assigns null character '\0' as the last character of every string. It indicates the end of the string and it means if you want to store a 5 character string in an array, then you must define an array size of 6 as a good practice, though C does not complain about it. If the above code is compiled and executed, it produces the following result − String = Hello ch[0] = H ch[1] = e ch[2] = l ch[3] = l ch[4] = o Based on the above discussion, we can conclude the following important points about strings in C programming language − Strings in C are represented as arrays of characters. Strings in C are represented as arrays of characters. We can constitute a string in C programming by assigning character by character into an array of characters. We can constitute a string in C programming by assigning character by character into an array of characters. We can constitute a string in C programming by assigning a complete string enclosed in double quote. We can constitute a string in C programming by assigning a complete string enclosed in double quote. We can print a string character by character using an array subscript or a complete string by using an array name without subscript. We can print a string character by character using an array subscript or a complete string by using an array name without subscript. The last character of every string is a null character, i.e., ‘\0’. The last character of every string is a null character, i.e., ‘\0’. Most of the programming languages provide built-in functions to manipulate strings, i.e., you can concatenate strings, you can search from a string, you can extract sub-strings from a string, etc. For more, you can check our detailed tutorial on C programming or any other programming language. Most of the programming languages provide built-in functions to manipulate strings, i.e., you can concatenate strings, you can search from a string, you can extract sub-strings from a string, etc. For more, you can check our detailed tutorial on C programming or any other programming language. Though you can use character arrays to store strings, but Java is an advanced programming language and its designers tried to provide additional functionality. Java provides strings as a built-in data type like any other data type. It means you can define strings directly instead of defining them as array of characters. Following is the equivalent program written in Java. Java makes use of the new operator to create string variables as shown in the following program. You can try to execute the following program to see the output − public class DemoJava { public static void main(String []args) { String str = new String("Hello"); System.out.println( "String = " + str ); } } When the above program is executed, it produces the following result − String = Hello Creating strings in Python is as simple as assigning a string into a Python variable using single or double quotes. Given below is a simple program that creates two strings and prints them using print() function − var1 = 'Hello World!' var2 = "Python Programming" print "var1 = ", var1 print "var2 = ", var2 When the above program is executed, it produces the following result − var1 = Hello World! var2 = Python Programming Python does not support character type; these are treated as strings of length one, thus also considered a substring. To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. Take a look at the following code segment − var1 = 'Hello World!' var2 = "Python Programming" print "var1[0]: ", var1[0] print "var2[1:5]: ", var2[1:5] When the above code is executed, it produces the following result − var1[0]: H var2[1:5]: ytho 107 Lectures 13.5 hours Arnab Chakraborty 106 Lectures 8 hours Arnab Chakraborty 99 Lectures 6 hours Arnab Chakraborty 46 Lectures 2.5 hours Shweta 70 Lectures 9 hours Abhilash Nelson 52 Lectures 7 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2327, "s": 2140, "text": "During our discussion about characters, we learnt that character data type deals with a single character and you can assign any character from your keyboard to a character type variable." }, { "code": null, "e": 2644, "s": 2327, "text": "Now, let's move a little bit ahead and consider a situation where we need to store more than one character in a variable. We have seen that C programming does not allow to store more than one character in a character type variable. So the following statements are invalid in C programming and produce syntax errors −" }, { "code": null, "e": 2679, "s": 2644, "text": "char ch1 = 'ab';\nchar ch2 = '10';\n" }, { "code": null, "e": 2872, "s": 2679, "text": "We have also seen how to use the concept of arrays to store more than one value of similar data type in a variable. Here is the syntax to store and print five numbers in an array of int type −" }, { "code": null, "e": 3059, "s": 2872, "text": "#include <stdio.h>\n\nmain() {\n int number[5] = {10, 20, 30, 40, 50};\n int i = 0;\n \n while( i < 5 ) {\n printf(\"number[%d] = %d\\n\", i, number[i] );\n i = i + 1;\n }\n}" }, { "code": null, "e": 3140, "s": 3059, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3216, "s": 3140, "text": "number[0] = 10\nnumber[1] = 20\nnumber[2] = 30\nnumber[3] = 40\nnumber[4] = 50\n" }, { "code": null, "e": 3324, "s": 3216, "text": "Now, let's define an array of five characters in the same way as we did for numbers and try to print them −" }, { "code": null, "e": 3505, "s": 3324, "text": "#include <stdio.h>\n\nmain() {\n char ch[5] = {'H', 'e', 'l', 'l', 'o'};\n int i = 0;\n \n while( i < 5 ) {\n printf(\"ch[%d] = %c\\n\", i, ch[i] );\n i = i + 1;\n }\n}" }, { "code": null, "e": 3629, "s": 3505, "text": "Here, we used %c to print character value. When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3680, "s": 3629, "text": "ch[0] = H\nch[1] = e\nch[2] = l\nch[3] = l\nch[4] = o\n" }, { "code": null, "e": 3977, "s": 3680, "text": "If you are done with the above example, then I think you understood how strings work in C programming, because strings in C are represented as arrays of characters. C programming simplified the assignment and printing of strings. Let's check the same example once again with a simplified syntax −" }, { "code": null, "e": 4245, "s": 3977, "text": "#include <stdio.h>\n\nmain() {\n char ch[5] = \"Hello\";\n int i = 0;\n \n /* Print as a complete string */\n printf(\"String = %s\\n\", ch); \n\n /* Print character by character */\n while( i < 5 ) {\n printf(\"ch[%d] = %c\\n\", i, ch[i] );\n i = i + 1;\n }\n}" }, { "code": null, "e": 4405, "s": 4245, "text": "Here, we used %s to print the full string value using array name ch, which is actually the beginning of the memory address holding ch variable as shown below −" }, { "code": null, "e": 4746, "s": 4405, "text": "Although it's not visible from the above examples, a C program internally assigns null character '\\0' as the last character of every string. It indicates the end of the string and it means if you want to store a 5 character string in an array, then you must define an array size of 6 as a good practice, though C does not complain about it." }, { "code": null, "e": 4825, "s": 4746, "text": "If the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4891, "s": 4825, "text": "String = Hello\nch[0] = H\nch[1] = e\nch[2] = l\nch[3] = l\nch[4] = o\n" }, { "code": null, "e": 5011, "s": 4891, "text": "Based on the above discussion, we can conclude the following important points about strings in C programming language −" }, { "code": null, "e": 5065, "s": 5011, "text": "Strings in C are represented as arrays of characters." }, { "code": null, "e": 5119, "s": 5065, "text": "Strings in C are represented as arrays of characters." }, { "code": null, "e": 5228, "s": 5119, "text": "We can constitute a string in C programming by assigning character by character into an array of characters." }, { "code": null, "e": 5337, "s": 5228, "text": "We can constitute a string in C programming by assigning character by character into an array of characters." }, { "code": null, "e": 5438, "s": 5337, "text": "We can constitute a string in C programming by assigning a complete string enclosed in double quote." }, { "code": null, "e": 5539, "s": 5438, "text": "We can constitute a string in C programming by assigning a complete string enclosed in double quote." }, { "code": null, "e": 5672, "s": 5539, "text": "We can print a string character by character using an array subscript or a complete string by using an array name without subscript." }, { "code": null, "e": 5805, "s": 5672, "text": "We can print a string character by character using an array subscript or a complete string by using an array name without subscript." }, { "code": null, "e": 5873, "s": 5805, "text": "The last character of every string is a null character, i.e., ‘\\0’." }, { "code": null, "e": 5941, "s": 5873, "text": "The last character of every string is a null character, i.e., ‘\\0’." }, { "code": null, "e": 6236, "s": 5941, "text": "Most of the programming languages provide built-in functions to manipulate strings, i.e., you can concatenate strings, you can search from a string, you can extract sub-strings from a string, etc. For more, you can check our detailed tutorial on C programming or any other programming language." }, { "code": null, "e": 6531, "s": 6236, "text": "Most of the programming languages provide built-in functions to manipulate strings, i.e., you can concatenate strings, you can search from a string, you can extract sub-strings from a string, etc. For more, you can check our detailed tutorial on C programming or any other programming language." }, { "code": null, "e": 6853, "s": 6531, "text": "Though you can use character arrays to store strings, but Java is an advanced programming language and its designers tried to provide additional functionality. Java provides strings as a built-in data type like any other data type. It means you can define strings directly instead of defining them as array of characters." }, { "code": null, "e": 7003, "s": 6853, "text": "Following is the equivalent program written in Java. Java makes use of the new operator to create string variables as shown in the following program." }, { "code": null, "e": 7068, "s": 7003, "text": "You can try to execute the following program to see the output −" }, { "code": null, "e": 7232, "s": 7068, "text": "public class DemoJava {\n public static void main(String []args) {\n String str = new String(\"Hello\"); \n System.out.println( \"String = \" + str );\n }\n}" }, { "code": null, "e": 7303, "s": 7232, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 7319, "s": 7303, "text": "String = Hello\n" }, { "code": null, "e": 7435, "s": 7319, "text": "Creating strings in Python is as simple as assigning a string into a Python variable using single or double quotes." }, { "code": null, "e": 7533, "s": 7435, "text": "Given below is a simple program that creates two strings and prints them using print() function −" }, { "code": null, "e": 7628, "s": 7533, "text": "var1 = 'Hello World!'\nvar2 = \"Python Programming\"\n\nprint \"var1 = \", var1\nprint \"var2 = \", var2" }, { "code": null, "e": 7699, "s": 7628, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 7748, "s": 7699, "text": "var1 = Hello World!\nvar2 = Python Programming\n" }, { "code": null, "e": 7866, "s": 7748, "text": "Python does not support character type; these are treated as strings of length one, thus also considered a substring." }, { "code": null, "e": 8026, "s": 7866, "text": "To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. Take a look at the following code segment −" }, { "code": null, "e": 8135, "s": 8026, "text": "var1 = 'Hello World!'\nvar2 = \"Python Programming\"\n\nprint \"var1[0]: \", var1[0]\nprint \"var2[1:5]: \", var2[1:5]" }, { "code": null, "e": 8203, "s": 8135, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 8233, "s": 8203, "text": "var1[0]: H\nvar2[1:5]: ytho\n" }, { "code": null, "e": 8270, "s": 8233, "text": "\n 107 Lectures \n 13.5 hours \n" }, { "code": null, "e": 8289, "s": 8270, "text": " Arnab Chakraborty" }, { "code": null, "e": 8323, "s": 8289, "text": "\n 106 Lectures \n 8 hours \n" }, { "code": null, "e": 8342, "s": 8323, "text": " Arnab Chakraborty" }, { "code": null, "e": 8375, "s": 8342, "text": "\n 99 Lectures \n 6 hours \n" }, { "code": null, "e": 8394, "s": 8375, "text": " Arnab Chakraborty" }, { "code": null, "e": 8429, "s": 8394, "text": "\n 46 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8437, "s": 8429, "text": " Shweta" }, { "code": null, "e": 8470, "s": 8437, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 8487, "s": 8470, "text": " Abhilash Nelson" }, { "code": null, "e": 8520, "s": 8487, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 8542, "s": 8520, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 8549, "s": 8542, "text": " Print" }, { "code": null, "e": 8560, "s": 8549, "text": " Add Notes" } ]
Create red neon glow shadow using CSS
To create red neon glow shadow, use the text-shadow property. You can try to run the following code to achieve this Live Demo <!DOCTYPE html> <html> <head> <style> h1 { text-shadow: 0 0 4px #FF0000; } </style> </head> <body> <h1>Heading One</h1> <p>Above heading has a read neon glow shadow effect.</p> </body> </html>
[ { "code": null, "e": 1178, "s": 1062, "text": "To create red neon glow shadow, use the text-shadow property. You can try to run the following code to achieve this" }, { "code": null, "e": 1188, "s": 1178, "text": "Live Demo" }, { "code": null, "e": 1447, "s": 1188, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n h1 {\n text-shadow: 0 0 4px #FF0000;\n }\n </style>\n </head>\n <body>\n <h1>Heading One</h1>\n <p>Above heading has a read neon glow shadow effect.</p>\n </body>\n</html>" } ]
Graph Data Structure in Javascript
A graph is a pictorial representation of a set of objects where some pairs of objects are connected by links. The interconnected objects are represented by points termed as vertices, and the links that connect the vertices are called edges. Formally, a graph is a pair of sets (V, E), where V is the set of vertices and E is the set of edges, connecting the pairs of vertices. Take a look at the following graph − In the above graph, V = {a, b, c, d, e} E = {ab, ac, bd, cd, de} Mathematical graphs can be represented in the data structure. We can represent a graph using an array of vertices and a two-dimensional array of edges. Before we proceed further, let's familiarize ourselves with some important terms − Vertex − Each node of the graph is represented as a vertex. In the following example, the labeled circle represents vertices. Thus, A to G are vertices. We can represent them using an array as shown in the following image. Here A can be identified by index 0. B can be identified using index 1 and so on. Vertex − Each node of the graph is represented as a vertex. In the following example, the labeled circle represents vertices. Thus, A to G are vertices. We can represent them using an array as shown in the following image. Here A can be identified by index 0. B can be identified using index 1 and so on. Edge − Edge represents a path between two vertices or a line between two vertices. In the following example, the lines from A to B, B to C, and so on represent edges. We can use a two-dimensional array to represent an array as shown in the following image. Here AB can be represented as 1 at row 0, column 1, BC as 1 at row 1, column 2 and so on, keeping other combinations as 0. Edge − Edge represents a path between two vertices or a line between two vertices. In the following example, the lines from A to B, B to C, and so on represent edges. We can use a two-dimensional array to represent an array as shown in the following image. Here AB can be represented as 1 at row 0, column 1, BC as 1 at row 1, column 2 and so on, keeping other combinations as 0. Adjacency − Two node or vertices are adjacent if they are connected to each other through an edge. In the following example, B is adjacent to A, C is adjacent to B, and so on. Adjacency − Two node or vertices are adjacent if they are connected to each other through an edge. In the following example, B is adjacent to A, C is adjacent to B, and so on. Path − Path represents a sequence of edges between the two vertices. In the following example, ABCD represents a path from A to D. Path − Path represents a sequence of edges between the two vertices. In the following example, ABCD represents a path from A to D. Here is the complete implementation of the Graph Class using Javascript. const Queue = require("./Queue"); const Stack = require("./Stack"); const PriorityQueue = require("./PriorityQueue"); class Graph { constructor() { this.edges = {}; this.nodes = []; } addNode(node) { this.nodes.push(node); this.edges[node] = []; } addEdge(node1, node2, weight = 1) { this.edges[node1].push({ node: node2, weight: weight }); this.edges[node2].push({ node: node1, weight: weight }); } addDirectedEdge(node1, node2, weight = 1) { this.edges[node1].push({ node: node2, weight: weight }); } // addEdge(node1, node2) { // this.edges[node1].push(node2); // this.edges[node2].push(node1); // } // addDirectedEdge(node1, node2) { // this.edges[node1].push(node2); // } display() { let graph = ""; this.nodes.forEach(node => { graph += node + "->" + this.edges[node].map(n => n.node).join(", ") + "\n"; }); console.log(graph); } BFS(node) { let q = new Queue(this.nodes.length); let explored = new Set(); q.enqueue(node); explored.add(node); while (!q.isEmpty()) { let t = q.dequeue(); console.log(t); this.edges[t].filter(n => !explored.has(n)).forEach(n => { explored.add(n); q.enqueue(n); }); } } DFS(node) { // Create a Stack and add our initial node in it let s = new Stack(this.nodes.length); let explored = new Set(); s.push(node); // Mark the first node as explored explored.add(node); // We'll continue till our Stack gets empty while (!s.isEmpty()) { let t = s.pop(); // Log every element that comes out of the Stack console.log(t); // 1. In the edges object, we search for nodes this node is directly connected to. // 2. We filter out the nodes that have already been explored. // 3. Then we mark each unexplored node as explored and push it to the Stack. this.edges[t].filter(n => !explored.has(n)).forEach(n => { explored.add(n); s.push(n); }); } } topologicalSortHelper(node, explored, s) { explored.add(node); this.edges[node].forEach(n => { if (!explored.has(n)) { this.topologicalSortHelper(n, explored, s); } }); s.push(node); } topologicalSort() { // Create a Stack and add our initial node in it let s = new Stack(this.nodes.length); let explored = new Set(); this.nodes.forEach(node => { if (!explored.has(node)) { this.topologicalSortHelper(node, explored, s); } }); while (!s.isEmpty()) { console.log(s.pop()); } } BFSShortestPath(n1, n2) { let q = new Queue(this.nodes.length); let explored = new Set(); let distances = { n1: 0 }; q.enqueue(n1); explored.add(n1); while (!q.isEmpty()) { let t = q.dequeue(); this.edges[t].filter(n => !explored.has(n)).forEach(n => { explored.add(n); distances[n] = distances[t] == undefined ? 1 : distances[t] + 1; q.enqueue(n); }); } return distances[n2]; } primsMST() { // Initialize graph that'll contain the MST const MST = new Graph(); if (this.nodes.length === 0) { return MST; } // Select first node as starting node let s = this.nodes[0]; // Create a Priority Queue and explored set let edgeQueue = new PriorityQueue(this.nodes.length * this.nodes.length); let explored = new Set(); explored.add(s); MST.addNode(s); // Add all edges from this starting node to the PQ taking weights as priority this.edges[s].forEach(edge => { edgeQueue.enqueue([s, edge.node], edge.weight); }); // Take the smallest edge and add that to the new graph let currentMinEdge = edgeQueue.dequeue(); while (!edgeQueue.isEmpty()) { // COntinue removing edges till we get an edge with an unexplored node while (!edgeQueue.isEmpty() && explored.has(currentMinEdge.data[1])) { currentMinEdge = edgeQueue.dequeue(); } let nextNode = currentMinEdge.data[1]; // Check again as queue might get empty without giving back unexplored element if (!explored.has(nextNode)) { MST.addNode(nextNode); MST.addEdge(currentMinEdge.data[0], nextNode, currentMinEdge.priority); // Again add all edges to the PQ this.edges[nextNode].forEach(edge => { edgeQueue.enqueue([nextNode, edge.node], edge.weight); }); // Mark this node as explored explored.add(nextNode); s = nextNode; } } return MST; } kruskalsMST() { // Initialize graph that'll contain the MST const MST = new Graph(); this.nodes.forEach(node => MST.addNode(node)); if (this.nodes.length === 0) { return MST; } // Create a Priority Queue let edgeQueue = new PriorityQueue(this.nodes.length * this.nodes.length); // Add all edges to the Queue: for (let node in this.edges) { this.edges[node].forEach(edge => { edgeQueue.enqueue([node, edge.node], edge.weight); }); } let uf = new UnionFind(this.nodes); // Loop until either we explore all nodes or queue is empty while (!edgeQueue.isEmpty()) { // Get the edge data using destructuring let nextEdge = edgeQueue.dequeue(); let nodes = nextEdge.data; let weight = nextEdge.priority; if (!uf.connected(nodes[0], nodes[1])) { MST.addEdge(nodes[0], nodes[1], weight); uf.union(nodes[0], nodes[1]); } } return MST; } djikstraAlgorithm(startNode) { let distances = {}; // Stores the reference to previous nodes let prev = {}; let pq = new PriorityQueue(this.nodes.length * this.nodes.length); // Set distances to all nodes to be infinite except startNode distances[startNode] = 0; pq.enqueue(startNode, 0); this.nodes.forEach(node => { if (node !== startNode) distances[node] = Infinity; prev[node] = null; }); while (!pq.isEmpty()) { let minNode = pq.dequeue(); let currNode = minNode.data; let weight = minNode.priority; this.edges[currNode].forEach(neighbor => { let alt = distances[currNode] + neighbor.weight; if (alt < distances[neighbor.node]) { distances[neighbor.node] = alt; prev[neighbor.node] = currNode; pq.enqueue(neighbor.node, distances[neighbor.node]); } }); } return distances; } floydWarshallAlgorithm() { let dist = {}; for (let i = 0; i < this.nodes.length; i++) { dist[this.nodes[i]] = {}; // For existing edges assign the dist to be same as weight this.edges[this.nodes[i]].forEach(e => (dist[this.nodes[i]][e.node] = e.weight)); this.nodes.forEach(n => { // For all other nodes assign it to infinity if (dist[this.nodes[i]][n] == undefined) dist[this.nodes[i]][n] = Infinity; // For self edge assign dist to be 0 if (this.nodes[i] === n) dist[this.nodes[i]][n] = 0; }); } this.nodes.forEach(i => { this.nodes.forEach(j => { this.nodes.forEach(k => { // Check if going from i to k then from k to j is better // than directly going from i to j. If yes then update // i to j value to the new value if (dist[i][k] + dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j]; }); }); }); return dist; } } class UnionFind { constructor(elements) { // Number of disconnected components this.count = elements.length; // Keep Track of connected components this.parent = {}; // Initialize the data structure such that all elements have themselves as parents elements.forEach(e => (this.parent[e] = e)); } union(a, b) { let rootA = this.find(a); let rootB = this.find(b); // Roots are same so these are already connected. if (rootA === rootB) return; // Always make the element with smaller root the parent. if (rootA < rootB) { if (this.parent[b] != b) this.union(this.parent[b], a); this.parent[b] = this.parent[a]; } else { if (this.parent[a] != a) this.union(this.parent[a], b); this.parent[a] = this.parent[b]; } } // Returns final parent of a node find(a) { while (this.parent[a] !== a) { a = this.parent[a]; } return a; } // Checks connectivity of the 2 nodes connected(a, b) { return this.find(a) === this.find(b); } }
[ { "code": null, "e": 1303, "s": 1062, "text": "A graph is a pictorial representation of a set of objects where some pairs of objects are connected by links. The interconnected objects are represented by points termed as vertices, and the links that connect the vertices are called edges." }, { "code": null, "e": 1476, "s": 1303, "text": "Formally, a graph is a pair of sets (V, E), where V is the set of vertices and E is the set of edges, connecting the pairs of vertices. Take a look at the following graph −" }, { "code": null, "e": 1496, "s": 1476, "text": "In the above graph," }, { "code": null, "e": 1541, "s": 1496, "text": "V = {a, b, c, d, e}\nE = {ab, ac, bd, cd, de}" }, { "code": null, "e": 1776, "s": 1541, "text": "Mathematical graphs can be represented in the data structure. We can represent a graph using an array of vertices and a two-dimensional array of edges. Before we proceed further, let's familiarize ourselves with some important terms −" }, { "code": null, "e": 2081, "s": 1776, "text": "Vertex − Each node of the graph is represented as a vertex. In the following example, the labeled circle represents vertices. Thus, A to G are vertices. We can represent them using an array as shown in the following image. Here A can be identified by index 0. B can be identified using index 1 and so on." }, { "code": null, "e": 2386, "s": 2081, "text": "Vertex − Each node of the graph is represented as a vertex. In the following example, the labeled circle represents vertices. Thus, A to G are vertices. We can represent them using an array as shown in the following image. Here A can be identified by index 0. B can be identified using index 1 and so on." }, { "code": null, "e": 2766, "s": 2386, "text": "Edge − Edge represents a path between two vertices or a line between two vertices. In the following example, the lines from A to B, B to C, and so on represent edges. We can use a two-dimensional array to represent an array as shown in the following image. Here AB can be represented as 1 at row 0, column 1, BC as 1 at row 1, column 2 and so on, keeping other combinations as 0." }, { "code": null, "e": 3146, "s": 2766, "text": "Edge − Edge represents a path between two vertices or a line between two vertices. In the following example, the lines from A to B, B to C, and so on represent edges. We can use a two-dimensional array to represent an array as shown in the following image. Here AB can be represented as 1 at row 0, column 1, BC as 1 at row 1, column 2 and so on, keeping other combinations as 0." }, { "code": null, "e": 3322, "s": 3146, "text": "Adjacency − Two node or vertices are adjacent if they are connected to each other through an edge. In the following example, B is adjacent to A, C is adjacent to B, and so on." }, { "code": null, "e": 3498, "s": 3322, "text": "Adjacency − Two node or vertices are adjacent if they are connected to each other through an edge. In the following example, B is adjacent to A, C is adjacent to B, and so on." }, { "code": null, "e": 3629, "s": 3498, "text": "Path − Path represents a sequence of edges between the two vertices. In the following example, ABCD represents a path from A to D." }, { "code": null, "e": 3760, "s": 3629, "text": "Path − Path represents a sequence of edges between the two vertices. In the following example, ABCD represents a path from A to D." }, { "code": null, "e": 3833, "s": 3760, "text": "Here is the complete implementation of the Graph Class using Javascript." }, { "code": null, "e": 13070, "s": 3833, "text": "const Queue = require(\"./Queue\");\nconst Stack = require(\"./Stack\");\nconst PriorityQueue = require(\"./PriorityQueue\");\n\nclass Graph {\n constructor() {\n this.edges = {};\n this.nodes = [];\n }\n\n addNode(node) {\n this.nodes.push(node);\n this.edges[node] = [];\n }\n\n addEdge(node1, node2, weight = 1) {\n this.edges[node1].push({ node: node2, weight: weight });\n this.edges[node2].push({ node: node1, weight: weight });\n }\n\n addDirectedEdge(node1, node2, weight = 1) {\n this.edges[node1].push({ node: node2, weight: weight });\n }\n\n // addEdge(node1, node2) {\n // this.edges[node1].push(node2);\n // this.edges[node2].push(node1);\n // }\n\n // addDirectedEdge(node1, node2) {\n // this.edges[node1].push(node2);\n // }\n\n display() {\n let graph = \"\";\n this.nodes.forEach(node => {\n graph += node + \"->\" + this.edges[node].map(n => n.node).join(\", \") + \"\\n\";\n });\n console.log(graph);\n }\n\n BFS(node) {\n let q = new Queue(this.nodes.length);\n let explored = new Set();\n q.enqueue(node);\n explored.add(node);\n while (!q.isEmpty()) {\n let t = q.dequeue();\n console.log(t);\n this.edges[t].filter(n => !explored.has(n)).forEach(n => {\n explored.add(n);\n q.enqueue(n);\n });\n }\n }\n\n DFS(node) {\n // Create a Stack and add our initial node in it\n let s = new Stack(this.nodes.length);\n let explored = new Set();\n s.push(node);\n\n // Mark the first node as explored\n explored.add(node);\n\n // We'll continue till our Stack gets empty\n while (!s.isEmpty()) {\n let t = s.pop();\n\n // Log every element that comes out of the Stack\n console.log(t);\n\n // 1. In the edges object, we search for nodes this node is directly connected to.\n // 2. We filter out the nodes that have already been explored.\n // 3. Then we mark each unexplored node as explored and push it to the Stack.\n this.edges[t].filter(n => !explored.has(n)).forEach(n => {\n explored.add(n);\n s.push(n);\n });\n }\n }\n\n topologicalSortHelper(node, explored, s) {\n explored.add(node);\n this.edges[node].forEach(n => {\n if (!explored.has(n)) {\n this.topologicalSortHelper(n, explored, s);\n }\n });\n s.push(node);\n }\n\n topologicalSort() {\n // Create a Stack and add our initial node in it\n let s = new Stack(this.nodes.length);\n let explored = new Set();\n this.nodes.forEach(node => {\n if (!explored.has(node)) {\n this.topologicalSortHelper(node, explored, s);\n }\n });\n while (!s.isEmpty()) {\n console.log(s.pop());\n }\n }\n\n BFSShortestPath(n1, n2) {\n let q = new Queue(this.nodes.length);\n let explored = new Set();\n let distances = { n1: 0 };\n q.enqueue(n1);\n explored.add(n1);\n while (!q.isEmpty()) {\n let t = q.dequeue();\n this.edges[t].filter(n => !explored.has(n)).forEach(n => {\n explored.add(n);\n distances[n] = distances[t] == undefined ? 1 : distances[t] + 1;\n q.enqueue(n);\n });\n }\n return distances[n2];\n }\n\n primsMST() {\n // Initialize graph that'll contain the MST\n const MST = new Graph();\n if (this.nodes.length === 0) {\n return MST;\n }\n\n // Select first node as starting node\n let s = this.nodes[0];\n\n // Create a Priority Queue and explored set\n let edgeQueue = new PriorityQueue(this.nodes.length * this.nodes.length);\n let explored = new Set();\n explored.add(s);\n MST.addNode(s);\n\n // Add all edges from this starting node to the PQ taking weights as priority\n this.edges[s].forEach(edge => {\n edgeQueue.enqueue([s, edge.node], edge.weight);\n });\n\n // Take the smallest edge and add that to the new graph\n let currentMinEdge = edgeQueue.dequeue();\n while (!edgeQueue.isEmpty()) {\n // COntinue removing edges till we get an edge with an unexplored node\n while (!edgeQueue.isEmpty() && explored.has(currentMinEdge.data[1])) {\n currentMinEdge = edgeQueue.dequeue();\n }\n let nextNode = currentMinEdge.data[1];\n // Check again as queue might get empty without giving back unexplored element\n if (!explored.has(nextNode)) {\n MST.addNode(nextNode);\n MST.addEdge(currentMinEdge.data[0], nextNode, currentMinEdge.priority);\n\n // Again add all edges to the PQ\n this.edges[nextNode].forEach(edge => {\n edgeQueue.enqueue([nextNode, edge.node], edge.weight);\n });\n\n // Mark this node as explored\n explored.add(nextNode);\n s = nextNode;\n }\n }\n return MST;\n }\n\n kruskalsMST() {\n // Initialize graph that'll contain the MST\n const MST = new Graph();\n\n this.nodes.forEach(node => MST.addNode(node));\n if (this.nodes.length === 0) {\n return MST;\n }\n\n // Create a Priority Queue\n let edgeQueue = new PriorityQueue(this.nodes.length * this.nodes.length);\n\n // Add all edges to the Queue:\n for (let node in this.edges) {\n this.edges[node].forEach(edge => {\n edgeQueue.enqueue([node, edge.node], edge.weight);\n });\n }\n let uf = new UnionFind(this.nodes);\n\n // Loop until either we explore all nodes or queue is empty\n while (!edgeQueue.isEmpty()) {\n // Get the edge data using destructuring\n let nextEdge = edgeQueue.dequeue();\n let nodes = nextEdge.data;\n let weight = nextEdge.priority;\n\n if (!uf.connected(nodes[0], nodes[1])) {\n MST.addEdge(nodes[0], nodes[1], weight);\n uf.union(nodes[0], nodes[1]);\n }\n }\n return MST;\n }\n\n djikstraAlgorithm(startNode) {\n let distances = {};\n\n // Stores the reference to previous nodes\n let prev = {};\n let pq = new PriorityQueue(this.nodes.length * this.nodes.length);\n\n // Set distances to all nodes to be infinite except startNode\n distances[startNode] = 0;\n pq.enqueue(startNode, 0);\n\n this.nodes.forEach(node => {\n if (node !== startNode) distances[node] = Infinity;\n prev[node] = null;\n });\n\n while (!pq.isEmpty()) {\n let minNode = pq.dequeue();\n let currNode = minNode.data;\n let weight = minNode.priority;\n\n this.edges[currNode].forEach(neighbor => {\n let alt = distances[currNode] + neighbor.weight;\n if (alt < distances[neighbor.node]) {\n distances[neighbor.node] = alt;\n prev[neighbor.node] = currNode;\n pq.enqueue(neighbor.node, distances[neighbor.node]);\n }\n });\n }\n return distances;\n }\n\n floydWarshallAlgorithm() {\n let dist = {};\n for (let i = 0; i < this.nodes.length; i++) {\n dist[this.nodes[i]] = {};\n\n // For existing edges assign the dist to be same as weight\n this.edges[this.nodes[i]].forEach(e => (dist[this.nodes[i]][e.node] = e.weight));\n\n this.nodes.forEach(n => {\n // For all other nodes assign it to infinity\n if (dist[this.nodes[i]][n] == undefined)\n dist[this.nodes[i]][n] = Infinity;\n // For self edge assign dist to be 0\n if (this.nodes[i] === n) dist[this.nodes[i]][n] = 0;\n });\n}\n\nthis.nodes.forEach(i => {\n this.nodes.forEach(j => {\n this.nodes.forEach(k => {\n // Check if going from i to k then from k to j is better\n // than directly going from i to j. If yes then update\n // i to j value to the new value\n if (dist[i][k] + dist[k][j] < dist[i][j])\n dist[i][j] = dist[i][k] + dist[k][j];\n });\n });\n});\nreturn dist;\n}\n}\n\nclass UnionFind {\n constructor(elements) {\n // Number of disconnected components\n this.count = elements.length;\n\n // Keep Track of connected components\n this.parent = {};\n // Initialize the data structure such that all elements have themselves as parents\n elements.forEach(e => (this.parent[e] = e));\n }\n\n union(a, b) {\n let rootA = this.find(a);\n let rootB = this.find(b);\n\n // Roots are same so these are already connected.\n if (rootA === rootB) return;\n\n // Always make the element with smaller root the parent.\n if (rootA < rootB) {\n if (this.parent[b] != b) this.union(this.parent[b], a);\n this.parent[b] = this.parent[a];\n } else {\n if (this.parent[a] != a) this.union(this.parent[a], b);\n this.parent[a] = this.parent[b];\n }\n }\n\n // Returns final parent of a node\n find(a) {\n while (this.parent[a] !== a) {\n a = this.parent[a];\n }\n return a;\n}\n\n// Checks connectivity of the 2 nodes\n connected(a, b) {\n return this.find(a) === this.find(b);\n }\n}" } ]
Understand how to transfer your paragraph to vector by doc2vec | by Edward Ma | Towards Data Science
In previous story, mentioned word2vec is introduced by Mikolov et al. (2013). Mikolov and Le released sentence/ document vectors transformation. It is another breakthrough on embeddings such that we can use vector to represent a sentence or document. Mikolov et al. call it as “Paragraph Vector”. After reading this article, you will understand: Paragraph Vector Design Architecture Implementation Take Away Design for doc2vec is based on word2vec. If you do not familiar with word2vec (i.e. skip-gram and CBOW), you may check out this story. Doc2vec also uses and unsupervised learning approach to learn the document representation. The input of texts (i.e. word) per document can be various while the output is fixed-length vectors. Paragraph vector and word vectors are initialized. Paragraph vector is unique among all document while word vectors are shared among all document such that word vector can be learnt from different document. During training phase, word vectors will be trained while paragraph will be thrown away after that. During prediction phase (i.e. online prediction), paragraph vector will be initialized randomly and computing it by word vectors. There are 2 algorithms for learning word vectors. Both of them are inspired by learning word vectors which are skip-gram and continuous bag-of-words(CBOW) Distributed Memory Model of Paragraph Vectors (PV-DM) Both paragraph vectors and word vectors are initialized randomly. Every paragraph vector is assigned to single document while word vectors are shared among all documents. Either averaging or concatenating both paragraph vector and words vectors and passing to stochastic gradient descent and the gradient is obtained via back propagation. This approach is similar to continuous bag-of-words (CBOW) approach in word2vec. Distributed Bag of Words version of Paragraph Vector (PV-DBOW) Another approach goes a different way. Instead of predicting next word, it use a paragraph vector to classify entire words in the document. During training, sampling a list of word and then form a classifer to classify whether word belongs to the document such that word vectors can be learnt. This approach is similar to skip-gram approach in word2vec. First of all, we need to to pass the training data to build vocabulary and invoke the training phase in order to compute word vectors. doc2vec_embs = Doc2VecEmbeddings()x_train_tokens = doc2vec_embs.build_vocab(documents=x_train)doc2vec_embs.train(x_train_tokens) After that, we can encode it by providing training data and testing data. x_train_t = doc2vec_embs.encode(documents=x_train)x_test_t = doc2vec_embs.encode(documents=x_test) Finally, we can pass vectors to a classifier from sklearn.linear_model import LogisticRegressionmodel = LogisticRegression(solver='newton-cg', max_iter=1000)model.fit(x_train_t, y_train)y_pred = model.predict(x_test_t)from sklearn.metrics import accuracy_scorefrom sklearn.metrics import classification_reportprint('Accuracy:%.2f%%' % (accuracy_score(y_test, y_pred)*100))print('Classification Report:')print(classification_report(y_test, y_pred)) Result Accuracy: 52.8%Average Precision: 0.66Average Recall: 0.53Average f1: 0.5 To access all code, you can visit my github repo. Unlike word2vec, doc2vec computes sentence/ document vector on the fly. In other word, it takes time to get vector during prediction time. From Mikolov et al. experiment, PV-DM is consistently better than PV-DBOW. In PV-DM approach, concatenation way is often better than sum/ average. Mikolov Tomas, Le Quoc. 2014. Distributed Representations of Sentences and Documents Doc2vec in gensim
[ { "code": null, "e": 468, "s": 171, "text": "In previous story, mentioned word2vec is introduced by Mikolov et al. (2013). Mikolov and Le released sentence/ document vectors transformation. It is another breakthrough on embeddings such that we can use vector to represent a sentence or document. Mikolov et al. call it as “Paragraph Vector”." }, { "code": null, "e": 517, "s": 468, "text": "After reading this article, you will understand:" }, { "code": null, "e": 541, "s": 517, "text": "Paragraph Vector Design" }, { "code": null, "e": 554, "s": 541, "text": "Architecture" }, { "code": null, "e": 569, "s": 554, "text": "Implementation" }, { "code": null, "e": 579, "s": 569, "text": "Take Away" }, { "code": null, "e": 906, "s": 579, "text": "Design for doc2vec is based on word2vec. If you do not familiar with word2vec (i.e. skip-gram and CBOW), you may check out this story. Doc2vec also uses and unsupervised learning approach to learn the document representation. The input of texts (i.e. word) per document can be various while the output is fixed-length vectors." }, { "code": null, "e": 1113, "s": 906, "text": "Paragraph vector and word vectors are initialized. Paragraph vector is unique among all document while word vectors are shared among all document such that word vector can be learnt from different document." }, { "code": null, "e": 1343, "s": 1113, "text": "During training phase, word vectors will be trained while paragraph will be thrown away after that. During prediction phase (i.e. online prediction), paragraph vector will be initialized randomly and computing it by word vectors." }, { "code": null, "e": 1498, "s": 1343, "text": "There are 2 algorithms for learning word vectors. Both of them are inspired by learning word vectors which are skip-gram and continuous bag-of-words(CBOW)" }, { "code": null, "e": 1552, "s": 1498, "text": "Distributed Memory Model of Paragraph Vectors (PV-DM)" }, { "code": null, "e": 1891, "s": 1552, "text": "Both paragraph vectors and word vectors are initialized randomly. Every paragraph vector is assigned to single document while word vectors are shared among all documents. Either averaging or concatenating both paragraph vector and words vectors and passing to stochastic gradient descent and the gradient is obtained via back propagation." }, { "code": null, "e": 1972, "s": 1891, "text": "This approach is similar to continuous bag-of-words (CBOW) approach in word2vec." }, { "code": null, "e": 2035, "s": 1972, "text": "Distributed Bag of Words version of Paragraph Vector (PV-DBOW)" }, { "code": null, "e": 2329, "s": 2035, "text": "Another approach goes a different way. Instead of predicting next word, it use a paragraph vector to classify entire words in the document. During training, sampling a list of word and then form a classifer to classify whether word belongs to the document such that word vectors can be learnt." }, { "code": null, "e": 2389, "s": 2329, "text": "This approach is similar to skip-gram approach in word2vec." }, { "code": null, "e": 2524, "s": 2389, "text": "First of all, we need to to pass the training data to build vocabulary and invoke the training phase in order to compute word vectors." }, { "code": null, "e": 2653, "s": 2524, "text": "doc2vec_embs = Doc2VecEmbeddings()x_train_tokens = doc2vec_embs.build_vocab(documents=x_train)doc2vec_embs.train(x_train_tokens)" }, { "code": null, "e": 2727, "s": 2653, "text": "After that, we can encode it by providing training data and testing data." }, { "code": null, "e": 2826, "s": 2727, "text": "x_train_t = doc2vec_embs.encode(documents=x_train)x_test_t = doc2vec_embs.encode(documents=x_test)" }, { "code": null, "e": 2871, "s": 2826, "text": "Finally, we can pass vectors to a classifier" }, { "code": null, "e": 3274, "s": 2871, "text": "from sklearn.linear_model import LogisticRegressionmodel = LogisticRegression(solver='newton-cg', max_iter=1000)model.fit(x_train_t, y_train)y_pred = model.predict(x_test_t)from sklearn.metrics import accuracy_scorefrom sklearn.metrics import classification_reportprint('Accuracy:%.2f%%' % (accuracy_score(y_test, y_pred)*100))print('Classification Report:')print(classification_report(y_test, y_pred))" }, { "code": null, "e": 3281, "s": 3274, "text": "Result" }, { "code": null, "e": 3355, "s": 3281, "text": "Accuracy: 52.8%Average Precision: 0.66Average Recall: 0.53Average f1: 0.5" }, { "code": null, "e": 3405, "s": 3355, "text": "To access all code, you can visit my github repo." }, { "code": null, "e": 3544, "s": 3405, "text": "Unlike word2vec, doc2vec computes sentence/ document vector on the fly. In other word, it takes time to get vector during prediction time." }, { "code": null, "e": 3619, "s": 3544, "text": "From Mikolov et al. experiment, PV-DM is consistently better than PV-DBOW." }, { "code": null, "e": 3691, "s": 3619, "text": "In PV-DM approach, concatenation way is often better than sum/ average." }, { "code": null, "e": 3776, "s": 3691, "text": "Mikolov Tomas, Le Quoc. 2014. Distributed Representations of Sentences and Documents" } ]
Can't find my.ini in MySQL directory?
The my.ini is in hidden folder of program data. First go to C: drive and then hidden folder of program data. From that, move to the MySQL version directory. Here is the snapshot of the C: drive − Click on C drive. The snapshot is as follows. Here, you can see the Program Data folder − Now go to MySQL under Program Data folder. The snapshot is as follows − Go to MySQL version. The snapshot is as follows − Note − Here, we are using MySQL version 8.0.12 Here is the my.ini file. In order to reach the location, you can also use the following command − mysql> select @@datadir; The following is the output − +---------------------------------------------+ | @@datadir | +---------------------------------------------+ | C:\ProgramData\MySQL\MySQL Server 8.0\Data\ | +---------------------------------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1219, "s": 1062, "text": "The my.ini is in hidden folder of program data. First go to C: drive and then hidden folder of program data. From that, move to the MySQL version directory." }, { "code": null, "e": 1258, "s": 1219, "text": "Here is the snapshot of the C: drive −" }, { "code": null, "e": 1348, "s": 1258, "text": "Click on C drive. The snapshot is as follows. Here, you can see the Program Data folder −" }, { "code": null, "e": 1420, "s": 1348, "text": "Now go to MySQL under Program Data folder. The snapshot is as follows −" }, { "code": null, "e": 1470, "s": 1420, "text": "Go to MySQL version. The snapshot is as follows −" }, { "code": null, "e": 1517, "s": 1470, "text": "Note − Here, we are using MySQL version 8.0.12" }, { "code": null, "e": 1542, "s": 1517, "text": "Here is the my.ini file." }, { "code": null, "e": 1615, "s": 1542, "text": "In order to reach the location, you can also use the following command −" }, { "code": null, "e": 1640, "s": 1615, "text": "mysql> select @@datadir;" }, { "code": null, "e": 1670, "s": 1640, "text": "The following is the output −" }, { "code": null, "e": 1934, "s": 1670, "text": "+---------------------------------------------+\n| @@datadir |\n+---------------------------------------------+\n| C:\\ProgramData\\MySQL\\MySQL Server 8.0\\Data\\ |\n+---------------------------------------------+\n1 row in set (0.00 sec)" } ]
iOS - In-App Purchase
In-App purchase is used to purchase additional content or upgrade features with respect to an application. Step 1 − In iTunes connect, ensure that you have a unique App ID and when we create the application update with the bundle ID and code signing in Xcode with corresponding provisioning profile. Step 2 − Create a new application and update application information. You can know more about this in apple's Add new apps documentation. Step 3 − Add a new product for in-app purchase in Manage In-App Purchase of your application's page. Step 4 − Ensure you setup the bank details for your application. This needs to be setup for In-App purchase to work. Also, create a test user account using Manage Users option in iTunes connect page of your app. Step 5 − The next steps are related to handling code and creating UI for our In-App purchase. Step 6 − Create a single view application and enter the bundle identifier is the identifier specified in iTunes connect. Step 7 − Update the ViewController.xib as shown below − Step 8 − Create IBOutlets for the three labels and the button naming them as productTitleLabel, productDescriptionLabel, productPriceLabel and purchaseButton respectively. Step 9 − Select your project file, then select targets and then add StoreKit.framework. Step 10 − Update ViewController.h as follows − #import <UIKit/UIKit.h> #import <StoreKit/StoreKit.h> @interface ViewController : UIViewController< SKProductsRequestDelegate,SKPaymentTransactionObserver> { SKProductsRequest *productsRequest; NSArray *validProducts; UIActivityIndicatorView *activityIndicatorView; IBOutlet UILabel *productTitleLabel; IBOutlet UILabel *productDescriptionLabel; IBOutlet UILabel *productPriceLabel; IBOutlet UIButton *purchaseButton; } - (void)fetchAvailableProducts; - (BOOL)canMakePurchases; - (void)purchaseMyProduct:(SKProduct*)product; - (IBAction)purchase:(id)sender; @end Step 11 − Update ViewController.m as follows − #import "ViewController.h" #define kTutorialPointProductID @"com.tutorialPoints.testApp.testProduct" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Adding activity indicator activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; activityIndicatorView.center = self.view.center; [activityIndicatorView hidesWhenStopped]; [self.view addSubview:activityIndicatorView]; [activityIndicatorView startAnimating]; //Hide purchase button initially purchaseButton.hidden = YES; [self fetchAvailableProducts]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(void)fetchAvailableProducts { NSSet *productIdentifiers = [NSSet setWithObjects:kTutorialPointProductID,nil]; productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers]; productsRequest.delegate = self; [productsRequest start]; } - (BOOL)canMakePurchases { return [SKPaymentQueue canMakePayments]; } - (void)purchaseMyProduct:(SKProduct*)product { if ([self canMakePurchases]) { SKPayment *payment = [SKPayment paymentWithProduct:product]; [[SKPaymentQueue defaultQueue] addTransactionObserver:self]; [[SKPaymentQueue defaultQueue] addPayment:payment]; } else { UIAlertView *alertView = [[UIAlertView alloc]initWithTitle: @"Purchases are disabled in your device" message:nil delegate: self cancelButtonTitle:@"Ok" otherButtonTitles: nil]; [alertView show]; } } -(IBAction)purchase:(id)sender { [self purchaseMyProduct:[validProducts objectAtIndex:0]]; purchaseButton.enabled = NO; } #pragma mark StoreKit Delegate -(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions { for (SKPaymentTransaction *transaction in transactions) { switch (transaction.transactionState) { case SKPaymentTransactionStatePurchasing: NSLog(@"Purchasing"); break; case SKPaymentTransactionStatePurchased: if ([transaction.payment.productIdentifier isEqualToString:kTutorialPointProductID]) { NSLog(@"Purchased "); UIAlertView *alertView = [[UIAlertView alloc]initWithTitle: @"Purchase is completed succesfully" message:nil delegate: self cancelButtonTitle:@"Ok" otherButtonTitles: nil]; [alertView show]; } [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; break; case SKPaymentTransactionStateRestored: NSLog(@"Restored "); [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; break; case SKPaymentTransactionStateFailed: NSLog(@"Purchase failed "); break default: break; } } } -(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response { SKProduct *validProduct = nil; int count = [response.products count]; if (count>0) { validProducts = response.products; validProduct = [response.products objectAtIndex:0]; if ([validProduct.productIdentifier isEqualToString:kTutorialPointProductID]) { [productTitleLabel setText:[NSString stringWithFormat: @"Product Title: %@",validProduct.localizedTitle]]; [productDescriptionLabel setText:[NSString stringWithFormat: @"Product Desc: %@",validProduct.localizedDescription]]; [productPriceLabel setText:[NSString stringWithFormat: @"Product Price: %@",validProduct.price]]; } } else { UIAlertView *tmp = [[UIAlertView alloc] initWithTitle:@"Not Available" message:@"No products to purchase" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok", nil]; [tmp show]; } [activityIndicatorView stopAnimating]; purchaseButton.hidden = NO; } @end You have to update kTutorialPointProductID to the productID you have created for your In-App Purchase. You can add more than one product by updating the productIdentifiers's NSSet in fetchAvailableProducts. Similary, handle the purchase related actions for product IDs you add. When we run the application, we'll get the following output − Ensure you had logged out of your account in the settings screen. On clicking the Initiate Purchase, select Use Existing Apple ID. Enter your valid test account username and password. You will be shown the following alert in a few seconds. Once your product is purchased successfully, you will get the following alert. You can see relevant code for updating the application features where we show this alert. 23 Lectures 1.5 hours Ashish Sharma 9 Lectures 1 hours Abhilash Nelson 14 Lectures 1.5 hours Abhilash Nelson 15 Lectures 1.5 hours Abhilash Nelson 10 Lectures 1 hours Abhilash Nelson 69 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2198, "s": 2091, "text": "In-App purchase is used to purchase additional content or upgrade features with respect to an application." }, { "code": null, "e": 2391, "s": 2198, "text": "Step 1 − In iTunes connect, ensure that you have a unique App ID and when we create the application update with the bundle ID and code signing in Xcode with corresponding provisioning profile." }, { "code": null, "e": 2529, "s": 2391, "text": "Step 2 − Create a new application and update application information. You can know more about this in apple's Add new apps documentation." }, { "code": null, "e": 2630, "s": 2529, "text": "Step 3 − Add a new product for in-app purchase in Manage In-App Purchase of your application's page." }, { "code": null, "e": 2842, "s": 2630, "text": "Step 4 − Ensure you setup the bank details for your application. This needs to be setup for In-App purchase to work. Also, create a test user account using Manage Users option in iTunes connect page of your app." }, { "code": null, "e": 2936, "s": 2842, "text": "Step 5 − The next steps are related to handling code and creating UI for our In-App purchase." }, { "code": null, "e": 3057, "s": 2936, "text": "Step 6 − Create a single view application and enter the bundle identifier is the identifier specified in iTunes connect." }, { "code": null, "e": 3113, "s": 3057, "text": "Step 7 − Update the ViewController.xib as shown below −" }, { "code": null, "e": 3285, "s": 3113, "text": "Step 8 − Create IBOutlets for the three labels and the button naming them as productTitleLabel, productDescriptionLabel, productPriceLabel and purchaseButton respectively." }, { "code": null, "e": 3373, "s": 3285, "text": "Step 9 − Select your project file, then select targets and then add StoreKit.framework." }, { "code": null, "e": 3420, "s": 3373, "text": "Step 10 − Update ViewController.h as follows −" }, { "code": null, "e": 4007, "s": 3420, "text": "#import <UIKit/UIKit.h>\n#import <StoreKit/StoreKit.h>\n\n@interface ViewController : UIViewController<\nSKProductsRequestDelegate,SKPaymentTransactionObserver> {\n SKProductsRequest *productsRequest;\n NSArray *validProducts;\n UIActivityIndicatorView *activityIndicatorView;\n IBOutlet UILabel *productTitleLabel;\n IBOutlet UILabel *productDescriptionLabel;\n IBOutlet UILabel *productPriceLabel;\n IBOutlet UIButton *purchaseButton;\n}\n\n- (void)fetchAvailableProducts;\n- (BOOL)canMakePurchases;\n- (void)purchaseMyProduct:(SKProduct*)product;\n- (IBAction)purchase:(id)sender;\n\n@end" }, { "code": null, "e": 4054, "s": 4007, "text": "Step 11 − Update ViewController.m as follows −" }, { "code": null, "e": 8260, "s": 4054, "text": "#import \"ViewController.h\"\n#define kTutorialPointProductID \n@\"com.tutorialPoints.testApp.testProduct\"\n\n@interface ViewController ()\n@end\n\n@implementation ViewController\n\n- (void)viewDidLoad {\n [super viewDidLoad];\n \n // Adding activity indicator\n activityIndicatorView = [[UIActivityIndicatorView alloc]\n initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];\n activityIndicatorView.center = self.view.center;\n [activityIndicatorView hidesWhenStopped];\n [self.view addSubview:activityIndicatorView];\n [activityIndicatorView startAnimating];\n \n //Hide purchase button initially\n purchaseButton.hidden = YES;\n [self fetchAvailableProducts];\n}\n\n- (void)didReceiveMemoryWarning {\n [super didReceiveMemoryWarning];\n // Dispose of any resources that can be recreated.\n}\n\n-(void)fetchAvailableProducts {\n NSSet *productIdentifiers = [NSSet \n setWithObjects:kTutorialPointProductID,nil];\n productsRequest = [[SKProductsRequest alloc] \n initWithProductIdentifiers:productIdentifiers];\n productsRequest.delegate = self;\n [productsRequest start];\n}\n\n- (BOOL)canMakePurchases {\n return [SKPaymentQueue canMakePayments];\n}\n\n- (void)purchaseMyProduct:(SKProduct*)product {\n if ([self canMakePurchases]) {\n SKPayment *payment = [SKPayment paymentWithProduct:product];\n [[SKPaymentQueue defaultQueue] addTransactionObserver:self];\n [[SKPaymentQueue defaultQueue] addPayment:payment];\n } else {\n UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:\n @\"Purchases are disabled in your device\" message:nil delegate:\n self cancelButtonTitle:@\"Ok\" otherButtonTitles: nil];\n [alertView show];\n }\n}\n-(IBAction)purchase:(id)sender {\n [self purchaseMyProduct:[validProducts objectAtIndex:0]];\n purchaseButton.enabled = NO; \n}\n\n#pragma mark StoreKit Delegate\n\n-(void)paymentQueue:(SKPaymentQueue *)queue \nupdatedTransactions:(NSArray *)transactions {\n for (SKPaymentTransaction *transaction in transactions) {\n switch (transaction.transactionState) {\n case SKPaymentTransactionStatePurchasing:\n NSLog(@\"Purchasing\");\n break;\n \n case SKPaymentTransactionStatePurchased:\n if ([transaction.payment.productIdentifier \n isEqualToString:kTutorialPointProductID]) {\n NSLog(@\"Purchased \");\n UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:\n @\"Purchase is completed succesfully\" message:nil delegate:\n self cancelButtonTitle:@\"Ok\" otherButtonTitles: nil];\n [alertView show];\n }\n [[SKPaymentQueue defaultQueue] finishTransaction:transaction];\n break;\n \n case SKPaymentTransactionStateRestored:\n NSLog(@\"Restored \");\n [[SKPaymentQueue defaultQueue] finishTransaction:transaction];\n break;\n \n case SKPaymentTransactionStateFailed:\n NSLog(@\"Purchase failed \");\n break\n default:\n break;\n }\n }\n}\n\n-(void)productsRequest:(SKProductsRequest *)request \ndidReceiveResponse:(SKProductsResponse *)response {\n SKProduct *validProduct = nil;\n int count = [response.products count];\n \n if (count>0) {\n validProducts = response.products;\n validProduct = [response.products objectAtIndex:0];\n \n if ([validProduct.productIdentifier \n isEqualToString:kTutorialPointProductID]) {\n [productTitleLabel setText:[NSString stringWithFormat:\n @\"Product Title: %@\",validProduct.localizedTitle]];\n [productDescriptionLabel setText:[NSString stringWithFormat:\n @\"Product Desc: %@\",validProduct.localizedDescription]];\n [productPriceLabel setText:[NSString stringWithFormat:\n @\"Product Price: %@\",validProduct.price]];\n }\n } else {\n UIAlertView *tmp = [[UIAlertView alloc]\n initWithTitle:@\"Not Available\"\n message:@\"No products to purchase\"\n delegate:self\n cancelButtonTitle:nil\n otherButtonTitles:@\"Ok\", nil];\n [tmp show];\n }\n \n [activityIndicatorView stopAnimating];\n purchaseButton.hidden = NO;\n}\n@end" }, { "code": null, "e": 8538, "s": 8260, "text": "You have to update kTutorialPointProductID to the productID you have created for your In-App Purchase. You can add more than one product by updating the productIdentifiers's NSSet in fetchAvailableProducts. Similary, handle the purchase related actions for product IDs you add." }, { "code": null, "e": 8600, "s": 8538, "text": "When we run the application, we'll get the following output −" }, { "code": null, "e": 8840, "s": 8600, "text": "Ensure you had logged out of your account in the settings screen. On clicking the Initiate Purchase, select Use Existing Apple ID. Enter your valid test account username and password. You will be shown the following alert in a few seconds." }, { "code": null, "e": 9009, "s": 8840, "text": "Once your product is purchased successfully, you will get the following alert. You can see relevant code for updating the application features where we show this alert." }, { "code": null, "e": 9044, "s": 9009, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9059, "s": 9044, "text": " Ashish Sharma" }, { "code": null, "e": 9091, "s": 9059, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 9108, "s": 9091, "text": " Abhilash Nelson" }, { "code": null, "e": 9143, "s": 9108, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9160, "s": 9143, "text": " Abhilash Nelson" }, { "code": null, "e": 9195, "s": 9160, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9212, "s": 9195, "text": " Abhilash Nelson" }, { "code": null, "e": 9245, "s": 9212, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 9262, "s": 9245, "text": " Abhilash Nelson" }, { "code": null, "e": 9295, "s": 9262, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 9312, "s": 9295, "text": " Frahaan Hussain" }, { "code": null, "e": 9319, "s": 9312, "text": " Print" }, { "code": null, "e": 9330, "s": 9319, "text": " Add Notes" } ]
Method Overriding in Dart - GeeksforGeeks
20 Jul, 2020 Method overriding occurs in dart when a child class tries to override the parent class’s method. When a child class extends a parent class, it gets full access to the methods of the parent class and thus it overrides the methods of the parent class. It is achieved by re-defining the same method present in the parent class. This method is helpful when you have to perform different functions for a different child class, so we can simply re-define the content by overriding it. Important Points: A method can be overridden only in the child class, not in the parent class itself.Both the methods defined in the child and the parent class should be the exact copy, from name to argument list except the content present inside the method i.e. it can and can’t be the same.A method declared final or static inside the parent class can’t be overridden by the child class.Constructors of the parent class can’t be inherited, so they can’t be overridden by the child class. A method can be overridden only in the child class, not in the parent class itself. Both the methods defined in the child and the parent class should be the exact copy, from name to argument list except the content present inside the method i.e. it can and can’t be the same. A method declared final or static inside the parent class can’t be overridden by the child class. Constructors of the parent class can’t be inherited, so they can’t be overridden by the child class. Example 1: Simple case of method overriding. Dart // Dart Program to illustrate the // method overriding conceptclass SuperGeek { // Creating a method void show(){ print("This is class SuperGeek."); }} class SubGeek extends SuperGeek { // Overriding show method void show(){ print("This is class SubGeek child of SuperGeek."); }} void main() { // Creating objects //of both the classes SuperGeek geek1 = new SuperGeek(); SubGeek geek2 = new SubGeek(); // Calling same function // from both the classes // object to show method overriding geek1.show(); geek2.show();} Output: This is class SuperGeek. This is class SubGeek child of SuperGeek. Example 2: When there is more than one child class. Dart // Dart Program to illustrate the // method overriding concept class SuperGeek { // Creating a method void show(){ print("This is class SuperGeek."); }} class SubGeek1 extends SuperGeek { // Overriding show method void show(){ print("This is class SubGeek1 child of SuperGeek."); }} class SubGeek2 extends SuperGeek { // Overriding show method void show(){ print("This is class SubGeek2 child of SuperGeek."); }} void main() { // Creating objects of both the classes SuperGeek geek1 = new SuperGeek(); SubGeek1 geek2 = new SubGeek1(); SubGeek2 geek3 = new SubGeek2(); // Calling same function // from both the classes // object to show method // overriding geek1.show(); geek2.show(); geek3.show();} Output: This is class SuperGeek. This is class SubGeek1 child of SuperGeek. This is class SubGeek2 child of SuperGeek. Dart-OOPs Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Dart Tutorial Flutter - Checkbox Widget ListView Class in Flutter Flutter - Stack Widget Flutter - BoxShadow Widget What is widgets in Flutter? How to Append or Concatenate Strings in Dart? Flutter - Carousel Slider
[ { "code": null, "e": 23956, "s": 23928, "text": "\n20 Jul, 2020" }, { "code": null, "e": 24281, "s": 23956, "text": "Method overriding occurs in dart when a child class tries to override the parent class’s method. When a child class extends a parent class, it gets full access to the methods of the parent class and thus it overrides the methods of the parent class. It is achieved by re-defining the same method present in the parent class." }, { "code": null, "e": 24435, "s": 24281, "text": "This method is helpful when you have to perform different functions for a different child class, so we can simply re-define the content by overriding it." }, { "code": null, "e": 24454, "s": 24435, "text": "Important Points: " }, { "code": null, "e": 24926, "s": 24454, "text": "A method can be overridden only in the child class, not in the parent class itself.Both the methods defined in the child and the parent class should be the exact copy, from name to argument list except the content present inside the method i.e. it can and can’t be the same.A method declared final or static inside the parent class can’t be overridden by the child class.Constructors of the parent class can’t be inherited, so they can’t be overridden by the child class." }, { "code": null, "e": 25010, "s": 24926, "text": "A method can be overridden only in the child class, not in the parent class itself." }, { "code": null, "e": 25202, "s": 25010, "text": "Both the methods defined in the child and the parent class should be the exact copy, from name to argument list except the content present inside the method i.e. it can and can’t be the same." }, { "code": null, "e": 25300, "s": 25202, "text": "A method declared final or static inside the parent class can’t be overridden by the child class." }, { "code": null, "e": 25401, "s": 25300, "text": "Constructors of the parent class can’t be inherited, so they can’t be overridden by the child class." }, { "code": null, "e": 25448, "s": 25401, "text": "Example 1: Simple case of method overriding. " }, { "code": null, "e": 25453, "s": 25448, "text": "Dart" }, { "code": "// Dart Program to illustrate the // method overriding conceptclass SuperGeek { // Creating a method void show(){ print(\"This is class SuperGeek.\"); }} class SubGeek extends SuperGeek { // Overriding show method void show(){ print(\"This is class SubGeek child of SuperGeek.\"); }} void main() { // Creating objects //of both the classes SuperGeek geek1 = new SuperGeek(); SubGeek geek2 = new SubGeek(); // Calling same function // from both the classes // object to show method overriding geek1.show(); geek2.show();}", "e": 26007, "s": 25453, "text": null }, { "code": null, "e": 26018, "s": 26009, "text": "Output: " }, { "code": null, "e": 26086, "s": 26018, "text": "This is class SuperGeek.\nThis is class SubGeek child of SuperGeek.\n" }, { "code": null, "e": 26140, "s": 26086, "text": "Example 2: When there is more than one child class. " }, { "code": null, "e": 26145, "s": 26140, "text": "Dart" }, { "code": "// Dart Program to illustrate the // method overriding concept class SuperGeek { // Creating a method void show(){ print(\"This is class SuperGeek.\"); }} class SubGeek1 extends SuperGeek { // Overriding show method void show(){ print(\"This is class SubGeek1 child of SuperGeek.\"); }} class SubGeek2 extends SuperGeek { // Overriding show method void show(){ print(\"This is class SubGeek2 child of SuperGeek.\"); }} void main() { // Creating objects of both the classes SuperGeek geek1 = new SuperGeek(); SubGeek1 geek2 = new SubGeek1(); SubGeek2 geek3 = new SubGeek2(); // Calling same function // from both the classes // object to show method // overriding geek1.show(); geek2.show(); geek3.show();}", "e": 26900, "s": 26145, "text": null }, { "code": null, "e": 26911, "s": 26902, "text": "Output: " }, { "code": null, "e": 27023, "s": 26911, "text": "This is class SuperGeek.\nThis is class SubGeek1 child of SuperGeek.\nThis is class SubGeek2 child of SuperGeek.\n" }, { "code": null, "e": 27033, "s": 27023, "text": "Dart-OOPs" }, { "code": null, "e": 27038, "s": 27033, "text": "Dart" }, { "code": null, "e": 27136, "s": 27038, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27145, "s": 27136, "text": "Comments" }, { "code": null, "e": 27158, "s": 27145, "text": "Old Comments" }, { "code": null, "e": 27190, "s": 27158, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 27229, "s": 27190, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 27243, "s": 27229, "text": "Dart Tutorial" }, { "code": null, "e": 27269, "s": 27243, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 27295, "s": 27269, "text": "ListView Class in Flutter" }, { "code": null, "e": 27318, "s": 27295, "text": "Flutter - Stack Widget" }, { "code": null, "e": 27345, "s": 27318, "text": "Flutter - BoxShadow Widget" }, { "code": null, "e": 27373, "s": 27345, "text": "What is widgets in Flutter?" }, { "code": null, "e": 27419, "s": 27373, "text": "How to Append or Concatenate Strings in Dart?" } ]
Counting elements in two arrays | Practice | GeeksforGeeks
Given two unsorted arrays arr1[] and arr2[]. They may contain duplicates. For each element in arr1[] count elements less than or equal to it in array arr2[]. Example 1: Input: m = 6, n = 6 arr1[] = {1,2,3,4,7,9} arr2[] = {0,1,2,1,1,4} Output: 4 5 5 6 6 6 Explanation: Number of elements less than or equal to 1, 2, 3, 4, 7, and 9 in the second array are respectively 4,5,5,6,6,6 Example 2: Input: m = 5, n = 7 arr1[] = {4 8 7 5 1} arr2[] = {4,48,3,0,1,1,5} Output: 5 6 6 6 3 Your Task : Complete the function countEleLessThanOrEqual() that takes two array arr1[], arr2[], m, and n as input and returns an array containing the required results(the count of elements less than or equal to it in arr2 for each element in arr1 where ith output represents the count for ith element in arr1.) Expected Time Complexity: O((m + n) * log n). Expected Auxiliary Space: O(1). Constraints: 1<=m,n<=10^5 1<=arr1[i],arr2[j]<=10^5 0 vikasrajpoot4791 day ago //using binary search class Solution{ public: vector<int> countEleLessThanOrEqual(int arr1[], int arr2[], int m, int n) { sort(arr2,arr2+n); vector<int>sol; for(int i=0;i<m;i++) { int k=arr1[i]; int s=0; int e=n-1; int ans=0; while(s<=e) { int mid=s+(e-s)/2; if(arr2[mid]<=k) { ans=mid+1; s=mid+1; } else{ e=mid-1; } } sol.push_back(ans); } return sol; }}; 0 ajay7yadav956 days ago //hy javaScript lovers ----------------→ A7 arr2.sort((x,y)=>x-y); for(let i=0; i<arr1.length; i++){ let x = arr1[i]; let l=0; let r=arr2.length-1; let count = 0; while(l<=r){ let mid = parseInt(l+(r-l)/2); if(arr2[mid]<= x){ count = mid+1; l = mid+1; } if(arr2[mid]> x){ r = mid -1; } } arr1[i] = count; } return arr1; 0 tanashah1 week ago int counforfirst(int arr[],int low,int high ,int x){ while(low<=high){ int mid=(low+high)/2; if(arr[mid]<=x){ low=mid+1; } else{ high=mid-1; } } return high; //nichese element hai uska index print karvare rahe hai simple } vector<int> countEleLessThanOrEqual(int arr1[], int arr2[], int m, int n) { //Your code goes here //O(n^2) soln 16-02 vector<int>v; sort(arr2,arr2+n); for(int i=0;i<m;i++){ int count=counforfirst(arr2,0,n-1,arr1[i]); v.push_back(count+1); } return v; } 0 hr15171517hr1 week ago //JAVA USING BS class Solution { public static ArrayList<Integer> countEleLessThanOrEqual(int arr1[], int arr2[], int m, int n) { ArrayList<Integer> al = new ArrayList<>(); Arrays.sort(arr2); for (int i = 0; i < m; i++) { int x = ceiling(arr2, arr1[i]); if(x==-1){ al.add(n); } else{ al.add(x); } } return al; } static int ceiling(int arr[], int x) { int res = -1; int low = 0, high = arr.length - 1; while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] > x) { res = mid; high = mid - 1; } else if (arr[mid] <= x) { low = mid + 1; } } return res; } } 0 itsmeshahid1 week ago int bs(int arr[], int low, int high, int x){ while(low<=high){ int mid=(low+high)/2; if(arr[mid]<=x){ low=mid+1; } else{ high=mid-1; } } return high; } vector<int> countEleLessThanOrEqual(int arr1[], int arr2[], int m, int n) { sort(arr2, arr2+n); vector<int>ans; for(int i=0; i<m; i++){ int index=bs(arr2, 0, n-1, arr1[i]); ans.push_back(index+1); } return ans; } 0 itsmeshahid This comment was deleted. 0 skjha919992 weeks ago ArrayList<Integer>a=new ArrayList<>(); Set<Integer>h=new LinkedHashSet<>(); for(int i=0;i<m;i++) { h.add(arr1[i]); } //System.out.print(h); Iterator iterator = h.iterator(); while(iterator.hasNext()) { int i1=(Integer)iterator.next(); int count=0; for(int i=0;i<n;i++) { if(arr2[i]<=i1) count++; } a.add(count); } return a; } 0 harshilrpanchal19983 weeks ago java code ArrayList<Integer> list = new ArrayList<>(); Arrays.sort(arr2); int count =0; for (int i=0 ; i < arr1.length ; i++){ count =0; for (int j=0 ; j < arr2.length ; j++){ if(arr1[i] >= arr2[j]){ count++; } } list.add(count); } return list; 0 tanishkaashi5671 month ago Time limit is exceeding if we use an array to return the result. (I know they asked us to solve it in O(1) space complexity. But the driver code is taking list as an output. What to do about that? Otherwise my code is working fine. Just not able to submit it due to space complexity issue!! please fix it. +1 guruprasadnb14021 month ago vector<int> countEleLessThanOrEqual(int arr1[], int arr2[], int m, int n) { //Your code goes here vector<int>ans; sort(arr2,arr2+n); for(int i=0;i<m;++i){ auto count=upper_bound(arr2,arr2+n,arr1[i]); ans.push_back(count-arr2); } return ans; } 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": 396, "s": 238, "text": "Given two unsorted arrays arr1[] and arr2[]. They may contain duplicates. For each element in arr1[] count elements less than or equal to it in array arr2[]." }, { "code": null, "e": 407, "s": 396, "text": "Example 1:" }, { "code": null, "e": 618, "s": 407, "text": "Input:\nm = 6, n = 6\narr1[] = {1,2,3,4,7,9}\narr2[] = {0,1,2,1,1,4}\nOutput: 4 5 5 6 6 6\nExplanation: Number of elements less than\nor equal to 1, 2, 3, 4, 7, and 9 in the\nsecond array are respectively 4,5,5,6,6,6\n" }, { "code": null, "e": 629, "s": 618, "text": "Example 2:" }, { "code": null, "e": 714, "s": 629, "text": "Input:\nm = 5, n = 7\narr1[] = {4 8 7 5 1}\narr2[] = {4,48,3,0,1,1,5}\nOutput: 5 6 6 6 3" }, { "code": null, "e": 1027, "s": 714, "text": "Your Task :\nComplete the function countEleLessThanOrEqual() that takes two array arr1[], arr2[], m, and n as input and returns an array containing the required results(the count of elements less than or equal to it in arr2 for each element in arr1 where ith output represents the count for ith element in arr1.)" }, { "code": null, "e": 1105, "s": 1027, "text": "Expected Time Complexity: O((m + n) * log n).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1156, "s": 1105, "text": "Constraints:\n1<=m,n<=10^5\n1<=arr1[i],arr2[j]<=10^5" }, { "code": null, "e": 1158, "s": 1156, "text": "0" }, { "code": null, "e": 1183, "s": 1158, "text": "vikasrajpoot4791 day ago" }, { "code": null, "e": 1205, "s": 1183, "text": "//using binary search" }, { "code": null, "e": 1783, "s": 1205, "text": "class Solution{ public: vector<int> countEleLessThanOrEqual(int arr1[], int arr2[], int m, int n) { sort(arr2,arr2+n); vector<int>sol; for(int i=0;i<m;i++) { int k=arr1[i]; int s=0; int e=n-1; int ans=0; while(s<=e) { int mid=s+(e-s)/2; if(arr2[mid]<=k) { ans=mid+1; s=mid+1; } else{ e=mid-1; } } sol.push_back(ans); } return sol; }};" }, { "code": null, "e": 1785, "s": 1783, "text": "0" }, { "code": null, "e": 1808, "s": 1785, "text": "ajay7yadav956 days ago" }, { "code": null, "e": 1852, "s": 1808, "text": "//hy javaScript lovers ----------------→ A7" }, { "code": null, "e": 2342, "s": 1854, "text": "arr2.sort((x,y)=>x-y); for(let i=0; i<arr1.length; i++){ let x = arr1[i]; let l=0; let r=arr2.length-1; let count = 0; while(l<=r){ let mid = parseInt(l+(r-l)/2); if(arr2[mid]<= x){ count = mid+1; l = mid+1; } if(arr2[mid]> x){ r = mid -1; } } arr1[i] = count; } return arr1;" }, { "code": null, "e": 2344, "s": 2342, "text": "0" }, { "code": null, "e": 2363, "s": 2344, "text": "tanashah1 week ago" }, { "code": null, "e": 3114, "s": 2363, "text": " int counforfirst(int arr[],int low,int high ,int x){\n while(low<=high){\n int mid=(low+high)/2;\n \n if(arr[mid]<=x){\n low=mid+1;\n }\n else{\n high=mid-1;\n }\n }\n return high; //nichese element hai uska index print karvare rahe hai simple\n \n }\n vector<int> countEleLessThanOrEqual(int arr1[], int arr2[], \n int m, int n)\n {\n //Your code goes here\n //O(n^2) soln 16-02\n vector<int>v;\n sort(arr2,arr2+n);\n for(int i=0;i<m;i++){\n \n int count=counforfirst(arr2,0,n-1,arr1[i]);\n v.push_back(count+1);\n }\n return v;\n }" }, { "code": null, "e": 3116, "s": 3114, "text": "0" }, { "code": null, "e": 3139, "s": 3116, "text": "hr15171517hr1 week ago" }, { "code": null, "e": 3995, "s": 3139, "text": "//JAVA USING BS\nclass Solution\n{\n public static ArrayList<Integer> countEleLessThanOrEqual(int arr1[], int arr2[], int m, int n)\n {\n ArrayList<Integer> al = new ArrayList<>();\n Arrays.sort(arr2);\n for (int i = 0; i < m; i++) {\n int x = ceiling(arr2, arr1[i]);\n if(x==-1){\n al.add(n);\n }\n else{\n al.add(x);\n }\n }\n return al;\n }\n static int ceiling(int arr[], int x) {\n int res = -1;\n int low = 0, high = arr.length - 1;\n while (low <= high) {\n int mid = low + (high - low) / 2;\n if (arr[mid] > x) {\n res = mid;\n high = mid - 1;\n } else if (arr[mid] <= x) {\n low = mid + 1;\n }\n }\n return res;\n }\n}\n" }, { "code": null, "e": 3997, "s": 3995, "text": "0" }, { "code": null, "e": 4019, "s": 3997, "text": "itsmeshahid1 week ago" }, { "code": null, "e": 4696, "s": 4019, "text": "int bs(int arr[], int low, int high, int x){ while(low<=high){ int mid=(low+high)/2; if(arr[mid]<=x){ low=mid+1; } else{ high=mid-1; } } return high; } vector<int> countEleLessThanOrEqual(int arr1[], int arr2[], int m, int n) { sort(arr2, arr2+n); vector<int>ans; for(int i=0; i<m; i++){ int index=bs(arr2, 0, n-1, arr1[i]); ans.push_back(index+1); } return ans; }" }, { "code": null, "e": 4698, "s": 4696, "text": "0" }, { "code": null, "e": 4710, "s": 4698, "text": "itsmeshahid" }, { "code": null, "e": 4736, "s": 4710, "text": "This comment was deleted." }, { "code": null, "e": 4738, "s": 4736, "text": "0" }, { "code": null, "e": 4760, "s": 4738, "text": "skjha919992 weeks ago" }, { "code": null, "e": 5199, "s": 4760, "text": "ArrayList<Integer>a=new ArrayList<>(); Set<Integer>h=new LinkedHashSet<>(); for(int i=0;i<m;i++) { h.add(arr1[i]); } //System.out.print(h); Iterator iterator = h.iterator(); while(iterator.hasNext()) { int i1=(Integer)iterator.next(); int count=0; for(int i=0;i<n;i++) { if(arr2[i]<=i1) count++; } a.add(count); } return a; }" }, { "code": null, "e": 5201, "s": 5199, "text": "0" }, { "code": null, "e": 5232, "s": 5201, "text": "harshilrpanchal19983 weeks ago" }, { "code": null, "e": 5242, "s": 5232, "text": "java code" }, { "code": null, "e": 5289, "s": 5244, "text": "ArrayList<Integer> list = new ArrayList<>();" }, { "code": null, "e": 5457, "s": 5289, "text": " Arrays.sort(arr2); int count =0; for (int i=0 ; i < arr1.length ; i++){ count =0; for (int j=0 ; j < arr2.length ; j++){" }, { "code": null, "e": 5539, "s": 5457, "text": " if(arr1[i] >= arr2[j]){ count++; }" }, { "code": null, "e": 5616, "s": 5539, "text": " } list.add(count); } return list;" }, { "code": null, "e": 5618, "s": 5616, "text": "0" }, { "code": null, "e": 5645, "s": 5618, "text": "tanishkaashi5671 month ago" }, { "code": null, "e": 5951, "s": 5645, "text": "Time limit is exceeding if we use an array to return the result. (I know they asked us to solve it in O(1) space complexity. But the driver code is taking list as an output. What to do about that? Otherwise my code is working fine. Just not able to submit it due to space complexity issue!! please fix it." }, { "code": null, "e": 5954, "s": 5951, "text": "+1" }, { "code": null, "e": 5982, "s": 5954, "text": "guruprasadnb14021 month ago" }, { "code": null, "e": 6285, "s": 5982, "text": "vector<int> countEleLessThanOrEqual(int arr1[], int arr2[], int m, int n) { //Your code goes here vector<int>ans; sort(arr2,arr2+n); for(int i=0;i<m;++i){ auto count=upper_bound(arr2,arr2+n,arr1[i]); ans.push_back(count-arr2); } return ans; }" }, { "code": null, "e": 6431, "s": 6285, "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": 6467, "s": 6431, "text": " Login to access your submissions. " }, { "code": null, "e": 6477, "s": 6467, "text": "\nProblem\n" }, { "code": null, "e": 6487, "s": 6477, "text": "\nContest\n" }, { "code": null, "e": 6550, "s": 6487, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6698, "s": 6550, "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": 6906, "s": 6698, "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": 7012, "s": 6906, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
CNN-LSTM-Based Models for Multiple Parallel Input and Multi-Step Forecast | by Halil Ertan | Towards Data Science
Time series forecasting is a very popular field of machine learning. The reason behind this is the widespread usage of time series in daily life in almost every domain. Going into details for time series forecasting, we encounter lots of different kinds of sub-fields and approaches. In this writing, I will focus on a specific subdomain that is performing multi-step forecasts by receiving multiple parallel time series, and also mention basic key points that should be taken into consideration in time series forecasting. Note that forecasting models differ from predictive models at various points. Let's think about lots of network devices spread over a large geography, and traffic flows through these devices continuously. Another example might be about lots of different temperature devices which measure the temperature of the weather in different locations continuously or another one might be to calculate the energy consumption of numerous devices in a system. We can just extend these kinds of examples easily. The goal is simple; forecast the next multiple time steps; this corresponds to forecasting traffic value, temperature, or the energy consumption of many devices respectively in our case. The first thing that comes to mind is certainly modeling each device separately. I think we will probably get the highest forecast results. What about if there are more than 100 different devices or even more? That means designing 100 different models. It is not much applicable considering the deploying, monitoring, and maintenance costs. Therefore, we aim to cover the entire problem with just a single model. I think it is still a very popular and searching field of time series forecasting, although time series forecasting has been on the table for a long time. I encounter lots of different academic research in this field. This problem might also be defined as seq2seq prediction. In particular, it is a very common case in speech recognition and translations. LSTM is very convenient for these kinds of problems. CNN can also be considered as another type of neural network and is commonly used in image processing tasks. Typically, it is used in feature extraction and time series forecasting as well. I will mention the appliance of LSTM and CNN for time series forecasting in multiple parallel inputs and multi-step forecasting cases. Explanation of LSTM and CNN is simply beyond the scope of the writing. To make it more clear, I depict a simple data example below. It is an example of forecasting traffic values of 3 different devices for the next 2 hours by looking at the previous 3 hours time slots. In this writing, I will utilize a data set consisting of a CPU usage of 288 different servers within 15 minutes time interval. For simplicity, I will narrow down the scope into 3 servers. Pre-modelling is very critical in neural network implementations. You mostly can not simply feed the neural network with raw data directly, a simple transformation is needed. However, we should apply a few more additional steps to the raw data before the transformation. The following is for pivoting the raw data in our case. df_cpu_pivot = pd.pivot_table(df, values=’CPUUSED’, index=[‘DATETIME’], columns=[‘ID’]) The following is for interpolating the missing values in the data set. Imputing null values in time series is very crucial on its own, and a challenging task as well. We don’t have many null values in this data set and imputing null values is beyond the scope of this writing, therefore I perform a simple implementation. for i in range(0, len(df_cpu_pivot.columns)): df_cpu_pivot.iloc[:,i].interpolate(inplace = True) The first thing before passing into the modeling phase, at the very beginning of the data preprocessing step for time series forecasting is plotting the time series in my opinion. Let's see what tells the data to us. As I mentioned before, I select only 3 different servers for simplicity. As it can be seen, all of them follow very similar patterns in different scales. import plotlyimport plotly.express as pximport plotly.graph_objects as godf_cpu_pivot.reset_index(inplace=True)df_cpu_pivot['DATETIME'] = pd.to_datetime(df_cpu_pivot['DATETIME'])trace1 = go.Scatter( x = df_cpu_pivot[‘DATETIME’], y = df_cpu_pivot[‘HSSFE-hssahlk01CPU-0’], mode = ‘lines’, name = ‘cpu_1’)trace2 = go.Scatter( x = df_cpu_pivot[‘DATETIME’], y = df_cpu_pivot[‘HSSFE-hssumrk03CPU-29’], mode = ‘lines’, name = ‘cpu_2’)trace3 = go.Scatter( x = df_cpu_pivot[‘DATETIME’], y = df_cpu_pivot[‘HSSFE-hssumrk03CPU-4’], mode = ‘lines’, name = ‘cpu_3’)layout = go.Layout( title = “CPU Usage”, xaxis = {‘title’ : “Date”}, yaxis = {‘title’ : “Cpu Usage”})fig = go.Figure(data=[trace1, trace2, trace3], layout=layout)fig.show() The next step is to split the data set into train and test sets. It is a bit different in time series from conventional machine learning implementations. We can intuitively determine a split date for separating the data set. from datetime import datetimetrain_test_split = datetime.strptime(‘20.04.2020 00:00:00’, ‘%d.%m.%Y %H:%M:%S’)df_train = df_cpu_pivot.loc[df_cpu_pivot[‘DATETIME’] < train_test_split]df_test = df_cpu_pivot.loc[df_cpu_pivot[‘DATETIME’] >= train_test_split] We also normalize the data before feeding it into any neural network model because of its sensitivity. from sklearn.preprocessing import MinMaxScalercpu_list = [i for i in df_cpu_pivot.columns if i != ‘DATETIME’]scaler = MinMaxScaler()scaled_train = scaler.fit_transform(df_train[cpu_list])scaled_test = scaler.transform(df_test[cpu_list]) And the final stage is to transform both train and test set into an acceptable format for neural networks. The following method can be implemented to transform the data. It simply expects 2 parameters except for the sequence itself, which are time lag(steps of looking back), and forecasting range respectively. You can also take a look at TimeSeriesGenerator class defined in Keras to transform the data set. def split_sequence(sequence, look_back, forecast_horizon): X, y = list(), list() for i in range(len(sequence)): lag_end = i + look_back forecast_end = lag_end + forecast_horizon if forecast_end > len(sequence): break seq_x, seq_y = sequence[i:lag_end], sequence[lag_end:forecast_end] X.append(seq_x) y.append(seq_y) return np.array(X), np.array(y) An LSTM model expects data to have the shape; [samples, timesteps, features]. Similarly, CNN also expects 3D data as LSTMs. # Take into consideration last 6 hours, and perform forecasting for next 1 hourLOOK_BACK = 24FORECAST_RANGE = 4n_features = len(cpu_list)X_train, y_train = split_sequence(scaled_train, look_back=LOOK_BACK, forecast_horizon=FORECAST_RANGE)X_test, y_test = split_sequence(scaled_test, look_back=LOOK_BACK, forecast_horizon=FORECAST_RANGE)print(X_train.shape)print(y_train.shape)print(X_test.shape)print(y_test.shape)(4869, 24, 3)(4869, 4, 3)(1029, 24, 3)(1029, 4, 3) Additional Notes I want to also mention additional pre-modeling steps for time series forecasting. These are not directly scope of the writing but worth knowing. Stationary is a very important issue for time series, most forecasting algorithm like ARIMA expects time series to be stationary. Stationary time series basically keep very similar mean, variance values over time and do not include seasonality and trend. To make time series stationary, the most straightforward method is to take the difference of subsequent values in the sequence. If variance fluctuates very much compared to mean, it also might be a good idea to take the log of the sequence to make it stationary. Unlike most of the other forecasting algorithms, LSTMs are capable of learning nonlinearities and long-term dependencies in the sequence. Thus, stationary is a less of concern of LSTMs. Nevertheless, it is a good practice to make the time series stationary and increase the performance of LSTMs a bit higher. There are many stationary tests, the most famous one is Augmented Dicky-Fuller Test, which has off-the-shelf implementations in python. There is an excellent article here, that simply designs a model to forecast a time series generated by a random walk process, and evaluates a very high accuracy. In fact, forecasting a random walk process is impossible. However, this misleading inference might occur if you use directly raw data instead of stationary differenced data. Another thing to mention about time series is to plot ACF and PACF plots and investigate dependencies of time series with respect to different historical lag values. That will definitely give an insight into the time series you are dealing with. It is always a good idea to have a baseline model to measure the performance of your model relatively. Baseline models are expected to be simple, fast, and repeatable. The most common method to establish a baseline model is the persistence model. It has a very simple working principle, just forecast the next time step as the previous one, in other saying t+1 is the same as t. For multi-step forecasting, it might be adapted forecast t+1, t+2, t+3 as t, entire forecast horizon will be the same. In my opinion, that is not very reasonable. Instead of that, I prefer to forecast each time step in the forecast horizon as the mean of the previous same time of the same devices. A simple code snippet is the following. df[‘DATETIME’] = pd.to_datetime(df[‘DATETIME’])df[‘hour’] = df[‘DATETIME’].apply(lambda x: x.hour)df[‘minute’] = df[‘DATETIME’].apply(lambda x: x.minute)train_test_split = datetime.strptime(‘20.04.2020 00:00:00’, ‘%d.%m.%Y %H:%M:%S’)df_train_pers = df.loc[df[‘DATETIME’] < train_test_split]df_test_pers = df.loc[df[‘DATETIME’] >= train_test_split]df_cpu_mean = df_train_pers.groupby([‘ID’, ‘hour’, ‘minute’]).mean(‘CPUUSED’).round(2)df_cpu_mean.reset_index(inplace=True)df_cpu_mean = df_cpu_mean.rename(columns={“CPUUSED”: “CPUUSED_PRED”})df_test_pers = df_test_pers.merge(df_cpu_mean, on=[‘ID’,’hour’, ‘minute’], how=’inner’)# the method explanation is at the next sectionevaluate_forecast(df_test_pers[‘CPUUSED’], df_test_pers[‘CPUUSED_PRED’])mae: 355.13mse: 370617.18mape: 16.56 As it can be seen, our baseline model forecast with approximately 16.56% error margin. I will go into detail for the evaluation metrics in the Evaluation of the Model part. Let’s see if we might outperform this result. I will mention different neural network-based models for Multiple Parallel Input and Multi-Step Forecast. Before describing the models, let me share a few common things and code snippets like Keras callbacks, applying the inverse transformation, and evaluating the results. The used callbacks while compiling the models are the following. ModelCheckpoint is to save the model(weights) at certain frequencies. EarlyStopping is used for stopping the progress if the monitored evaluation metric is no longer improved. ReduceLROnPlateau is for decreasing the learning rate when the monitored metric has stopped improving. checkpoint_filepath = ‘path_to_checkpoint_filepath’checkpoint_callback = ModelCheckpoint( filepath=checkpoint_filepath, save_weights_only=False, monitor=’val_loss’, mode=’min’, save_best_only=True)early_stopping_callback = EarlyStopping( monitor=”val_loss”, min_delta=0.005, patience=10, mode=”min”)rlrop_callback = ReduceLROnPlateau(monitor=’val_loss’, factor=0.2, mode=’min’, patience=3, min_lr=0.001) Since we apply normalization to the data before feeding it to the model, we should transform it back to the original scale to evaluate the forecast. We might simply utilize the following method. In the case of differencing the data to make it stationary, you should first invert scaling and then invert differencing sequentially. The order is opposite for forecasting, that is you first apply differencing and then normalize the data. For inverting the differencing data, the simple approach is to cumulatively add the difference forecasts to the last cumulative observation. def inverse_transform(y_test, yhat): y_test_reshaped = y_test.reshape(-1, y_test.shape[-1]) yhat_reshaped = yhat.reshape(-1, yhat.shape[-1]) yhat_inverse = scaler.inverse_transform(yhat_reshaped) y_test_inverse = scaler.inverse_transform(y_test_reshaped) return yhat_inverse, y_test_inverse To evaluate the forecast, I simply take into consideration mean square error(mse), mean absolute error(mae), and mean absolute percentage error(mape) respectively. You can extend the evaluation metrics. Note that, root mean square error(rmse) and mae give error in the same units as the variable itself and are widely used. I will just compare the models according to mape in this writing. def evaluate_forecast(y_test_inverse, yhat_inverse): mse_ = tf.keras.losses.MeanSquaredError() mae_ = tf.keras.losses.MeanAbsoluteError() mape_ = tf.keras.losses.MeanAbsolutePercentageError() mae = mae_(y_test_inverse,yhat_inverse) print('mae:', mae) mse = mse_(y_test_inverse,yhat_inverse) print('mse:', mse) mape = mape_(y_test_inverse,yhat_inverse) print('mape:', mape) The common imported packages are below. from tensorflow.keras import Sequentialfrom tensorflow.keras.layers import LSTM, Dense, Dropout, TimeDistributed, Conv1D, MaxPooling1D, Flatten, Bidirectional, Input, Flatten, Activation, Reshape, RepeatVector, Concatenatefrom tensorflow.keras.models import Modelfrom tensorflow.keras.utils import plot_modelfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint At this step, I think mentioning about TimeDistributed and RepeatVector layer in Keras would be beneficial. These are not very frequently used layers, however, they might be very useful in some specific cases like in our case. In short, TimeDistributed layer is a kind of wrapper and expects another layer as an argument. It applies this layer to every temporal slice of input and therefore allows to build models that have one-to-many, many-to-many architectures. Similarly, it expects the input at least as 3 dimensions. I am aware that it is not very clear for beginners, you can find a useful discussion here. RepeatVector basically repeats inputs n times. In other words, it increases the dimension of the output shape by 1. There is a good explanation and diagram for RepeatVector here, take a look. epochs = 50batch_size = 32validation = 0.1 The above are defined for compiling the model. Encoder-Decoder Model model_enc_dec = Sequential()model_enc_dec.add(LSTM(100, activation=’relu’, input_shape=(LOOK_BACK, n_features)))model_enc_dec.add(RepeatVector(FORECAST_RANGE))model_enc_dec.add(LSTM(100, activation=’relu’, return_sequences=True))model_enc_dec.add(TimeDistributed(Dense(n_features)))model_enc_dec.compile(optimizer=’adam’, loss=’mse’)plot_model(model=model_enc_dec, show_shapes=True)history = model_enc_dec.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, validation_split=validation,callbacks=[early_stopping_callback, checkpoint_callback, rlrop_callback])yhat = model_enc_dec.predict(X_test, verbose=0)yhat_inverse, y_test_inverse = inverse_transform(y_test, yhat)evaluate_forecast(y_test_inverse, yhat_inverse)mae: 145.95mse: 49972.53mape: 7.40 Encoder-decoder architecture is a typical solution for sequence to sequence learning. This architecture contains at least two RNN/LSTMs, and one of them behaves as an encoder while the other one behaves as a decoder. The encoder is basically responsible for reading and interpreting the input. The encoder part compresses the input into a small representation(a fixed-length vector) of the original input, and this context vector is given to the decoder part as input to be interpreted and perform forecasting. A RepeatVector layer is used to repeat the context vector we obtain from the encoder part. It is repeated for the number of future steps you want to forecast and is fed into the decoder part. The output received from the decoder in terms of each time step is mixed. A fully connected Dense layer is applied to each time step via TimeDistributed wrapper, so separates the output for each time step. In each encoder and decoder, different kinds of architectures might be utilized. One example is given in the next part in which CNN is used as a feature extractor in the encoder. CNN-LSTM Encoder-Decoder Model The following model is an extension of encoder-decoder architecture where the encoder part consists of Conv1D layers, unlike the previous model. First of all, two subsequent Conv1D layers are placed at the beginning to extract features, and then it is flattened after pooling the results of Conv1D. The rest of the architecture is very similar to the previous model. For simplicity, I just do not share plotting, fitting of the model, forecasting of the test set, and inverse transforming step those will be exactly the same as the rest of the models. model_enc_dec_cnn = Sequential()model_enc_dec_cnn.add(Conv1D(filters=64, kernel_size=9, activation=’relu’, input_shape=(LOOK_BACK, n_features)))model_enc_dec_cnn.add(Conv1D(filters=64, kernel_size=11, activation=’relu’))model_enc_dec_cnn.add(MaxPooling1D(pool_size=2))model_enc_dec_cnn.add(Flatten())model_enc_dec_cnn.add(RepeatVector(FORECAST_RANGE))model_enc_dec_cnn.add(LSTM(200, activation=’relu’, return_sequences=True))model_enc_dec_cnn.add(TimeDistributed(Dense(100, activation=’relu’)))model_enc_dec_cnn.add(TimeDistributed(Dense(n_features)))model_enc_dec_cnn.compile(loss=’mse’, optimizer=’adam’)mae: 131.89mse: 50962.38mape: 7.01 Vector Output Model This architecture might be thought of as a much more common architecture compared to the above-mentioned models, however, it is not very suitable for our case. Nevertheless, I share an example model to give an idea. At variance with encoder-decoder architecture, neither RepeatVector nor TimeDistributed layer exists. The point is to add a Dense layer with FORECAST_RANGE*n_features node, and then reshape it accordingly at the next layer. You might also design a similar architecture with RepeatVector layer instead of Reshape layer. The time steps of each series would be flattened in this structure and must interpret each of the outputs as a specific time step for a specific series during training and prediction. That means we also might reshape our label set as 2 dimensions rather than 3 dimensions, and interpret the results in the output layer accordingly without using Reshape layer. For simplicity, I did not change the shape of the label set, but just keep it in mind this alternative way as well. I also utilized Conv1D layers at the beginning of the architecture. This structure might be also called a multi-channel model. Do not overestimate the names. When dealing with multiple time series, CNNs with multiple channels are utilized traditionally. In this structure, each channel corresponds to a single time series and similarly extracts convolved features separately for each time series. Since all of the extracted features are combined before feeding into the LSTM layer, some typical features of each time series might be lost. input_layer = Input(shape=(LOOK_BACK, n_features)) conv = Conv1D(filters=4, kernel_size=7, activation=’relu’)(input_layer)conv = Conv1D(filters=6, kernel_size=11, activation=’relu’)(conv)lstm = LSTM(100, return_sequences=True, activation=’relu’)(conv)dropout = Dropout(0.2)(lstm)lstm = LSTM(100, activation=’relu’)(dropout)dense = Dense(FORECAST_RANGE*n_features, activation=’relu’)(lstm)output_layer = Reshape((FORECAST_RANGE,n_features))(dense)model_vector_output = Model([input_layer], [output_layer])model_vector_output.compile(optimizer=’adam’, loss=’mse’)mae: 185.95mse: 92596.76mape: 9.49 Multi-Head CNN-LSTM Model This architecture is a bit different from the above-mentioned models. It is explained very clearly in the study of Canizo. The multi-head structure uses multiple one-dimensional CNN layers in order to process each time series and extract independent convolved features from each time series. These separate CNNs are called “head” and flattened, concatenated, and reshaped respectively before feeding into the LSTM layer. To summarize, multi-head structures utilize multiple CNNs rather than only one CNN like in multi-channel structure. Therefore, they might be more successful to keep significant features of each time series and make better forecasts in this sense. input_layer = Input(shape=(LOOK_BACK, n_features)) head_list = []for i in range(0, n_features): conv_layer_head = Conv1D(filters=4, kernel_size=7, activation=’relu’)(input_layer) conv_layer_head_2 = Conv1D(filters=6, kernel_size=11, activation=’relu’)(conv_layer_head) conv_layer_flatten = Flatten()(conv_layer_head_2) head_list.append(conv_layer_flatten) concat_cnn = Concatenate(axis=1)(head_list)reshape = Reshape((head_list[0].shape[1], n_features))(concat_cnn)lstm = LSTM(100, activation=’relu’)(reshape)repeat = RepeatVector(FORECAST_RANGE)(lstm)lstm_2 = LSTM(100, activation=’relu’, return_sequences=True)(repeat)dropout = Dropout(0.2)(lstm_2)dense = Dense(n_features, activation=’linear’)(dropout)multi_head_cnn_lstm_model = Model(inputs=input_layer, outputs=dense)mae: 149.88mse: 65214.09mape: 8.03 Evaluation is basically the same with any forecasting modeling approach and the general performance of the models might be calculated with the evaluate_forecast method I shared in previous parts. However, there are 2 different points in our case, and it would be beneficial to take them into consideration as well. The first one is that we are performing multi-step forecasting, so we might want to analyze our forecasting accuracy for each of the time steps separately. This would give an insight into selecting an accurate forecast horizon. The second one is that we are performing a forecast for multiple parallel time series. Therefore, it would also be beneficial to observe the results of each time series forecasting. The model might work significantly worse for a specific time series than the rest of the time series. You can simply utilize different kinds of evaluation metrics, I prefer Mean Absolute Percentage Error(mape) in this article that handles the different time series scales. Given the stochastic nature of the models, it is good practice to evaluate a given model multiple times and report the mean performance on a test data set. For simplicity, I just run them only once in this article. With respect to each time step output, I just share a simple code snippet and figure that represents the mape values of forecasting for each time step. As expected, mape increases along with an increasing forecasting range. The figure represents the Multi-Head CNN-LSTM architecture and might be applied directly to other architectures I mentioned above. If you observe a sharp increase in mape, you might decrease your forecast horizon and set it to the point just before the sharp increase. y_test_inverse_time_step = y_test_inverse.reshape(int(y_test_inverse.shape[0]/FORECAST_RANGE), FORECAST_RANGE, y_test_inverse.shape[-1])yhat_inverse_time_step = yhat_inverse.reshape(int(yhat_inverse.shape[0]/FORECAST_RANGE), FORECAST_RANGE, yhat_inverse.shape[-1])# yhat_inverse_time_step and y_test_inverse_time_step are both same dimension.time_step_list_yhat = [[] for i in range(FORECAST_RANGE)]time_step_list_y_test = [[] for i in range(FORECAST_RANGE)]for i in range(0, yhat_inverse_time_step.shape[0]): for j in range(0, yhat_inverse_time_step.shape[1]): time_step_list_yhat[j].append(list(yhat_inverse_time_step[i][j])) time_step_list_y_test[j].append(list(y_test_inverse_time_step[i][j]))yhat_time_step = np.array(time_step_list_yhat)yhat_time_step = yhat_time_step.reshape(yhat_time_step.shape[0], -1)y_test_time_step = np.array(time_step_list_y_test)y_test_time_step = y_test_time_step.reshape(y_test_time_step.shape[0], -1)# plottingmape_list = []for i in range(0, FORECAST_RANGE): mape = mape_(y_test_time_step[i], yhat_time_step[i]) mape_list.append(mape)plt.plot(range(0, FORECAST_RANGE), mape_list, marker=’o’)plt.xticks((range(0, FORECAST_RANGE)))plt.xlabel(‘Forecast Range’)plt.ylabel(‘MAPE’) The following code snippet might be used for analyzing model performance with respect to different input time series. The forecast performance of the model is better for all CPUs compared to the overall results of the baseline model. Although mae of the second CPU is significantly low compared to the other CPUs, its mape is significantly higher than the others. Actually, it is one of the reasons why I am using mape in this article as an evaluation criterion. Each of the CPU usage values behaves similarly, but completely on different scales. To be honest, it has been a good example of my point. Why error ratio for the second CPU is so high? What should I do in such circumstances? Dividing the entire time series into subparts, and developing separate models for each of them might be an option. What else? I really appreciate reading any valuable approaches in the comments. Even though it is not very meaningful for our case, plotting a histogram for the performance of each time series would be expressive for data sets including more parallel time series. for i in range(0, n_features): print(‘->‘, i) mae = mae_(y_test_inverse[:,i],yhat_inverse[:,i]) print('mae:', mae) mse = mse_(y_test_inverse[:,i],yhat_inverse[:,i]) print('mse:', mse) mape = mape_(y_test_inverse[:,i],yhat_inverse[:,i]) print('mape:', mape)-> 0mae: 126.53mse: 32139.92mape: 5.44-> 1mae: 42.03mse: 3149.85mape: 13.18-> 2mae: 281.08mse: 160352.55mape: 5.46 Before finalizing the article, I want to touch on a few important points about time series forecasting in real life. First of all, traditional methods used in machine learning for model evaluation are mostly not valid in time series forecasting. It is because they do not take into consideration temporal dependencies that are the case for time series. 3 different methodologies are mentioned here. The most straightforward one is to determine a split point and separate the data set as train and test without shuffling just as we have done in this article. However, in real life, it does not give a robust insight into the performance of the model. The other one is to repeat the same strategy multiple times, that is multiple train test splits. In this method, you create multiple train and test sets and so multiple models. You should consider keeping the test set size the same to compare the models' performance correctly. You might also keep the train set size the same by only taking into account a fixed length of the latest data. Note that there is a package in sklearn called as TimeSeriesSplit to perform this methodology. The final most robust methodology is walk forward validation which is the k-fold cross-validation of the time series world. In this approach, a new model is created after each forecast by including new known value to the train set. It is repeated continuously with a sliding window approach and takes into a minimum number of observations for training the model. It is the most robust method but comes with a cost obviously. To create many models for especially mass amounts of data might be cumbersome. Apart from the traditional ML approaches, time series forecasting models should be updated more frequently in order to capture changing trend behaviors. However, in my opinion, the model does not need to be retrained whenever you want to generate a new prediction as stated here. It will be very costly and unnecessary if the time series does not change in a very frequent and drastic way. What I agree totally with the above article is that accurately defining confidence intervals for forecasting is as important as forecasting itself, even more important in real-life scenarios considering anomaly detection use cases. It deserves to be the topic of another article. Last but not definitely least, running a multi-step forecasting model in production is quite different from traditional machine learning approaches. There are a few options, the most common ones are recursive and direct strategies. In recursive strategy, at each forecasting step, the model is used to predict one step ahead and the value obtained from the forecasting is then fed into the same model to predict the following step. The same model is used for each forecast. However, at this strategy, the forecasting error propagates along the forecast horizon as you can expect. And it might be a burden, especially for long forecast horizons. On the other hand, a separate model is designed for each forecast horizon in direct strategy. It will be obviously overwhelmed with the increasing length of the forecast horizon, which means an increasing number of models. Furthermore, it does not take into account statistical dependencies among the predictions since each model is independent of each others. As another strategy, you might also design a model that is capable of performing multi-step forecasting at once like what we did in this article. In this article, I focus on a very specific use case for time series forecasting but a common use case at the same time in real-life scenarios. Additionally, I mention a few general key points that should be taken into consideration while implementing forecasting models. When you encounter multiple time series and are supposed to perform multi-step forecasting for each of them, firstly try to create separate models to achieve the best result. However, the number of time series might be extremely much in real life, you should also consider using above mentioned single model architectures in such cases. You might also utilize different kinds of layers like Bidirectional, ConvLSTM adhering to the architectures, and get better results by tuning parameters. The use cases I mention mostly consist of the same unit time series like traffic values flowing through each device or temperature values of different devices spread over a large area. To see the results with different kinds of time series would be interesting as well. For instance, a single model approach for forecasting temperature, humidity, pressure at once. I believe it is still an open research area considering lots of different academic studies in this area. In this sense, I appreciate hearing different approaches as well in the comments.
[ { "code": null, "e": 774, "s": 172, "text": "Time series forecasting is a very popular field of machine learning. The reason behind this is the widespread usage of time series in daily life in almost every domain. Going into details for time series forecasting, we encounter lots of different kinds of sub-fields and approaches. In this writing, I will focus on a specific subdomain that is performing multi-step forecasts by receiving multiple parallel time series, and also mention basic key points that should be taken into consideration in time series forecasting. Note that forecasting models differ from predictive models at various points." }, { "code": null, "e": 1382, "s": 774, "text": "Let's think about lots of network devices spread over a large geography, and traffic flows through these devices continuously. Another example might be about lots of different temperature devices which measure the temperature of the weather in different locations continuously or another one might be to calculate the energy consumption of numerous devices in a system. We can just extend these kinds of examples easily. The goal is simple; forecast the next multiple time steps; this corresponds to forecasting traffic value, temperature, or the energy consumption of many devices respectively in our case." }, { "code": null, "e": 2013, "s": 1382, "text": "The first thing that comes to mind is certainly modeling each device separately. I think we will probably get the highest forecast results. What about if there are more than 100 different devices or even more? That means designing 100 different models. It is not much applicable considering the deploying, monitoring, and maintenance costs. Therefore, we aim to cover the entire problem with just a single model. I think it is still a very popular and searching field of time series forecasting, although time series forecasting has been on the table for a long time. I encounter lots of different academic research in this field." }, { "code": null, "e": 2600, "s": 2013, "text": "This problem might also be defined as seq2seq prediction. In particular, it is a very common case in speech recognition and translations. LSTM is very convenient for these kinds of problems. CNN can also be considered as another type of neural network and is commonly used in image processing tasks. Typically, it is used in feature extraction and time series forecasting as well. I will mention the appliance of LSTM and CNN for time series forecasting in multiple parallel inputs and multi-step forecasting cases. Explanation of LSTM and CNN is simply beyond the scope of the writing." }, { "code": null, "e": 2799, "s": 2600, "text": "To make it more clear, I depict a simple data example below. It is an example of forecasting traffic values of 3 different devices for the next 2 hours by looking at the previous 3 hours time slots." }, { "code": null, "e": 2987, "s": 2799, "text": "In this writing, I will utilize a data set consisting of a CPU usage of 288 different servers within 15 minutes time interval. For simplicity, I will narrow down the scope into 3 servers." }, { "code": null, "e": 3258, "s": 2987, "text": "Pre-modelling is very critical in neural network implementations. You mostly can not simply feed the neural network with raw data directly, a simple transformation is needed. However, we should apply a few more additional steps to the raw data before the transformation." }, { "code": null, "e": 3314, "s": 3258, "text": "The following is for pivoting the raw data in our case." }, { "code": null, "e": 3403, "s": 3314, "text": "df_cpu_pivot = pd.pivot_table(df, values=’CPUUSED’, index=[‘DATETIME’], columns=[‘ID’])" }, { "code": null, "e": 3725, "s": 3403, "text": "The following is for interpolating the missing values in the data set. Imputing null values in time series is very crucial on its own, and a challenging task as well. We don’t have many null values in this data set and imputing null values is beyond the scope of this writing, therefore I perform a simple implementation." }, { "code": null, "e": 3822, "s": 3725, "text": "for i in range(0, len(df_cpu_pivot.columns)): df_cpu_pivot.iloc[:,i].interpolate(inplace = True)" }, { "code": null, "e": 4193, "s": 3822, "text": "The first thing before passing into the modeling phase, at the very beginning of the data preprocessing step for time series forecasting is plotting the time series in my opinion. Let's see what tells the data to us. As I mentioned before, I select only 3 different servers for simplicity. As it can be seen, all of them follow very similar patterns in different scales." }, { "code": null, "e": 4917, "s": 4193, "text": "import plotlyimport plotly.express as pximport plotly.graph_objects as godf_cpu_pivot.reset_index(inplace=True)df_cpu_pivot['DATETIME'] = pd.to_datetime(df_cpu_pivot['DATETIME'])trace1 = go.Scatter( x = df_cpu_pivot[‘DATETIME’], y = df_cpu_pivot[‘HSSFE-hssahlk01CPU-0’], mode = ‘lines’, name = ‘cpu_1’)trace2 = go.Scatter( x = df_cpu_pivot[‘DATETIME’], y = df_cpu_pivot[‘HSSFE-hssumrk03CPU-29’], mode = ‘lines’, name = ‘cpu_2’)trace3 = go.Scatter( x = df_cpu_pivot[‘DATETIME’], y = df_cpu_pivot[‘HSSFE-hssumrk03CPU-4’], mode = ‘lines’, name = ‘cpu_3’)layout = go.Layout( title = “CPU Usage”, xaxis = {‘title’ : “Date”}, yaxis = {‘title’ : “Cpu Usage”})fig = go.Figure(data=[trace1, trace2, trace3], layout=layout)fig.show()" }, { "code": null, "e": 5142, "s": 4917, "text": "The next step is to split the data set into train and test sets. It is a bit different in time series from conventional machine learning implementations. We can intuitively determine a split date for separating the data set." }, { "code": null, "e": 5396, "s": 5142, "text": "from datetime import datetimetrain_test_split = datetime.strptime(‘20.04.2020 00:00:00’, ‘%d.%m.%Y %H:%M:%S’)df_train = df_cpu_pivot.loc[df_cpu_pivot[‘DATETIME’] < train_test_split]df_test = df_cpu_pivot.loc[df_cpu_pivot[‘DATETIME’] >= train_test_split]" }, { "code": null, "e": 5499, "s": 5396, "text": "We also normalize the data before feeding it into any neural network model because of its sensitivity." }, { "code": null, "e": 5736, "s": 5499, "text": "from sklearn.preprocessing import MinMaxScalercpu_list = [i for i in df_cpu_pivot.columns if i != ‘DATETIME’]scaler = MinMaxScaler()scaled_train = scaler.fit_transform(df_train[cpu_list])scaled_test = scaler.transform(df_test[cpu_list])" }, { "code": null, "e": 6146, "s": 5736, "text": "And the final stage is to transform both train and test set into an acceptable format for neural networks. The following method can be implemented to transform the data. It simply expects 2 parameters except for the sequence itself, which are time lag(steps of looking back), and forecasting range respectively. You can also take a look at TimeSeriesGenerator class defined in Keras to transform the data set." }, { "code": null, "e": 6511, "s": 6146, "text": "def split_sequence(sequence, look_back, forecast_horizon): X, y = list(), list() for i in range(len(sequence)): lag_end = i + look_back forecast_end = lag_end + forecast_horizon if forecast_end > len(sequence): break seq_x, seq_y = sequence[i:lag_end], sequence[lag_end:forecast_end] X.append(seq_x) y.append(seq_y) return np.array(X), np.array(y)" }, { "code": null, "e": 6635, "s": 6511, "text": "An LSTM model expects data to have the shape; [samples, timesteps, features]. Similarly, CNN also expects 3D data as LSTMs." }, { "code": null, "e": 7100, "s": 6635, "text": "# Take into consideration last 6 hours, and perform forecasting for next 1 hourLOOK_BACK = 24FORECAST_RANGE = 4n_features = len(cpu_list)X_train, y_train = split_sequence(scaled_train, look_back=LOOK_BACK, forecast_horizon=FORECAST_RANGE)X_test, y_test = split_sequence(scaled_test, look_back=LOOK_BACK, forecast_horizon=FORECAST_RANGE)print(X_train.shape)print(y_train.shape)print(X_test.shape)print(y_test.shape)(4869, 24, 3)(4869, 4, 3)(1029, 24, 3)(1029, 4, 3)" }, { "code": null, "e": 7117, "s": 7100, "text": "Additional Notes" }, { "code": null, "e": 7262, "s": 7117, "text": "I want to also mention additional pre-modeling steps for time series forecasting. These are not directly scope of the writing but worth knowing." }, { "code": null, "e": 8225, "s": 7262, "text": "Stationary is a very important issue for time series, most forecasting algorithm like ARIMA expects time series to be stationary. Stationary time series basically keep very similar mean, variance values over time and do not include seasonality and trend. To make time series stationary, the most straightforward method is to take the difference of subsequent values in the sequence. If variance fluctuates very much compared to mean, it also might be a good idea to take the log of the sequence to make it stationary. Unlike most of the other forecasting algorithms, LSTMs are capable of learning nonlinearities and long-term dependencies in the sequence. Thus, stationary is a less of concern of LSTMs. Nevertheless, it is a good practice to make the time series stationary and increase the performance of LSTMs a bit higher. There are many stationary tests, the most famous one is Augmented Dicky-Fuller Test, which has off-the-shelf implementations in python." }, { "code": null, "e": 8561, "s": 8225, "text": "There is an excellent article here, that simply designs a model to forecast a time series generated by a random walk process, and evaluates a very high accuracy. In fact, forecasting a random walk process is impossible. However, this misleading inference might occur if you use directly raw data instead of stationary differenced data." }, { "code": null, "e": 8807, "s": 8561, "text": "Another thing to mention about time series is to plot ACF and PACF plots and investigate dependencies of time series with respect to different historical lag values. That will definitely give an insight into the time series you are dealing with." }, { "code": null, "e": 9525, "s": 8807, "text": "It is always a good idea to have a baseline model to measure the performance of your model relatively. Baseline models are expected to be simple, fast, and repeatable. The most common method to establish a baseline model is the persistence model. It has a very simple working principle, just forecast the next time step as the previous one, in other saying t+1 is the same as t. For multi-step forecasting, it might be adapted forecast t+1, t+2, t+3 as t, entire forecast horizon will be the same. In my opinion, that is not very reasonable. Instead of that, I prefer to forecast each time step in the forecast horizon as the mean of the previous same time of the same devices. A simple code snippet is the following." }, { "code": null, "e": 10307, "s": 9525, "text": "df[‘DATETIME’] = pd.to_datetime(df[‘DATETIME’])df[‘hour’] = df[‘DATETIME’].apply(lambda x: x.hour)df[‘minute’] = df[‘DATETIME’].apply(lambda x: x.minute)train_test_split = datetime.strptime(‘20.04.2020 00:00:00’, ‘%d.%m.%Y %H:%M:%S’)df_train_pers = df.loc[df[‘DATETIME’] < train_test_split]df_test_pers = df.loc[df[‘DATETIME’] >= train_test_split]df_cpu_mean = df_train_pers.groupby([‘ID’, ‘hour’, ‘minute’]).mean(‘CPUUSED’).round(2)df_cpu_mean.reset_index(inplace=True)df_cpu_mean = df_cpu_mean.rename(columns={“CPUUSED”: “CPUUSED_PRED”})df_test_pers = df_test_pers.merge(df_cpu_mean, on=[‘ID’,’hour’, ‘minute’], how=’inner’)# the method explanation is at the next sectionevaluate_forecast(df_test_pers[‘CPUUSED’], df_test_pers[‘CPUUSED_PRED’])mae: 355.13mse: 370617.18mape: 16.56" }, { "code": null, "e": 10526, "s": 10307, "text": "As it can be seen, our baseline model forecast with approximately 16.56% error margin. I will go into detail for the evaluation metrics in the Evaluation of the Model part. Let’s see if we might outperform this result." }, { "code": null, "e": 10800, "s": 10526, "text": "I will mention different neural network-based models for Multiple Parallel Input and Multi-Step Forecast. Before describing the models, let me share a few common things and code snippets like Keras callbacks, applying the inverse transformation, and evaluating the results." }, { "code": null, "e": 11144, "s": 10800, "text": "The used callbacks while compiling the models are the following. ModelCheckpoint is to save the model(weights) at certain frequencies. EarlyStopping is used for stopping the progress if the monitored evaluation metric is no longer improved. ReduceLROnPlateau is for decreasing the learning rate when the monitored metric has stopped improving." }, { "code": null, "e": 11548, "s": 11144, "text": "checkpoint_filepath = ‘path_to_checkpoint_filepath’checkpoint_callback = ModelCheckpoint( filepath=checkpoint_filepath, save_weights_only=False, monitor=’val_loss’, mode=’min’, save_best_only=True)early_stopping_callback = EarlyStopping( monitor=”val_loss”, min_delta=0.005, patience=10, mode=”min”)rlrop_callback = ReduceLROnPlateau(monitor=’val_loss’, factor=0.2, mode=’min’, patience=3, min_lr=0.001)" }, { "code": null, "e": 12124, "s": 11548, "text": "Since we apply normalization to the data before feeding it to the model, we should transform it back to the original scale to evaluate the forecast. We might simply utilize the following method. In the case of differencing the data to make it stationary, you should first invert scaling and then invert differencing sequentially. The order is opposite for forecasting, that is you first apply differencing and then normalize the data. For inverting the differencing data, the simple approach is to cumulatively add the difference forecasts to the last cumulative observation." }, { "code": null, "e": 12415, "s": 12124, "text": "def inverse_transform(y_test, yhat): y_test_reshaped = y_test.reshape(-1, y_test.shape[-1]) yhat_reshaped = yhat.reshape(-1, yhat.shape[-1]) yhat_inverse = scaler.inverse_transform(yhat_reshaped) y_test_inverse = scaler.inverse_transform(y_test_reshaped) return yhat_inverse, y_test_inverse" }, { "code": null, "e": 12805, "s": 12415, "text": "To evaluate the forecast, I simply take into consideration mean square error(mse), mean absolute error(mae), and mean absolute percentage error(mape) respectively. You can extend the evaluation metrics. Note that, root mean square error(rmse) and mae give error in the same units as the variable itself and are widely used. I will just compare the models according to mape in this writing." }, { "code": null, "e": 13178, "s": 12805, "text": "def evaluate_forecast(y_test_inverse, yhat_inverse): mse_ = tf.keras.losses.MeanSquaredError() mae_ = tf.keras.losses.MeanAbsoluteError() mape_ = tf.keras.losses.MeanAbsolutePercentageError() mae = mae_(y_test_inverse,yhat_inverse) print('mae:', mae) mse = mse_(y_test_inverse,yhat_inverse) print('mse:', mse) mape = mape_(y_test_inverse,yhat_inverse) print('mape:', mape)" }, { "code": null, "e": 13218, "s": 13178, "text": "The common imported packages are below." }, { "code": null, "e": 13615, "s": 13218, "text": "from tensorflow.keras import Sequentialfrom tensorflow.keras.layers import LSTM, Dense, Dropout, TimeDistributed, Conv1D, MaxPooling1D, Flatten, Bidirectional, Input, Flatten, Activation, Reshape, RepeatVector, Concatenatefrom tensorflow.keras.models import Modelfrom tensorflow.keras.utils import plot_modelfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint" }, { "code": null, "e": 13842, "s": 13615, "text": "At this step, I think mentioning about TimeDistributed and RepeatVector layer in Keras would be beneficial. These are not very frequently used layers, however, they might be very useful in some specific cases like in our case." }, { "code": null, "e": 14229, "s": 13842, "text": "In short, TimeDistributed layer is a kind of wrapper and expects another layer as an argument. It applies this layer to every temporal slice of input and therefore allows to build models that have one-to-many, many-to-many architectures. Similarly, it expects the input at least as 3 dimensions. I am aware that it is not very clear for beginners, you can find a useful discussion here." }, { "code": null, "e": 14421, "s": 14229, "text": "RepeatVector basically repeats inputs n times. In other words, it increases the dimension of the output shape by 1. There is a good explanation and diagram for RepeatVector here, take a look." }, { "code": null, "e": 14464, "s": 14421, "text": "epochs = 50batch_size = 32validation = 0.1" }, { "code": null, "e": 14511, "s": 14464, "text": "The above are defined for compiling the model." }, { "code": null, "e": 14533, "s": 14511, "text": "Encoder-Decoder Model" }, { "code": null, "e": 15291, "s": 14533, "text": "model_enc_dec = Sequential()model_enc_dec.add(LSTM(100, activation=’relu’, input_shape=(LOOK_BACK, n_features)))model_enc_dec.add(RepeatVector(FORECAST_RANGE))model_enc_dec.add(LSTM(100, activation=’relu’, return_sequences=True))model_enc_dec.add(TimeDistributed(Dense(n_features)))model_enc_dec.compile(optimizer=’adam’, loss=’mse’)plot_model(model=model_enc_dec, show_shapes=True)history = model_enc_dec.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, validation_split=validation,callbacks=[early_stopping_callback, checkpoint_callback, rlrop_callback])yhat = model_enc_dec.predict(X_test, verbose=0)yhat_inverse, y_test_inverse = inverse_transform(y_test, yhat)evaluate_forecast(y_test_inverse, yhat_inverse)mae: 145.95mse: 49972.53mape: 7.40" }, { "code": null, "e": 16379, "s": 15291, "text": "Encoder-decoder architecture is a typical solution for sequence to sequence learning. This architecture contains at least two RNN/LSTMs, and one of them behaves as an encoder while the other one behaves as a decoder. The encoder is basically responsible for reading and interpreting the input. The encoder part compresses the input into a small representation(a fixed-length vector) of the original input, and this context vector is given to the decoder part as input to be interpreted and perform forecasting. A RepeatVector layer is used to repeat the context vector we obtain from the encoder part. It is repeated for the number of future steps you want to forecast and is fed into the decoder part. The output received from the decoder in terms of each time step is mixed. A fully connected Dense layer is applied to each time step via TimeDistributed wrapper, so separates the output for each time step. In each encoder and decoder, different kinds of architectures might be utilized. One example is given in the next part in which CNN is used as a feature extractor in the encoder." }, { "code": null, "e": 16410, "s": 16379, "text": "CNN-LSTM Encoder-Decoder Model" }, { "code": null, "e": 16777, "s": 16410, "text": "The following model is an extension of encoder-decoder architecture where the encoder part consists of Conv1D layers, unlike the previous model. First of all, two subsequent Conv1D layers are placed at the beginning to extract features, and then it is flattened after pooling the results of Conv1D. The rest of the architecture is very similar to the previous model." }, { "code": null, "e": 16962, "s": 16777, "text": "For simplicity, I just do not share plotting, fitting of the model, forecasting of the test set, and inverse transforming step those will be exactly the same as the rest of the models." }, { "code": null, "e": 17603, "s": 16962, "text": "model_enc_dec_cnn = Sequential()model_enc_dec_cnn.add(Conv1D(filters=64, kernel_size=9, activation=’relu’, input_shape=(LOOK_BACK, n_features)))model_enc_dec_cnn.add(Conv1D(filters=64, kernel_size=11, activation=’relu’))model_enc_dec_cnn.add(MaxPooling1D(pool_size=2))model_enc_dec_cnn.add(Flatten())model_enc_dec_cnn.add(RepeatVector(FORECAST_RANGE))model_enc_dec_cnn.add(LSTM(200, activation=’relu’, return_sequences=True))model_enc_dec_cnn.add(TimeDistributed(Dense(100, activation=’relu’)))model_enc_dec_cnn.add(TimeDistributed(Dense(n_features)))model_enc_dec_cnn.compile(loss=’mse’, optimizer=’adam’)mae: 131.89mse: 50962.38mape: 7.01" }, { "code": null, "e": 17623, "s": 17603, "text": "Vector Output Model" }, { "code": null, "e": 18158, "s": 17623, "text": "This architecture might be thought of as a much more common architecture compared to the above-mentioned models, however, it is not very suitable for our case. Nevertheless, I share an example model to give an idea. At variance with encoder-decoder architecture, neither RepeatVector nor TimeDistributed layer exists. The point is to add a Dense layer with FORECAST_RANGE*n_features node, and then reshape it accordingly at the next layer. You might also design a similar architecture with RepeatVector layer instead of Reshape layer." }, { "code": null, "e": 18702, "s": 18158, "text": "The time steps of each series would be flattened in this structure and must interpret each of the outputs as a specific time step for a specific series during training and prediction. That means we also might reshape our label set as 2 dimensions rather than 3 dimensions, and interpret the results in the output layer accordingly without using Reshape layer. For simplicity, I did not change the shape of the label set, but just keep it in mind this alternative way as well. I also utilized Conv1D layers at the beginning of the architecture." }, { "code": null, "e": 19173, "s": 18702, "text": "This structure might be also called a multi-channel model. Do not overestimate the names. When dealing with multiple time series, CNNs with multiple channels are utilized traditionally. In this structure, each channel corresponds to a single time series and similarly extracts convolved features separately for each time series. Since all of the extracted features are combined before feeding into the LSTM layer, some typical features of each time series might be lost." }, { "code": null, "e": 19769, "s": 19173, "text": "input_layer = Input(shape=(LOOK_BACK, n_features)) conv = Conv1D(filters=4, kernel_size=7, activation=’relu’)(input_layer)conv = Conv1D(filters=6, kernel_size=11, activation=’relu’)(conv)lstm = LSTM(100, return_sequences=True, activation=’relu’)(conv)dropout = Dropout(0.2)(lstm)lstm = LSTM(100, activation=’relu’)(dropout)dense = Dense(FORECAST_RANGE*n_features, activation=’relu’)(lstm)output_layer = Reshape((FORECAST_RANGE,n_features))(dense)model_vector_output = Model([input_layer], [output_layer])model_vector_output.compile(optimizer=’adam’, loss=’mse’)mae: 185.95mse: 92596.76mape: 9.49" }, { "code": null, "e": 19795, "s": 19769, "text": "Multi-Head CNN-LSTM Model" }, { "code": null, "e": 20463, "s": 19795, "text": "This architecture is a bit different from the above-mentioned models. It is explained very clearly in the study of Canizo. The multi-head structure uses multiple one-dimensional CNN layers in order to process each time series and extract independent convolved features from each time series. These separate CNNs are called “head” and flattened, concatenated, and reshaped respectively before feeding into the LSTM layer. To summarize, multi-head structures utilize multiple CNNs rather than only one CNN like in multi-channel structure. Therefore, they might be more successful to keep significant features of each time series and make better forecasts in this sense." }, { "code": null, "e": 21271, "s": 20463, "text": "input_layer = Input(shape=(LOOK_BACK, n_features)) head_list = []for i in range(0, n_features): conv_layer_head = Conv1D(filters=4, kernel_size=7, activation=’relu’)(input_layer) conv_layer_head_2 = Conv1D(filters=6, kernel_size=11, activation=’relu’)(conv_layer_head) conv_layer_flatten = Flatten()(conv_layer_head_2) head_list.append(conv_layer_flatten) concat_cnn = Concatenate(axis=1)(head_list)reshape = Reshape((head_list[0].shape[1], n_features))(concat_cnn)lstm = LSTM(100, activation=’relu’)(reshape)repeat = RepeatVector(FORECAST_RANGE)(lstm)lstm_2 = LSTM(100, activation=’relu’, return_sequences=True)(repeat)dropout = Dropout(0.2)(lstm_2)dense = Dense(n_features, activation=’linear’)(dropout)multi_head_cnn_lstm_model = Model(inputs=input_layer, outputs=dense)mae: 149.88mse: 65214.09mape: 8.03" }, { "code": null, "e": 22098, "s": 21271, "text": "Evaluation is basically the same with any forecasting modeling approach and the general performance of the models might be calculated with the evaluate_forecast method I shared in previous parts. However, there are 2 different points in our case, and it would be beneficial to take them into consideration as well. The first one is that we are performing multi-step forecasting, so we might want to analyze our forecasting accuracy for each of the time steps separately. This would give an insight into selecting an accurate forecast horizon. The second one is that we are performing a forecast for multiple parallel time series. Therefore, it would also be beneficial to observe the results of each time series forecasting. The model might work significantly worse for a specific time series than the rest of the time series." }, { "code": null, "e": 22269, "s": 22098, "text": "You can simply utilize different kinds of evaluation metrics, I prefer Mean Absolute Percentage Error(mape) in this article that handles the different time series scales." }, { "code": null, "e": 22484, "s": 22269, "text": "Given the stochastic nature of the models, it is good practice to evaluate a given model multiple times and report the mean performance on a test data set. For simplicity, I just run them only once in this article." }, { "code": null, "e": 22977, "s": 22484, "text": "With respect to each time step output, I just share a simple code snippet and figure that represents the mape values of forecasting for each time step. As expected, mape increases along with an increasing forecasting range. The figure represents the Multi-Head CNN-LSTM architecture and might be applied directly to other architectures I mentioned above. If you observe a sharp increase in mape, you might decrease your forecast horizon and set it to the point just before the sharp increase." }, { "code": null, "e": 24188, "s": 22977, "text": "y_test_inverse_time_step = y_test_inverse.reshape(int(y_test_inverse.shape[0]/FORECAST_RANGE), FORECAST_RANGE, y_test_inverse.shape[-1])yhat_inverse_time_step = yhat_inverse.reshape(int(yhat_inverse.shape[0]/FORECAST_RANGE), FORECAST_RANGE, yhat_inverse.shape[-1])# yhat_inverse_time_step and y_test_inverse_time_step are both same dimension.time_step_list_yhat = [[] for i in range(FORECAST_RANGE)]time_step_list_y_test = [[] for i in range(FORECAST_RANGE)]for i in range(0, yhat_inverse_time_step.shape[0]): for j in range(0, yhat_inverse_time_step.shape[1]): time_step_list_yhat[j].append(list(yhat_inverse_time_step[i][j])) time_step_list_y_test[j].append(list(y_test_inverse_time_step[i][j]))yhat_time_step = np.array(time_step_list_yhat)yhat_time_step = yhat_time_step.reshape(yhat_time_step.shape[0], -1)y_test_time_step = np.array(time_step_list_y_test)y_test_time_step = y_test_time_step.reshape(y_test_time_step.shape[0], -1)# plottingmape_list = []for i in range(0, FORECAST_RANGE): mape = mape_(y_test_time_step[i], yhat_time_step[i]) mape_list.append(mape)plt.plot(range(0, FORECAST_RANGE), mape_list, marker=’o’)plt.xticks((range(0, FORECAST_RANGE)))plt.xlabel(‘Forecast Range’)plt.ylabel(‘MAPE’)" }, { "code": null, "e": 25071, "s": 24188, "text": "The following code snippet might be used for analyzing model performance with respect to different input time series. The forecast performance of the model is better for all CPUs compared to the overall results of the baseline model. Although mae of the second CPU is significantly low compared to the other CPUs, its mape is significantly higher than the others. Actually, it is one of the reasons why I am using mape in this article as an evaluation criterion. Each of the CPU usage values behaves similarly, but completely on different scales. To be honest, it has been a good example of my point. Why error ratio for the second CPU is so high? What should I do in such circumstances? Dividing the entire time series into subparts, and developing separate models for each of them might be an option. What else? I really appreciate reading any valuable approaches in the comments." }, { "code": null, "e": 25255, "s": 25071, "text": "Even though it is not very meaningful for our case, plotting a histogram for the performance of each time series would be expressive for data sets including more parallel time series." }, { "code": null, "e": 25626, "s": 25255, "text": "for i in range(0, n_features): print(‘->‘, i) mae = mae_(y_test_inverse[:,i],yhat_inverse[:,i]) print('mae:', mae) mse = mse_(y_test_inverse[:,i],yhat_inverse[:,i]) print('mse:', mse) mape = mape_(y_test_inverse[:,i],yhat_inverse[:,i]) print('mape:', mape)-> 0mae: 126.53mse: 32139.92mape: 5.44-> 1mae: 42.03mse: 3149.85mape: 13.18-> 2mae: 281.08mse: 160352.55mape: 5.46" }, { "code": null, "e": 25979, "s": 25626, "text": "Before finalizing the article, I want to touch on a few important points about time series forecasting in real life. First of all, traditional methods used in machine learning for model evaluation are mostly not valid in time series forecasting. It is because they do not take into consideration temporal dependencies that are the case for time series." }, { "code": null, "e": 26276, "s": 25979, "text": "3 different methodologies are mentioned here. The most straightforward one is to determine a split point and separate the data set as train and test without shuffling just as we have done in this article. However, in real life, it does not give a robust insight into the performance of the model." }, { "code": null, "e": 26760, "s": 26276, "text": "The other one is to repeat the same strategy multiple times, that is multiple train test splits. In this method, you create multiple train and test sets and so multiple models. You should consider keeping the test set size the same to compare the models' performance correctly. You might also keep the train set size the same by only taking into account a fixed length of the latest data. Note that there is a package in sklearn called as TimeSeriesSplit to perform this methodology." }, { "code": null, "e": 27264, "s": 26760, "text": "The final most robust methodology is walk forward validation which is the k-fold cross-validation of the time series world. In this approach, a new model is created after each forecast by including new known value to the train set. It is repeated continuously with a sliding window approach and takes into a minimum number of observations for training the model. It is the most robust method but comes with a cost obviously. To create many models for especially mass amounts of data might be cumbersome." }, { "code": null, "e": 27934, "s": 27264, "text": "Apart from the traditional ML approaches, time series forecasting models should be updated more frequently in order to capture changing trend behaviors. However, in my opinion, the model does not need to be retrained whenever you want to generate a new prediction as stated here. It will be very costly and unnecessary if the time series does not change in a very frequent and drastic way. What I agree totally with the above article is that accurately defining confidence intervals for forecasting is as important as forecasting itself, even more important in real-life scenarios considering anomaly detection use cases. It deserves to be the topic of another article." }, { "code": null, "e": 29086, "s": 27934, "text": "Last but not definitely least, running a multi-step forecasting model in production is quite different from traditional machine learning approaches. There are a few options, the most common ones are recursive and direct strategies. In recursive strategy, at each forecasting step, the model is used to predict one step ahead and the value obtained from the forecasting is then fed into the same model to predict the following step. The same model is used for each forecast. However, at this strategy, the forecasting error propagates along the forecast horizon as you can expect. And it might be a burden, especially for long forecast horizons. On the other hand, a separate model is designed for each forecast horizon in direct strategy. It will be obviously overwhelmed with the increasing length of the forecast horizon, which means an increasing number of models. Furthermore, it does not take into account statistical dependencies among the predictions since each model is independent of each others. As another strategy, you might also design a model that is capable of performing multi-step forecasting at once like what we did in this article." }, { "code": null, "e": 29358, "s": 29086, "text": "In this article, I focus on a very specific use case for time series forecasting but a common use case at the same time in real-life scenarios. Additionally, I mention a few general key points that should be taken into consideration while implementing forecasting models." } ]
Markov Chain Monte Carlo in Python | by Will Koehrsen | Towards Data Science
A Complete Real-World Implementation The past few months, I encountered one term again and again in the data science world: Markov Chain Monte Carlo. In my research lab, in podcasts, in articles, every time I heard the phrase I would nod and think that sounds pretty cool with only a vague idea of what anyone was talking about. Several times I tried to learn MCMC and Bayesian inference, but every time I started reading the books, I soon gave up. Exasperated, I turned to the best method to learn any new skill: apply it to a problem. Using some of my sleep data I had been meaning to explore and a hands-on application-based book (Bayesian Methods for Hackers, available free online), I finally learned Markov Chain Monte Carlo through a real-world project. As usual, it was much easier (and more enjoyable) to understand the technical concepts when I applied them to a problem rather than reading them as abstract ideas on a page. This article walks through the introductory implementation of Markov Chain Monte Carlo in Python that finally taught me this powerful modeling and analysis tool. The full code and data for this project is on GitHub. I encourage anyone to take a look and use it on their own data. This article focuses on applications and results, so there are a lot of topics covered at a high level, but I have tried to provide links for those wanting to learn more! My Garmin Vivosmart watch tracks when I fall asleep and wake up based on heart rate and motion. It’s not 100% accurate, but real-world data is never perfect, and we can still extract useful knowledge from noisy data with the right model! The objective of this project was to use the sleep data to create a model that specifies the posterior probability of sleep as a function of time. As time is a continuous variable, specifying the entire posterior distribution is intractable, and we turn to methods to approximate a distribution, such as Markov Chain Monte Carlo (MCMC). Before we can start with MCMC, we need to determine an appropriate function for modeling the posterior probability distribution of sleep. One simple way to do this is to visually inspect the data. The observations for when I fall asleep as a function of time are shown below. Every data point is represented as a dot, with the intensity of the dot showing the number of observations at the specific time. My watch records only the minute at which I fall asleep, so to expand the data, I added points to every minute on both sides of the precise time. If my watch says I fell asleep at 10:05 PM, then every minute before is represented as a 0 (awake) and every minute after gets a 1 (asleep). This expanded the roughly 60 nights of observations into 11340 data points. We can see that I tend to fall asleep a little after 10:00 PM but we want to create a model that captures the transition from awake to asleep in terms of a probability. We could use a simple step function for our model that changes from awake (0) to asleep (1) at one precise time, but this would not represent the uncertainty in the data. I do not go to sleep at the same time every night, and we need a function to that models the transition as a gradual process to show the variability. The best choice given the data is a logistic function which is smoothly transitions between the bounds of 0 and 1. Following is a logistic equation for the probability of sleep as a function of time Here, β (beta) and α (alpha) are the parameters of the model that we must learn during MCMC. A logistic function with varying parameters is shown below. A logistic function fits the data because the probability of being asleep transitions gradually, capturing the variability in my sleep patterns. We want to be able to plug in a time t to the function and get out the probability of sleep, which must be between 0 and 1. Rather than a straight yes or no answer to the question am I asleep at 10:00 PM, we can get a probability. To create this model, we use the data to find the best alpha and beta parameters through one of the techniques classified as Markov Chain Monte Carlo. Markov Chain Monte Carlo refers to a class of methods for sampling from a probability distribution in order to construct the most likely distribution. We cannot directly calculate the logistic distribution, so instead we generate thousands of values — called samples — for the parameters of the function (alpha and beta) to create an approximation of the distribution. The idea behind MCMC is that as we generate more samples, our approximation gets closer and closer to the actual true distribution. There are two parts to a Markov Chain Monte Carlo method. Monte Carlo refers to a general technique of using repeated random samples to obtain a numerical answer. Monte Carlo can be thought of as carrying out many experiments, each time changing the variables in a model and observing the response. By choosing random values, we can explore a large portion of the parameter space, the range of possible values for the variables. A parameter space for our problem using normal priors for the variables (more on this in a moment) is shown below. Clearly we cannot try every single point in these plots, but by randomly sampling from regions of higher probability (red) we can create the most likely model for our problem. A Markov Chain is a process where the next state depends only on the current state. (A state in this context refers to the assignment of values to the parameters). A Markov Chain is memoryless because only the current state matters and not how it arrived in that state. If that’s a little difficult to understand, consider an everyday phenomenon, the weather. If we want to predict the weather tomorrow we can get a reasonable estimate using only the weather today. If it snowed today, we look at historical data showing the distribution of weather on the day after it snows to estimate probabilities of the weather tomorrow. The concept of a Markov Chain is that we do not need to know the entire history of a process to predict the next output, an approximation that works well in many real-world situations. Putting together the ideas of Markov Chain and Monte Carlo, MCMC is a method that repeatedly draws random values for the parameters of a distribution based on the current values. Each sample of values is random, but the choices for the values are limited by the current state and the assumed prior distribution of the parameters. MCMC can be considered as a random walk that gradually converges to the true distribution. In order to draw random values of alpha and beta, we need to assume a prior distribution for these values. As we have no assumptions about the parameters ahead of time, we can use a normal distribution. The normal, or Gaussian distribution, is defined by the mean, showing the location of the data, and the variance, showing the spread. Several normal distributions with different means and spreads are below: The specific MCMC algorithm we are using is called Metropolis Hastings. In order to connect our observed data to the model, every time a set of random values are drawn, the algorithm evaluates them against the data. If they do not agree with the data (I’m simplifying a little here), the values are rejected and the model remains in the current state. If the random values are in agreement with the data, the values are assigned to the parameters and become the current state. This process continues for a specified number of steps, with the accuracy of the model improving with the number of steps. Putting it all together, the basic procedure for Markov Chain Monte Carlo in our problem is as follows: Select an initial set of values for alpha and beta, the parameters of the logistic function.Randomly assign new values to alpha and beta based on the current state.Check if the new random values agree with the observations. If they do not, reject the values and return to the previous state. If they do, accept the values as the new current state.Repeat steps 2 and 3 for the specified number of iterations. Select an initial set of values for alpha and beta, the parameters of the logistic function. Randomly assign new values to alpha and beta based on the current state. Check if the new random values agree with the observations. If they do not, reject the values and return to the previous state. If they do, accept the values as the new current state. Repeat steps 2 and 3 for the specified number of iterations. The algorithm returns all of the values it generates for alpha and beta. We can then use the average of these values as the most likely final values for alpha and beta in the logistic function. MCMC cannot return the “True” value but rather an approximation for the distribution. The final model for the probability of sleep given the data will be the logistic function with the average values of alpha and beta. The above details went over my head many times until I applied them in Python! Seeing the results first-hand is a lot more helpful than reading someone else describe. To implement MCMC in Python, we will use the PyMC3 Bayesian inference library. It abstracts away most of the details, allowing us to create models without getting lost in the theory. The following code creates the full model with the parameters, alpha and beta, the probability, p, and the observations, observed The step variable refers to the specific algorithm, and the sleep_trace holds all of the values of the parameters generated by the model. (Check out the notebook for the full code) To get a sense of what occurs when we run this code, we can look at all the value of alpha and beta generated during the model run. These are called trace plots. We can see that each state is correlated to the previous — the Markov Chain — but the values oscillate significantly — the Monte Carlo sampling. In MCMC, it is common practice to discard up to 90% of the trace. The algorithm does not immediately converge to the true distribution and the initial values are often inaccurate. The later values for the parameters are generally better which means they are what we should use for building our model. We used 10000 samples and discarded the first 50%, but an industry application would likely use hundreds of thousands or millions of samples. MCMC converges to the true value given enough steps, but assessing convergence can be difficult. I will leave that topic out of this post (one way is by measuring the auto-correlation of the traces) but it is an important consideration if we want the most accurate results. PyMC3 has built in functions for assessing the quality of models, including trace and autocorrelation plots. pm.traceplot(sleep_trace, ['alpha', 'beta'])pm.autocorrplot(sleep_trace, ['alpha', 'beta']) After finally building and running the model, it’s time to use the results. We will the the average of the last 5000 alpha and beta samples as the most likely values for the parameters which allows us to create a single curve modeling the posterior sleep probability: The model represents the data well. Moreover, it captures the inherent variability in my sleep patterns. Rather than a single yes or no answer, the model gives us a probability. For example, we can query the model to find out the probability I am asleep at a given time and find the time at which the probability of being asleep passes 50%: 9:30 PM probability of being asleep: 4.80%.10:00 PM probability of being asleep: 27.44%.10:30 PM probability of being asleep: 73.91%.The probability of sleep increases to above 50% at 10:14 PM. Although I try to go to bed at 10:00 PM, that clearly does not happen most nights! We can see that the average time I go to bed is around 10:14 PM. These values are the most likely estimates given the data. However, there is uncertainty associated with these probabilities because the model is approximate. To represent this uncertainty, we can make predictions of the sleep probability at a given time using all of the alpha and beta samples instead of the average and then plot a histogram of the results. These results give a better indicator of what an MCMC model really does. The method does not find a single answer, but rather a sample of possible values. Bayesian Inference is useful in the real-world because it expresses predictions in terms of probabilities. We can say there is one most likely answer, but the more accurate response is that there are a range of values for any prediction. I can use the waking data to find a similar model for when I wake up in the morning. I try to always be up at 6:00 AM with my alarm, but we can see that does not always happen! The following image shows the final model for the transition from sleeping to waking along with the observations. We can query the model to find the probability I’m asleep at a given time and the most likely time for me to wake up. Probability of being awake at 5:30 AM: 14.10%. Probability of being awake at 6:00 AM: 37.94%. Probability of being awake at 6:30 AM: 69.49%.The probability of being awake passes 50% at 6:11 AM. Looks like I have some work to do with that alarm! A final model I wanted to create — both out of curiosity and for the practice — was my duration of sleep. First, we need to find a function to model the distribution of the data. Ahead of time, I think it would be normal, but we can only find out by examining the data! A normal distribution would work, but it would not capture the outlying points on the right side (times when I severely slept in). We could use two separate normal distributions to represent the two modes, but instead, I will use a skewed normal. The skewed normal has three parameters, the mean, the variance, and alpha, the skew. All three of these must be learned from the MCMC algorithm. The following code creates the model and implements the Metropolis Hastings sampling. Now, we can use the average values of the three parameters to construct the most likely distribution. Following is the final skewed normal distribution on top of the data. It looks like a nice fit! We can query the model to find the likelihood I get at least a certain amount of sleep and the most likely duration of sleep: Probability of at least 6.5 hours of sleep = 99.16%.Probability of at least 8.0 hours of sleep = 44.53%.Probability of at least 9.0 hours of sleep = 10.94%.The most likely duration of sleep is 7.67 hours. I’m not entirely pleased with those results, but what can you expect as a graduate student? Once again, completing this project showed me the importance of solving problems, preferably ones with real world applications! Along the way to building an end-to-end implementation of Bayesian Inference using Markov Chain Monte Carlo, I picked up many of the fundamentals and enjoyed myself in the process. Not only did I learn a little bit about my habits (and what I need to improve), but now I can finally understand what everyone is talking about when they say MCMC and Bayesian Inference. Data science is about constantly adding tools to your repertoire and the most effective way to do that is to find a problem and get started! As always, I welcome feedback and constructive criticism. I can be reached on Twitter @koehrsen_will.
[ { "code": null, "e": 208, "s": 171, "text": "A Complete Real-World Implementation" }, { "code": null, "e": 708, "s": 208, "text": "The past few months, I encountered one term again and again in the data science world: Markov Chain Monte Carlo. In my research lab, in podcasts, in articles, every time I heard the phrase I would nod and think that sounds pretty cool with only a vague idea of what anyone was talking about. Several times I tried to learn MCMC and Bayesian inference, but every time I started reading the books, I soon gave up. Exasperated, I turned to the best method to learn any new skill: apply it to a problem." }, { "code": null, "e": 1268, "s": 708, "text": "Using some of my sleep data I had been meaning to explore and a hands-on application-based book (Bayesian Methods for Hackers, available free online), I finally learned Markov Chain Monte Carlo through a real-world project. As usual, it was much easier (and more enjoyable) to understand the technical concepts when I applied them to a problem rather than reading them as abstract ideas on a page. This article walks through the introductory implementation of Markov Chain Monte Carlo in Python that finally taught me this powerful modeling and analysis tool." }, { "code": null, "e": 1557, "s": 1268, "text": "The full code and data for this project is on GitHub. I encourage anyone to take a look and use it on their own data. This article focuses on applications and results, so there are a lot of topics covered at a high level, but I have tried to provide links for those wanting to learn more!" }, { "code": null, "e": 1795, "s": 1557, "text": "My Garmin Vivosmart watch tracks when I fall asleep and wake up based on heart rate and motion. It’s not 100% accurate, but real-world data is never perfect, and we can still extract useful knowledge from noisy data with the right model!" }, { "code": null, "e": 2132, "s": 1795, "text": "The objective of this project was to use the sleep data to create a model that specifies the posterior probability of sleep as a function of time. As time is a continuous variable, specifying the entire posterior distribution is intractable, and we turn to methods to approximate a distribution, such as Markov Chain Monte Carlo (MCMC)." }, { "code": null, "e": 2408, "s": 2132, "text": "Before we can start with MCMC, we need to determine an appropriate function for modeling the posterior probability distribution of sleep. One simple way to do this is to visually inspect the data. The observations for when I fall asleep as a function of time are shown below." }, { "code": null, "e": 2900, "s": 2408, "text": "Every data point is represented as a dot, with the intensity of the dot showing the number of observations at the specific time. My watch records only the minute at which I fall asleep, so to expand the data, I added points to every minute on both sides of the precise time. If my watch says I fell asleep at 10:05 PM, then every minute before is represented as a 0 (awake) and every minute after gets a 1 (asleep). This expanded the roughly 60 nights of observations into 11340 data points." }, { "code": null, "e": 3589, "s": 2900, "text": "We can see that I tend to fall asleep a little after 10:00 PM but we want to create a model that captures the transition from awake to asleep in terms of a probability. We could use a simple step function for our model that changes from awake (0) to asleep (1) at one precise time, but this would not represent the uncertainty in the data. I do not go to sleep at the same time every night, and we need a function to that models the transition as a gradual process to show the variability. The best choice given the data is a logistic function which is smoothly transitions between the bounds of 0 and 1. Following is a logistic equation for the probability of sleep as a function of time" }, { "code": null, "e": 3742, "s": 3589, "text": "Here, β (beta) and α (alpha) are the parameters of the model that we must learn during MCMC. A logistic function with varying parameters is shown below." }, { "code": null, "e": 4269, "s": 3742, "text": "A logistic function fits the data because the probability of being asleep transitions gradually, capturing the variability in my sleep patterns. We want to be able to plug in a time t to the function and get out the probability of sleep, which must be between 0 and 1. Rather than a straight yes or no answer to the question am I asleep at 10:00 PM, we can get a probability. To create this model, we use the data to find the best alpha and beta parameters through one of the techniques classified as Markov Chain Monte Carlo." }, { "code": null, "e": 4770, "s": 4269, "text": "Markov Chain Monte Carlo refers to a class of methods for sampling from a probability distribution in order to construct the most likely distribution. We cannot directly calculate the logistic distribution, so instead we generate thousands of values — called samples — for the parameters of the function (alpha and beta) to create an approximation of the distribution. The idea behind MCMC is that as we generate more samples, our approximation gets closer and closer to the actual true distribution." }, { "code": null, "e": 5314, "s": 4770, "text": "There are two parts to a Markov Chain Monte Carlo method. Monte Carlo refers to a general technique of using repeated random samples to obtain a numerical answer. Monte Carlo can be thought of as carrying out many experiments, each time changing the variables in a model and observing the response. By choosing random values, we can explore a large portion of the parameter space, the range of possible values for the variables. A parameter space for our problem using normal priors for the variables (more on this in a moment) is shown below." }, { "code": null, "e": 5490, "s": 5314, "text": "Clearly we cannot try every single point in these plots, but by randomly sampling from regions of higher probability (red) we can create the most likely model for our problem." }, { "code": null, "e": 6301, "s": 5490, "text": "A Markov Chain is a process where the next state depends only on the current state. (A state in this context refers to the assignment of values to the parameters). A Markov Chain is memoryless because only the current state matters and not how it arrived in that state. If that’s a little difficult to understand, consider an everyday phenomenon, the weather. If we want to predict the weather tomorrow we can get a reasonable estimate using only the weather today. If it snowed today, we look at historical data showing the distribution of weather on the day after it snows to estimate probabilities of the weather tomorrow. The concept of a Markov Chain is that we do not need to know the entire history of a process to predict the next output, an approximation that works well in many real-world situations." }, { "code": null, "e": 6722, "s": 6301, "text": "Putting together the ideas of Markov Chain and Monte Carlo, MCMC is a method that repeatedly draws random values for the parameters of a distribution based on the current values. Each sample of values is random, but the choices for the values are limited by the current state and the assumed prior distribution of the parameters. MCMC can be considered as a random walk that gradually converges to the true distribution." }, { "code": null, "e": 7132, "s": 6722, "text": "In order to draw random values of alpha and beta, we need to assume a prior distribution for these values. As we have no assumptions about the parameters ahead of time, we can use a normal distribution. The normal, or Gaussian distribution, is defined by the mean, showing the location of the data, and the variance, showing the spread. Several normal distributions with different means and spreads are below:" }, { "code": null, "e": 7732, "s": 7132, "text": "The specific MCMC algorithm we are using is called Metropolis Hastings. In order to connect our observed data to the model, every time a set of random values are drawn, the algorithm evaluates them against the data. If they do not agree with the data (I’m simplifying a little here), the values are rejected and the model remains in the current state. If the random values are in agreement with the data, the values are assigned to the parameters and become the current state. This process continues for a specified number of steps, with the accuracy of the model improving with the number of steps." }, { "code": null, "e": 7836, "s": 7732, "text": "Putting it all together, the basic procedure for Markov Chain Monte Carlo in our problem is as follows:" }, { "code": null, "e": 8244, "s": 7836, "text": "Select an initial set of values for alpha and beta, the parameters of the logistic function.Randomly assign new values to alpha and beta based on the current state.Check if the new random values agree with the observations. If they do not, reject the values and return to the previous state. If they do, accept the values as the new current state.Repeat steps 2 and 3 for the specified number of iterations." }, { "code": null, "e": 8337, "s": 8244, "text": "Select an initial set of values for alpha and beta, the parameters of the logistic function." }, { "code": null, "e": 8410, "s": 8337, "text": "Randomly assign new values to alpha and beta based on the current state." }, { "code": null, "e": 8594, "s": 8410, "text": "Check if the new random values agree with the observations. If they do not, reject the values and return to the previous state. If they do, accept the values as the new current state." }, { "code": null, "e": 8655, "s": 8594, "text": "Repeat steps 2 and 3 for the specified number of iterations." }, { "code": null, "e": 9068, "s": 8655, "text": "The algorithm returns all of the values it generates for alpha and beta. We can then use the average of these values as the most likely final values for alpha and beta in the logistic function. MCMC cannot return the “True” value but rather an approximation for the distribution. The final model for the probability of sleep given the data will be the logistic function with the average values of alpha and beta." }, { "code": null, "e": 9418, "s": 9068, "text": "The above details went over my head many times until I applied them in Python! Seeing the results first-hand is a lot more helpful than reading someone else describe. To implement MCMC in Python, we will use the PyMC3 Bayesian inference library. It abstracts away most of the details, allowing us to create models without getting lost in the theory." }, { "code": null, "e": 9686, "s": 9418, "text": "The following code creates the full model with the parameters, alpha and beta, the probability, p, and the observations, observed The step variable refers to the specific algorithm, and the sleep_trace holds all of the values of the parameters generated by the model." }, { "code": null, "e": 9729, "s": 9686, "text": "(Check out the notebook for the full code)" }, { "code": null, "e": 9861, "s": 9729, "text": "To get a sense of what occurs when we run this code, we can look at all the value of alpha and beta generated during the model run." }, { "code": null, "e": 10036, "s": 9861, "text": "These are called trace plots. We can see that each state is correlated to the previous — the Markov Chain — but the values oscillate significantly — the Monte Carlo sampling." }, { "code": null, "e": 10479, "s": 10036, "text": "In MCMC, it is common practice to discard up to 90% of the trace. The algorithm does not immediately converge to the true distribution and the initial values are often inaccurate. The later values for the parameters are generally better which means they are what we should use for building our model. We used 10000 samples and discarded the first 50%, but an industry application would likely use hundreds of thousands or millions of samples." }, { "code": null, "e": 10862, "s": 10479, "text": "MCMC converges to the true value given enough steps, but assessing convergence can be difficult. I will leave that topic out of this post (one way is by measuring the auto-correlation of the traces) but it is an important consideration if we want the most accurate results. PyMC3 has built in functions for assessing the quality of models, including trace and autocorrelation plots." }, { "code": null, "e": 10954, "s": 10862, "text": "pm.traceplot(sleep_trace, ['alpha', 'beta'])pm.autocorrplot(sleep_trace, ['alpha', 'beta'])" }, { "code": null, "e": 11222, "s": 10954, "text": "After finally building and running the model, it’s time to use the results. We will the the average of the last 5000 alpha and beta samples as the most likely values for the parameters which allows us to create a single curve modeling the posterior sleep probability:" }, { "code": null, "e": 11563, "s": 11222, "text": "The model represents the data well. Moreover, it captures the inherent variability in my sleep patterns. Rather than a single yes or no answer, the model gives us a probability. For example, we can query the model to find out the probability I am asleep at a given time and find the time at which the probability of being asleep passes 50%:" }, { "code": null, "e": 11758, "s": 11563, "text": "9:30 PM probability of being asleep: 4.80%.10:00 PM probability of being asleep: 27.44%.10:30 PM probability of being asleep: 73.91%.The probability of sleep increases to above 50% at 10:14 PM." }, { "code": null, "e": 11906, "s": 11758, "text": "Although I try to go to bed at 10:00 PM, that clearly does not happen most nights! We can see that the average time I go to bed is around 10:14 PM." }, { "code": null, "e": 12266, "s": 11906, "text": "These values are the most likely estimates given the data. However, there is uncertainty associated with these probabilities because the model is approximate. To represent this uncertainty, we can make predictions of the sleep probability at a given time using all of the alpha and beta samples instead of the average and then plot a histogram of the results." }, { "code": null, "e": 12659, "s": 12266, "text": "These results give a better indicator of what an MCMC model really does. The method does not find a single answer, but rather a sample of possible values. Bayesian Inference is useful in the real-world because it expresses predictions in terms of probabilities. We can say there is one most likely answer, but the more accurate response is that there are a range of values for any prediction." }, { "code": null, "e": 12950, "s": 12659, "text": "I can use the waking data to find a similar model for when I wake up in the morning. I try to always be up at 6:00 AM with my alarm, but we can see that does not always happen! The following image shows the final model for the transition from sleeping to waking along with the observations." }, { "code": null, "e": 13068, "s": 12950, "text": "We can query the model to find the probability I’m asleep at a given time and the most likely time for me to wake up." }, { "code": null, "e": 13262, "s": 13068, "text": "Probability of being awake at 5:30 AM: 14.10%. Probability of being awake at 6:00 AM: 37.94%. Probability of being awake at 6:30 AM: 69.49%.The probability of being awake passes 50% at 6:11 AM." }, { "code": null, "e": 13313, "s": 13262, "text": "Looks like I have some work to do with that alarm!" }, { "code": null, "e": 13583, "s": 13313, "text": "A final model I wanted to create — both out of curiosity and for the practice — was my duration of sleep. First, we need to find a function to model the distribution of the data. Ahead of time, I think it would be normal, but we can only find out by examining the data!" }, { "code": null, "e": 14061, "s": 13583, "text": "A normal distribution would work, but it would not capture the outlying points on the right side (times when I severely slept in). We could use two separate normal distributions to represent the two modes, but instead, I will use a skewed normal. The skewed normal has three parameters, the mean, the variance, and alpha, the skew. All three of these must be learned from the MCMC algorithm. The following code creates the model and implements the Metropolis Hastings sampling." }, { "code": null, "e": 14233, "s": 14061, "text": "Now, we can use the average values of the three parameters to construct the most likely distribution. Following is the final skewed normal distribution on top of the data." }, { "code": null, "e": 14385, "s": 14233, "text": "It looks like a nice fit! We can query the model to find the likelihood I get at least a certain amount of sleep and the most likely duration of sleep:" }, { "code": null, "e": 14590, "s": 14385, "text": "Probability of at least 6.5 hours of sleep = 99.16%.Probability of at least 8.0 hours of sleep = 44.53%.Probability of at least 9.0 hours of sleep = 10.94%.The most likely duration of sleep is 7.67 hours." }, { "code": null, "e": 14682, "s": 14590, "text": "I’m not entirely pleased with those results, but what can you expect as a graduate student?" }, { "code": null, "e": 15319, "s": 14682, "text": "Once again, completing this project showed me the importance of solving problems, preferably ones with real world applications! Along the way to building an end-to-end implementation of Bayesian Inference using Markov Chain Monte Carlo, I picked up many of the fundamentals and enjoyed myself in the process. Not only did I learn a little bit about my habits (and what I need to improve), but now I can finally understand what everyone is talking about when they say MCMC and Bayesian Inference. Data science is about constantly adding tools to your repertoire and the most effective way to do that is to find a problem and get started!" } ]
MongoDB Insert() Method - db.Collection.insert() - GeeksforGeeks
28 Jan, 2021 In MongoDB, the insert() method inserts a document or documents into the collection. It takes two parameters, the first parameter is the document or array of the document that we want to insert and the remaining are optional. Using this method you can also create a collection by inserting documents. You can insert documents with or without _id field. If you insert a document in the collection without _id field, then MongoDB will automatically add an _id field and assign it with a unique ObjectId. And if you insert a document with _id field, then the value of the _id field must be unique to avoid the duplicate key error. This method can also be used inside multi-document transactions. Syntax: db.Collection_name.insert( <document or [document1, document2,...]>, { writeConcern: <document>, ordered: <boolean> }) Parameters: The first parameter is the document or an array of documents. Documents are a structure created of file and value pairs, similar to JSON objects. The second parameter is optional. Optional Parameters: writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document. ordered: The default value of this parameter is true. If it is true, it inserts documents in the ordered manner. Otherwise, it randomly inserts documents. Return: This method returns WriteResult when you insert single document in the collection. This method returns BulkWriteResult when you insert multiple documents in the collection. Examples: In the following examples, we are working with: Database: gfg Collection: student Document: No document but, we want to insert in the form of the student name and student marks. Here, we insert a document in the student collection whose name is Akshay and marks is 500 using insert() method. db.student.insert({Name: "Akshay", Marks: 500}) Output: Here, we insert multiple documents in the collection by passing an array of documents in the insert method. db.student.insert([{Name: "Bablu", Marks: 550}, {Name: "Chintu", Marks: 430}, {Name: "Devanshu", Marks: 499}]) Output: Here, we insert a document in the student collection with _id field. db.student.insert({_id: 102,Name: "Anup", Marks: 400}) Output: MongoDB-method Picked MongoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Aggregation in MongoDB Spring Boot JpaRepository with Example Mongoose Populate() Method MongoDB - db.collection.Find() Method MongoDB - Check the existence of the fields in the specified collection How to build a basic CRUD app with Node.js and ReactJS ? Upsert in MongoDB Mongoose | findById() Function How to connect MongoDB with ReactJS ? MongoDB - Distinct() Method
[ { "code": null, "e": 25066, "s": 25038, "text": "\n28 Jan, 2021" }, { "code": null, "e": 25292, "s": 25066, "text": "In MongoDB, the insert() method inserts a document or documents into the collection. It takes two parameters, the first parameter is the document or array of the document that we want to insert and the remaining are optional." }, { "code": null, "e": 25367, "s": 25292, "text": "Using this method you can also create a collection by inserting documents." }, { "code": null, "e": 25694, "s": 25367, "text": "You can insert documents with or without _id field. If you insert a document in the collection without _id field, then MongoDB will automatically add an _id field and assign it with a unique ObjectId. And if you insert a document with _id field, then the value of the _id field must be unique to avoid the duplicate key error." }, { "code": null, "e": 25759, "s": 25694, "text": "This method can also be used inside multi-document transactions." }, { "code": null, "e": 25767, "s": 25759, "text": "Syntax:" }, { "code": null, "e": 25794, "s": 25767, "text": "db.Collection_name.insert(" }, { "code": null, "e": 25836, "s": 25794, "text": "<document or [document1, document2,...]>," }, { "code": null, "e": 25838, "s": 25836, "text": "{" }, { "code": null, "e": 25868, "s": 25838, "text": " writeConcern: <document>," }, { "code": null, "e": 25891, "s": 25868, "text": " ordered: <boolean>" }, { "code": null, "e": 25894, "s": 25891, "text": "})" }, { "code": null, "e": 25906, "s": 25894, "text": "Parameters:" }, { "code": null, "e": 26052, "s": 25906, "text": "The first parameter is the document or an array of documents. Documents are a structure created of file and value pairs, similar to JSON objects." }, { "code": null, "e": 26086, "s": 26052, "text": "The second parameter is optional." }, { "code": null, "e": 26107, "s": 26086, "text": "Optional Parameters:" }, { "code": null, "e": 26234, "s": 26107, "text": "writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document." }, { "code": null, "e": 26389, "s": 26234, "text": "ordered: The default value of this parameter is true. If it is true, it inserts documents in the ordered manner. Otherwise, it randomly inserts documents." }, { "code": null, "e": 26397, "s": 26389, "text": "Return:" }, { "code": null, "e": 26480, "s": 26397, "text": "This method returns WriteResult when you insert single document in the collection." }, { "code": null, "e": 26570, "s": 26480, "text": "This method returns BulkWriteResult when you insert multiple documents in the collection." }, { "code": null, "e": 26580, "s": 26570, "text": "Examples:" }, { "code": null, "e": 26628, "s": 26580, "text": "In the following examples, we are working with:" }, { "code": null, "e": 26642, "s": 26628, "text": "Database: gfg" }, { "code": null, "e": 26662, "s": 26642, "text": "Collection: student" }, { "code": null, "e": 26758, "s": 26662, "text": "Document: No document but, we want to insert in the form of the student name and student marks." }, { "code": null, "e": 26872, "s": 26758, "text": "Here, we insert a document in the student collection whose name is Akshay and marks is 500 using insert() method." }, { "code": null, "e": 26920, "s": 26872, "text": "db.student.insert({Name: \"Akshay\", Marks: 500})" }, { "code": null, "e": 26928, "s": 26920, "text": "Output:" }, { "code": null, "e": 27036, "s": 26928, "text": "Here, we insert multiple documents in the collection by passing an array of documents in the insert method." }, { "code": null, "e": 27178, "s": 27036, "text": "db.student.insert([{Name: \"Bablu\", Marks: 550}, \n {Name: \"Chintu\", Marks: 430},\n {Name: \"Devanshu\", Marks: 499}])" }, { "code": null, "e": 27186, "s": 27178, "text": "Output:" }, { "code": null, "e": 27255, "s": 27186, "text": "Here, we insert a document in the student collection with _id field." }, { "code": null, "e": 27310, "s": 27255, "text": "db.student.insert({_id: 102,Name: \"Anup\", Marks: 400})" }, { "code": null, "e": 27318, "s": 27310, "text": "Output:" }, { "code": null, "e": 27333, "s": 27318, "text": "MongoDB-method" }, { "code": null, "e": 27340, "s": 27333, "text": "Picked" }, { "code": null, "e": 27348, "s": 27340, "text": "MongoDB" }, { "code": null, "e": 27446, "s": 27348, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27455, "s": 27446, "text": "Comments" }, { "code": null, "e": 27468, "s": 27455, "text": "Old Comments" }, { "code": null, "e": 27491, "s": 27468, "text": "Aggregation in MongoDB" }, { "code": null, "e": 27530, "s": 27491, "text": "Spring Boot JpaRepository with Example" }, { "code": null, "e": 27557, "s": 27530, "text": "Mongoose Populate() Method" }, { "code": null, "e": 27595, "s": 27557, "text": "MongoDB - db.collection.Find() Method" }, { "code": null, "e": 27667, "s": 27595, "text": "MongoDB - Check the existence of the fields in the specified collection" }, { "code": null, "e": 27724, "s": 27667, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 27742, "s": 27724, "text": "Upsert in MongoDB" }, { "code": null, "e": 27773, "s": 27742, "text": "Mongoose | findById() Function" }, { "code": null, "e": 27811, "s": 27773, "text": "How to connect MongoDB with ReactJS ?" } ]
Center element of matrix equals sums of half diagonals - GeeksforGeeks
26 Apr, 2021 Given a matrix of odd order i.e(5*5). Task is to check if the center element of the matrix is equal to the individual sum of all the half diagonals. Examples: Input : mat[][] = { 2 9 1 4 -2 6 7 2 11 4 4 2 9 2 4 1 9 2 4 4 0 2 4 2 5 } Output :Yes Explanation : Sum of Half Diagonal 1 = 2 + 7 = 9 Sum of Half Diagonal 2 = 9 + 0 = 9 Sum of Half Diagonal 3 = 11 + -2 = 9 Sum of Half Diagonal 4 = 5 + 4 = 9 Here, All the sums equal to the center element that is mat[2][2] = 9 Simple Approach: Iterate two loops, find all half diagonal sums and then check all sums are equal to the center element of the matrix or not. If any one of them is not equal to center element Then print “No” Else “Yes”. Time Complexity: O(N*N) Efficient Approach : is based on Efficient approach to find diagonal sum in O(N) . Below are the Implementation of this approach C++ Java Python 3 C# PHP Javascript // C++ Program to check if the center// element is equal to the individual// sum of all the half diagonals#include <stdio.h>#include<bits/stdc++.h>using namespace std; const int MAX = 100; // Function to Check center element// is equal to the individual// sum of all the half diagonalsbool HalfDiagonalSums(int mat[][MAX], int n){ // Find sums of half diagonals int diag1_left = 0, diag1_right = 0; int diag2_left = 0, diag2_right = 0; for (int i = 0, j = n - 1; i < n; i++, j--) { if (i < n/2) { diag1_left += mat[i][i]; diag2_left += mat[j][i]; } else if (i > n/2) { diag1_right += mat[i][i]; diag2_right += mat[j][i]; } } return (diag1_left == diag2_right && diag2_right == diag2_left && diag1_right == diag2_left && diag2_right == mat[n/2][n/2]);} // Driver codeint main(){ int a[][MAX] = { { 2, 9, 1, 4, -2}, { 6, 7, 2, 11, 4}, { 4, 2, 9, 2, 4}, { 1, 9, 2, 4, 4}, { 0, 2, 4, 2, 5} }; cout << ( HalfDiagonalSums(a, 5) ? "Yes" : "No" ); return 0;} // Java program to find maximum elements// that can be made equal with k updatesimport java.util.Arrays;public class GFG { static int MAX = 100; // Function to Check center element // is equal to the individual // sum of all the half diagonals static boolean HalfDiagonalSums(int mat[][], int n) { // Find sums of half diagonals int diag1_left = 0, diag1_right = 0; int diag2_left = 0, diag2_right = 0; for (int i = 0, j = n - 1; i < n; i++, j--) { if (i < n/2) { diag1_left += mat[i][i]; diag2_left += mat[j][i]; } else if (i > n/2) { diag1_right += mat[i][i]; diag2_right += mat[j][i]; } } return (diag1_left == diag2_right && diag2_right == diag2_left && diag1_right == diag2_left && diag2_right == mat[n/2][n/2]); } // Driver code public static void main(String args[]) { int a[][] = { { 2, 9, 1, 4, -2}, { 6, 7, 2, 11, 4}, { 4, 2, 9, 2, 4}, { 1, 9, 2, 4, 4}, { 0, 2, 4, 2, 5} }; System.out.print ( HalfDiagonalSums(a, 5) ? "Yes" : "No" ); }} // This code is contributed by Sam007 # Python 3 Program to check if the center# element is equal to the individual# sum of all the half diagonals MAX = 100 # Function to Check center element# is equal to the individual# sum of all the half diagonalsdef HalfDiagonalSums( mat, n): # Find sums of half diagonals diag1_left = 0 diag1_right = 0 diag2_left = 0 diag2_right = 0 i = 0 j = n - 1 while i < n: if (i < n//2) : diag1_left += mat[i][i] diag2_left += mat[j][i] elif (i > n//2) : diag1_right += mat[i][i] diag2_right += mat[j][i] i += 1 j -= 1 return (diag1_left == diag2_right and diag2_right == diag2_left and diag1_right == diag2_left and diag2_right == mat[n//2][n//2]) # Driver codeif __name__ == "__main__": a = [[2, 9, 1, 4, -2], [6, 7, 2, 11, 4], [ 4, 2, 9, 2, 4], [1, 9, 2, 4, 4 ], [ 0, 2, 4, 2, 5]] print("Yes") if (HalfDiagonalSums(a, 5)) else print("No" ) // C# program to find maximum// elements that can be made// equal with k updatesusing System; class GFG{ // Function to Check // center element is // equal to the individual // sum of all the half // diagonals static bool HalfDiagonalSums(int [,]mat, int n) { // Find sums of // half diagonals int diag1_left = 0, diag1_right = 0; int diag2_left = 0, diag2_right = 0; for (int i = 0, j = n - 1; i < n; i++, j--) { if (i < n / 2) { diag1_left += mat[i, i]; diag2_left += mat[j, i]; } else if (i > n / 2) { diag1_right += mat[i, i]; diag2_right += mat[j, i]; } } return (diag1_left == diag2_right && diag2_right == diag2_left && diag1_right == diag2_left && diag2_right == mat[n / 2, n / 2]); } // Driver code static public void Main () { int [,]a = {{ 2, 9, 1, 4, -2}, { 6, 7, 2, 11, 4}, { 4, 2, 9, 2, 4}, { 1, 9, 2, 4, 4}, { 0, 2, 4, 2, 5}}; Console.WriteLine(HalfDiagonalSums(a, 5)? "Yes" : "No" ); }} // This code is contributed by ajit <?php// PHP Program to check if// the center element is// equal to the individual// sum of all the half diagonals$MAX = 100; // Function to Check center// element is equal to the// individual sum of all// the half diagonalsfunction HalfDiagonalSums($mat, $n){ global $MAX ; // Find sums of // half diagonals $diag1_left = 1; $diag1_right = 1; $diag2_left = 1; $diag2_right = 1; for ($i = 0, $j = $n - 1; $i < $n; $i++, $j--) { if ($i < $n / 2) { $diag1_left += $mat[$i][$i]; $diag2_left += $mat[$j][$i]; } else if ($i > $n / 2) { $diag1_right += $mat[$i][$i]; $diag2_right += $mat[$j][$i]; } } return ($diag1_left == $diag2_right && $diag2_right == $diag2_left && $diag1_right == $diag2_left && $diag2_right == $mat[$n / 2][$n / 2]);} // Driver code$a = array(array(2, 9, 1, 4, -2), array(6, 7, 2, 11, 4), array(4, 2, 9, 2, 4), array(1, 9, 2, 4, 4), array(0, 2, 4, 2, 5));if(HalfDiagonalSums($a, 5) == 0) echo "Yes" ;else echo "No" ; // This code is contributed// by akt_mit?> <script>// Javascript Program to check if the center// element is equal to the individual// sum of all the half diagonals const MAX = 100; // Function to Check center element// is equal to the individual// sum of all the half diagonalsfunction HalfDiagonalSums(mat, n){ // Find sums of half diagonals let diag1_left = 0, diag1_right = 0; let diag2_left = 0, diag2_right = 0; for (let i = 0, j = n - 1; i < n; i++, j--) { if (i < parseInt(n/2)) { diag1_left += mat[i][i]; diag2_left += mat[j][i]; } else if (i > parseInt(n/2)) { diag1_right += mat[i][i]; diag2_right += mat[j][i]; } } return (diag1_left == diag2_right && diag2_right == diag2_left && diag1_right == diag2_left && diag2_right == mat[parseInt(n/2)][parseInt(n/2)]);} // Driver code let a = [ [ 2, 9, 1, 4, -2], [ 6, 7, 2, 11, 4], [ 4, 2, 9, 2, 4], [ 1, 9, 2, 4, 4], [ 0, 2, 4, 2, 5] ]; document.write( HalfDiagonalSums(a, 5) ? "Yes" : "No" ); // This code is contributed by subham348.</script> Yes Time Complexity : O(N) Sam007 jit_t ukasp subham348 Matrix Misc Technical Scripter Misc Misc Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inplace rotate square matrix by 90 degrees | Set 1 Count all possible paths from top left to bottom right of a mXn matrix Min Cost Path | DP-6 Printing all solutions in N-Queen Problem Efficiently compute sums of diagonals of a matrix Top 10 algorithms in Interview Questions vector::push_back() and vector::pop_back() in C++ STL Overview of Data Structures | Set 1 (Linear Data Structures) How to write Regular Expressions? Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)
[ { "code": null, "e": 26370, "s": 26342, "text": "\n26 Apr, 2021" }, { "code": null, "e": 26521, "s": 26370, "text": "Given a matrix of odd order i.e(5*5). Task is to check if the center element of the matrix is equal to the individual sum of all the half diagonals. " }, { "code": null, "e": 26533, "s": 26521, "text": "Examples: " }, { "code": null, "e": 26975, "s": 26533, "text": "Input : mat[][] = { 2 9 1 4 -2\n 6 7 2 11 4\n 4 2 9 2 4\n 1 9 2 4 4\n 0 2 4 2 5 } \nOutput :Yes\nExplanation : \nSum of Half Diagonal 1 = 2 + 7 = 9\nSum of Half Diagonal 2 = 9 + 0 = 9\nSum of Half Diagonal 3 = 11 + -2 = 9\nSum of Half Diagonal 4 = 5 + 4 = 9\n\nHere, All the sums equal to the center element\nthat is mat[2][2] = 9" }, { "code": null, "e": 27352, "s": 26977, "text": "Simple Approach: Iterate two loops, find all half diagonal sums and then check all sums are equal to the center element of the matrix or not. If any one of them is not equal to center element Then print “No” Else “Yes”. Time Complexity: O(N*N) Efficient Approach : is based on Efficient approach to find diagonal sum in O(N) . Below are the Implementation of this approach " }, { "code": null, "e": 27356, "s": 27352, "text": "C++" }, { "code": null, "e": 27361, "s": 27356, "text": "Java" }, { "code": null, "e": 27370, "s": 27361, "text": "Python 3" }, { "code": null, "e": 27373, "s": 27370, "text": "C#" }, { "code": null, "e": 27377, "s": 27373, "text": "PHP" }, { "code": null, "e": 27388, "s": 27377, "text": "Javascript" }, { "code": "// C++ Program to check if the center// element is equal to the individual// sum of all the half diagonals#include <stdio.h>#include<bits/stdc++.h>using namespace std; const int MAX = 100; // Function to Check center element// is equal to the individual// sum of all the half diagonalsbool HalfDiagonalSums(int mat[][MAX], int n){ // Find sums of half diagonals int diag1_left = 0, diag1_right = 0; int diag2_left = 0, diag2_right = 0; for (int i = 0, j = n - 1; i < n; i++, j--) { if (i < n/2) { diag1_left += mat[i][i]; diag2_left += mat[j][i]; } else if (i > n/2) { diag1_right += mat[i][i]; diag2_right += mat[j][i]; } } return (diag1_left == diag2_right && diag2_right == diag2_left && diag1_right == diag2_left && diag2_right == mat[n/2][n/2]);} // Driver codeint main(){ int a[][MAX] = { { 2, 9, 1, 4, -2}, { 6, 7, 2, 11, 4}, { 4, 2, 9, 2, 4}, { 1, 9, 2, 4, 4}, { 0, 2, 4, 2, 5} }; cout << ( HalfDiagonalSums(a, 5) ? \"Yes\" : \"No\" ); return 0;}", "e": 28595, "s": 27388, "text": null }, { "code": "// Java program to find maximum elements// that can be made equal with k updatesimport java.util.Arrays;public class GFG { static int MAX = 100; // Function to Check center element // is equal to the individual // sum of all the half diagonals static boolean HalfDiagonalSums(int mat[][], int n) { // Find sums of half diagonals int diag1_left = 0, diag1_right = 0; int diag2_left = 0, diag2_right = 0; for (int i = 0, j = n - 1; i < n; i++, j--) { if (i < n/2) { diag1_left += mat[i][i]; diag2_left += mat[j][i]; } else if (i > n/2) { diag1_right += mat[i][i]; diag2_right += mat[j][i]; } } return (diag1_left == diag2_right && diag2_right == diag2_left && diag1_right == diag2_left && diag2_right == mat[n/2][n/2]); } // Driver code public static void main(String args[]) { int a[][] = { { 2, 9, 1, 4, -2}, { 6, 7, 2, 11, 4}, { 4, 2, 9, 2, 4}, { 1, 9, 2, 4, 4}, { 0, 2, 4, 2, 5} }; System.out.print ( HalfDiagonalSums(a, 5) ? \"Yes\" : \"No\" ); }} // This code is contributed by Sam007", "e": 30110, "s": 28595, "text": null }, { "code": "# Python 3 Program to check if the center# element is equal to the individual# sum of all the half diagonals MAX = 100 # Function to Check center element# is equal to the individual# sum of all the half diagonalsdef HalfDiagonalSums( mat, n): # Find sums of half diagonals diag1_left = 0 diag1_right = 0 diag2_left = 0 diag2_right = 0 i = 0 j = n - 1 while i < n: if (i < n//2) : diag1_left += mat[i][i] diag2_left += mat[j][i] elif (i > n//2) : diag1_right += mat[i][i] diag2_right += mat[j][i] i += 1 j -= 1 return (diag1_left == diag2_right and diag2_right == diag2_left and diag1_right == diag2_left and diag2_right == mat[n//2][n//2]) # Driver codeif __name__ == \"__main__\": a = [[2, 9, 1, 4, -2], [6, 7, 2, 11, 4], [ 4, 2, 9, 2, 4], [1, 9, 2, 4, 4 ], [ 0, 2, 4, 2, 5]] print(\"Yes\") if (HalfDiagonalSums(a, 5)) else print(\"No\" )", "e": 31175, "s": 30110, "text": null }, { "code": "// C# program to find maximum// elements that can be made// equal with k updatesusing System; class GFG{ // Function to Check // center element is // equal to the individual // sum of all the half // diagonals static bool HalfDiagonalSums(int [,]mat, int n) { // Find sums of // half diagonals int diag1_left = 0, diag1_right = 0; int diag2_left = 0, diag2_right = 0; for (int i = 0, j = n - 1; i < n; i++, j--) { if (i < n / 2) { diag1_left += mat[i, i]; diag2_left += mat[j, i]; } else if (i > n / 2) { diag1_right += mat[i, i]; diag2_right += mat[j, i]; } } return (diag1_left == diag2_right && diag2_right == diag2_left && diag1_right == diag2_left && diag2_right == mat[n / 2, n / 2]); } // Driver code static public void Main () { int [,]a = {{ 2, 9, 1, 4, -2}, { 6, 7, 2, 11, 4}, { 4, 2, 9, 2, 4}, { 1, 9, 2, 4, 4}, { 0, 2, 4, 2, 5}}; Console.WriteLine(HalfDiagonalSums(a, 5)? \"Yes\" : \"No\" ); }} // This code is contributed by ajit", "e": 32640, "s": 31175, "text": null }, { "code": "<?php// PHP Program to check if// the center element is// equal to the individual// sum of all the half diagonals$MAX = 100; // Function to Check center// element is equal to the// individual sum of all// the half diagonalsfunction HalfDiagonalSums($mat, $n){ global $MAX ; // Find sums of // half diagonals $diag1_left = 1; $diag1_right = 1; $diag2_left = 1; $diag2_right = 1; for ($i = 0, $j = $n - 1; $i < $n; $i++, $j--) { if ($i < $n / 2) { $diag1_left += $mat[$i][$i]; $diag2_left += $mat[$j][$i]; } else if ($i > $n / 2) { $diag1_right += $mat[$i][$i]; $diag2_right += $mat[$j][$i]; } } return ($diag1_left == $diag2_right && $diag2_right == $diag2_left && $diag1_right == $diag2_left && $diag2_right == $mat[$n / 2][$n / 2]);} // Driver code$a = array(array(2, 9, 1, 4, -2), array(6, 7, 2, 11, 4), array(4, 2, 9, 2, 4), array(1, 9, 2, 4, 4), array(0, 2, 4, 2, 5));if(HalfDiagonalSums($a, 5) == 0) echo \"Yes\" ;else echo \"No\" ; // This code is contributed// by akt_mit?>", "e": 33856, "s": 32640, "text": null }, { "code": "<script>// Javascript Program to check if the center// element is equal to the individual// sum of all the half diagonals const MAX = 100; // Function to Check center element// is equal to the individual// sum of all the half diagonalsfunction HalfDiagonalSums(mat, n){ // Find sums of half diagonals let diag1_left = 0, diag1_right = 0; let diag2_left = 0, diag2_right = 0; for (let i = 0, j = n - 1; i < n; i++, j--) { if (i < parseInt(n/2)) { diag1_left += mat[i][i]; diag2_left += mat[j][i]; } else if (i > parseInt(n/2)) { diag1_right += mat[i][i]; diag2_right += mat[j][i]; } } return (diag1_left == diag2_right && diag2_right == diag2_left && diag1_right == diag2_left && diag2_right == mat[parseInt(n/2)][parseInt(n/2)]);} // Driver code let a = [ [ 2, 9, 1, 4, -2], [ 6, 7, 2, 11, 4], [ 4, 2, 9, 2, 4], [ 1, 9, 2, 4, 4], [ 0, 2, 4, 2, 5] ]; document.write( HalfDiagonalSums(a, 5) ? \"Yes\" : \"No\" ); // This code is contributed by subham348.</script>", "e": 35067, "s": 33856, "text": null }, { "code": null, "e": 35071, "s": 35067, "text": "Yes" }, { "code": null, "e": 35098, "s": 35073, "text": "Time Complexity : O(N) " }, { "code": null, "e": 35105, "s": 35098, "text": "Sam007" }, { "code": null, "e": 35111, "s": 35105, "text": "jit_t" }, { "code": null, "e": 35117, "s": 35111, "text": "ukasp" }, { "code": null, "e": 35127, "s": 35117, "text": "subham348" }, { "code": null, "e": 35134, "s": 35127, "text": "Matrix" }, { "code": null, "e": 35139, "s": 35134, "text": "Misc" }, { "code": null, "e": 35158, "s": 35139, "text": "Technical Scripter" }, { "code": null, "e": 35163, "s": 35158, "text": "Misc" }, { "code": null, "e": 35168, "s": 35163, "text": "Misc" }, { "code": null, "e": 35175, "s": 35168, "text": "Matrix" }, { "code": null, "e": 35273, "s": 35175, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35324, "s": 35273, "text": "Inplace rotate square matrix by 90 degrees | Set 1" }, { "code": null, "e": 35395, "s": 35324, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 35416, "s": 35395, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 35458, "s": 35416, "text": "Printing all solutions in N-Queen Problem" }, { "code": null, "e": 35508, "s": 35458, "text": "Efficiently compute sums of diagonals of a matrix" }, { "code": null, "e": 35549, "s": 35508, "text": "Top 10 algorithms in Interview Questions" }, { "code": null, "e": 35603, "s": 35549, "text": "vector::push_back() and vector::pop_back() in C++ STL" }, { "code": null, "e": 35664, "s": 35603, "text": "Overview of Data Structures | Set 1 (Linear Data Structures)" }, { "code": null, "e": 35698, "s": 35664, "text": "How to write Regular Expressions?" } ]
End-to-end breast cancer detection with Python — Part 1 | by Jordan Van Eetveldt | Towards Data Science
According to cancer.org, breast cancer is the most common cancer in American women. In the US, there is a 1 in 8 chance that a woman will develop breast cancer. In this series of articles we will show how deep learning and image processing can be applied to detect malignant breast masses. We will first focus on detecting breast masses (part1), then we will segment them (part2) and finally we will classify whether a mass is benign or malignant (part3). There exists two types of mammography: Film-screen and more recently Full-Field Digital Mammography. In this article I used the INbreast dataset. It contains 115 cases with a total of 410 Full-Field Digital Mammography in DICOM format. There are four different types of breast diseases recorded in the database, including Mass, Calcification, Asymmetry, and Distortion. Only mass lesions were selected, resulting in 106 images. Each image is coupled with accurate contours made by specialists in XML format. For the detection part, as we don’t need to segment the mass, the contours were converted into bounding boxes. Below you can find the code that convert a mask of the lesions to YOLO format annotations: Here are shown some samples from the dataset with corresponding generated bounding boxes: As we can see a lot of pixels are background pixels which bring no information. To avoid the proportion of mass pixels from being underrepresented we can crop the ROI, that is the breast region. This can be done with OpenCV and Otsu’s thresholding technique: Then I applied 3 preprocessing steps inspired by [1]. These 3 steps consist of: Truncation normalization Image enhancement Image synthesizing Even after cropping, the image is still composed of many black pixels. This may have negative effects on the detection if we normalize the image as it is (because the breast region will appear less intense). Here the goal is to normalize the intensity distribution of the pixels in the breast region. You can refer to the original article to see algorithm details [1]. Below I provide my implementation in python: To enhance the contrast of the breast region and so the mass lesion, Contrast Limited Adaptive Histogram Equalization (CLAHE) algorithm is applied with clip limit 1 and 2: After applying these 3 steps, the mass lesions appear much clearly. This will improve Yolov4 accuracy. In the final step, a 3-channel image is synthesized and composed of the truncated and normalized image, the contrast enhanced image with clip limit 1, and the contrast enhanced image with clip limit 2 [1]. YOLOv4 has been used to perform mass detection on the enhanced images. It is a one stage detector particularly efficient when context is needed compared to two stages detector. As explained in [1], when background is independent from foreground, two stages detectors are useful as the first stage extracts ROI. However Cao, H [1] mentioned that in breast mass detection, lesions are not independent from the breast region and therefore one stage detectors may be more efficient. To correctly evaluate the performance of the algorithm I split the data-set into 3 parts: Train set is composed of 80% of the images Validation set is composed of 10% of the images Test set is composed of 10% of the images As the resulting train set is small, data augmentation has been applied (only on the train set). Each image has been augmented 8 times with random rotation, flip and shift. YOLO takes care of other augmentations such as Mosaic data augmentation etc; see [2]. I performed a 2-fold cross validation using the same procedure explained above. To evaluate the detector, I used the recall and the False Negative rate (FNR) metrics. Note that in cancer detection it is very important to have a very low FNR and a high recall (otherwise we miss a potential cancer). A detection is considered as a True Positive (TP) if the Intersection Over Union (IOU) between the predicted bounding box and the ground truth is greater than 0.25. Also a bounding box is considered only if its confidence is greater that 0.25. The results have been evaluated on the validation and test sets. Validation set evaluation+--------+----+----+----+--------+------+| | TP | FP | FN | Recall | FNR |+--------+----+----+----+--------+------+| Fold 1 | 10 | 3 | 1 | 0.91 | 0.07 || Fold 2 | 11 | 1 | 1 | 0.92 | 0.08 |+--------+----+----+----+--------+------+ Test set evaluation+--------+----+----+----+--------+------+| | TP | FP | FN | Recall | FNR |+--------+----+----+----+--------+------+| Fold 1 | 12 | 1 | 0 | 1 | 0 || Fold 2 | 11 | 4 | 2 | 0.85 | 0.13 |+--------+----+----+----+--------+------+ YOLOv4 appears to be highly efficient in breast mass detection. I achieve 92% mean recall on the validation and test sets which correspond to state-of-the-art results in the literature ([1] achieved 91.3% recall). The model seems to struggle a little bit on small mass lesions in the fold2 test set. I trained Yolov4 on a 8GB nvidia RTX 2080 GPU. This forces me to limit the image size to 512x512. Having more resources and data could allow us to train the algorithm on more powerful models such as the state-of-the-art YOLOv4-P7 and with higher resolution images. This should improve accuracy on small mass regions. Here are the results on the test set (unseen images) during both folds: We have trained a highly accurate breast mass detector in python with YOLOv4. This has been possible partly thanks to an efficient image preprocessing step. Results are really promising and similar to those in the literature. In the next articles, we will see how to segment the mass. Having already a detector being able to crop the masses will be useful to train the segmentation model only on the mass regions. Then we will classify whether a mass is malignant. Stay tuned ;) Note: I provide the script to create the dataset and my config file for training YOLO on my github :) [1] Cao, H. (2020). Breast mass detection in digital mammography based on anchor-free architecture. ArXiv, abs/2009.00857. [2] Bochkovskiy, A., Wang, C., & Liao, H. (2020). YOLOv4: Optimal Speed and Accuracy of Object Detection. ArXiv, abs/2004.10934. [3] Al-Antari MA, Al-Masni MA, Choi MT, Han SM, Kim TS. A fully integrated computer-aided diagnosis system for digital X-ray mammograms via deep learning detection, segmentation, and classification. International Journal of Medical Informatics. 2018 Sep;117:44–54. DOI: 10.1016/j.ijmedinf.2018.06.003.
[ { "code": null, "e": 628, "s": 172, "text": "According to cancer.org, breast cancer is the most common cancer in American women. In the US, there is a 1 in 8 chance that a woman will develop breast cancer. In this series of articles we will show how deep learning and image processing can be applied to detect malignant breast masses. We will first focus on detecting breast masses (part1), then we will segment them (part2) and finally we will classify whether a mass is benign or malignant (part3)." }, { "code": null, "e": 1338, "s": 628, "text": "There exists two types of mammography: Film-screen and more recently Full-Field Digital Mammography. In this article I used the INbreast dataset. It contains 115 cases with a total of 410 Full-Field Digital Mammography in DICOM format. There are four different types of breast diseases recorded in the database, including Mass, Calcification, Asymmetry, and Distortion. Only mass lesions were selected, resulting in 106 images. Each image is coupled with accurate contours made by specialists in XML format. For the detection part, as we don’t need to segment the mass, the contours were converted into bounding boxes. Below you can find the code that convert a mask of the lesions to YOLO format annotations:" }, { "code": null, "e": 1428, "s": 1338, "text": "Here are shown some samples from the dataset with corresponding generated bounding boxes:" }, { "code": null, "e": 1687, "s": 1428, "text": "As we can see a lot of pixels are background pixels which bring no information. To avoid the proportion of mass pixels from being underrepresented we can crop the ROI, that is the breast region. This can be done with OpenCV and Otsu’s thresholding technique:" }, { "code": null, "e": 1767, "s": 1687, "text": "Then I applied 3 preprocessing steps inspired by [1]. These 3 steps consist of:" }, { "code": null, "e": 1792, "s": 1767, "text": "Truncation normalization" }, { "code": null, "e": 1810, "s": 1792, "text": "Image enhancement" }, { "code": null, "e": 1829, "s": 1810, "text": "Image synthesizing" }, { "code": null, "e": 2243, "s": 1829, "text": "Even after cropping, the image is still composed of many black pixels. This may have negative effects on the detection if we normalize the image as it is (because the breast region will appear less intense). Here the goal is to normalize the intensity distribution of the pixels in the breast region. You can refer to the original article to see algorithm details [1]. Below I provide my implementation in python:" }, { "code": null, "e": 2415, "s": 2243, "text": "To enhance the contrast of the breast region and so the mass lesion, Contrast Limited Adaptive Histogram Equalization (CLAHE) algorithm is applied with clip limit 1 and 2:" }, { "code": null, "e": 2724, "s": 2415, "text": "After applying these 3 steps, the mass lesions appear much clearly. This will improve Yolov4 accuracy. In the final step, a 3-channel image is synthesized and composed of the truncated and normalized image, the contrast enhanced image with clip limit 1, and the contrast enhanced image with clip limit 2 [1]." }, { "code": null, "e": 3293, "s": 2724, "text": "YOLOv4 has been used to perform mass detection on the enhanced images. It is a one stage detector particularly efficient when context is needed compared to two stages detector. As explained in [1], when background is independent from foreground, two stages detectors are useful as the first stage extracts ROI. However Cao, H [1] mentioned that in breast mass detection, lesions are not independent from the breast region and therefore one stage detectors may be more efficient. To correctly evaluate the performance of the algorithm I split the data-set into 3 parts:" }, { "code": null, "e": 3336, "s": 3293, "text": "Train set is composed of 80% of the images" }, { "code": null, "e": 3384, "s": 3336, "text": "Validation set is composed of 10% of the images" }, { "code": null, "e": 3426, "s": 3384, "text": "Test set is composed of 10% of the images" }, { "code": null, "e": 3765, "s": 3426, "text": "As the resulting train set is small, data augmentation has been applied (only on the train set). Each image has been augmented 8 times with random rotation, flip and shift. YOLO takes care of other augmentations such as Mosaic data augmentation etc; see [2]. I performed a 2-fold cross validation using the same procedure explained above." }, { "code": null, "e": 4293, "s": 3765, "text": "To evaluate the detector, I used the recall and the False Negative rate (FNR) metrics. Note that in cancer detection it is very important to have a very low FNR and a high recall (otherwise we miss a potential cancer). A detection is considered as a True Positive (TP) if the Intersection Over Union (IOU) between the predicted bounding box and the ground truth is greater than 0.25. Also a bounding box is considered only if its confidence is greater that 0.25. The results have been evaluated on the validation and test sets." }, { "code": null, "e": 4850, "s": 4293, "text": " Validation set evaluation+--------+----+----+----+--------+------+| | TP | FP | FN | Recall | FNR |+--------+----+----+----+--------+------+| Fold 1 | 10 | 3 | 1 | 0.91 | 0.07 || Fold 2 | 11 | 1 | 1 | 0.92 | 0.08 |+--------+----+----+----+--------+------+ Test set evaluation+--------+----+----+----+--------+------+| | TP | FP | FN | Recall | FNR |+--------+----+----+----+--------+------+| Fold 1 | 12 | 1 | 0 | 1 | 0 || Fold 2 | 11 | 4 | 2 | 0.85 | 0.13 |+--------+----+----+----+--------+------+" }, { "code": null, "e": 5539, "s": 4850, "text": "YOLOv4 appears to be highly efficient in breast mass detection. I achieve 92% mean recall on the validation and test sets which correspond to state-of-the-art results in the literature ([1] achieved 91.3% recall). The model seems to struggle a little bit on small mass lesions in the fold2 test set. I trained Yolov4 on a 8GB nvidia RTX 2080 GPU. This forces me to limit the image size to 512x512. Having more resources and data could allow us to train the algorithm on more powerful models such as the state-of-the-art YOLOv4-P7 and with higher resolution images. This should improve accuracy on small mass regions. Here are the results on the test set (unseen images) during both folds:" }, { "code": null, "e": 6018, "s": 5539, "text": "We have trained a highly accurate breast mass detector in python with YOLOv4. This has been possible partly thanks to an efficient image preprocessing step. Results are really promising and similar to those in the literature. In the next articles, we will see how to segment the mass. Having already a detector being able to crop the masses will be useful to train the segmentation model only on the mass regions. Then we will classify whether a mass is malignant. Stay tuned ;)" }, { "code": null, "e": 6120, "s": 6018, "text": "Note: I provide the script to create the dataset and my config file for training YOLO on my github :)" }, { "code": null, "e": 6243, "s": 6120, "text": "[1] Cao, H. (2020). Breast mass detection in digital mammography based on anchor-free architecture. ArXiv, abs/2009.00857." }, { "code": null, "e": 6372, "s": 6243, "text": "[2] Bochkovskiy, A., Wang, C., & Liao, H. (2020). YOLOv4: Optimal Speed and Accuracy of Object Detection. ArXiv, abs/2004.10934." } ]
Python Syntax
As we learned in the previous page, Python syntax can be executed by writing directly in the Command Line: Or by creating a python file on the server, using the .py file extension, and running it in the Command Line: Indentation refers to the spaces at the beginning of a code line. Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important. Python uses indentation to indicate a block of code. Python will give you an error if you skip the indentation: Syntax Error: The number of spaces is up to you as a programmer, the most common use is four, but it has to be at least one. You have to use the same number of spaces in the same block of code, otherwise Python will give you an error: Syntax Error: In Python, variables are created when you assign a value to it: Variables in Python: Python has no command for declaring a variable. You will learn more about variables in the Python Variables chapter. Python has commenting capability for the purpose of in-code documentation. Comments start with a #, and Python will render the rest of the line as a comment: Comments in Python: Insert the missing part of the code below to output "Hello World". ("Hello World") Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 107, "s": 0, "text": "As we learned in the previous page, Python syntax can be executed by writing directly in the Command Line:" }, { "code": null, "e": 217, "s": 107, "text": "Or by creating a python file on the server, using the .py file extension, and running it in the Command Line:" }, { "code": null, "e": 283, "s": 217, "text": "Indentation refers to the spaces at the beginning of a code line." }, { "code": null, "e": 415, "s": 283, "text": "Where in other programming languages the indentation in code is for readability \nonly, the indentation in Python is very important." }, { "code": null, "e": 468, "s": 415, "text": "Python uses indentation to indicate a block of code." }, { "code": null, "e": 527, "s": 468, "text": "Python will give you an error if you skip the indentation:" }, { "code": null, "e": 541, "s": 527, "text": "Syntax Error:" }, { "code": null, "e": 653, "s": 541, "text": "The number of spaces is up to you as a programmer, the most common use is four, but it has \nto be at least one." }, { "code": null, "e": 764, "s": 653, "text": "You have to use the same number of spaces in the same block of code, \notherwise Python will give you an error:" }, { "code": null, "e": 778, "s": 764, "text": "Syntax Error:" }, { "code": null, "e": 843, "s": 778, "text": "In Python, variables are created when you assign a value to it:\n" }, { "code": null, "e": 864, "s": 843, "text": "Variables in Python:" }, { "code": null, "e": 912, "s": 864, "text": "Python has no command for declaring a variable." }, { "code": null, "e": 982, "s": 912, "text": "You will learn more about variables in the \nPython Variables chapter." }, { "code": null, "e": 1057, "s": 982, "text": "Python has commenting capability for the purpose of in-code documentation." }, { "code": null, "e": 1141, "s": 1057, "text": "Comments start with a #, and Python will render the rest of the line as a comment:\n" }, { "code": null, "e": 1161, "s": 1141, "text": "Comments in Python:" }, { "code": null, "e": 1228, "s": 1161, "text": "Insert the missing part of the code below to output \"Hello World\"." }, { "code": null, "e": 1245, "s": 1228, "text": "(\"Hello World\")\n" }, { "code": null, "e": 1264, "s": 1245, "text": "Start the Exercise" }, { "code": null, "e": 1297, "s": 1264, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1339, "s": 1297, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1446, "s": 1339, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1465, "s": 1446, "text": "[email protected]" } ]
Calculating and Setting Thresholds to Optimise Logistic Regression Performance | by Graham Harrison | Towards Data Science
I had learned about logistic regression, confusion matrices, ROC curves, thresholds etc. on the various data science courses I have undertaken but I never fully understood them and wanted to explore them in more detail. Also, I had seen various examples online about how to recalculate the true and false classifications given a chosen threshold but these examples fell short of the detail I needed to put thresholds to work in the real world. I suspected there might be a way to wrap threshold optimisation into a simple, object-oriented class so I could use them easily in future hence this article documents my learning journey to achieve these objectives. Let’s start by importing the libraries we will need ... We will also need some data to operate on. The data I selected was the bank credit default data from Kaggle — https://www.kaggle.com/c/credit-default-prediction-ai-big-data/overview. I have performed some cleaning of that data including dealing with the null values, converting the categorical features and balancing the data to evenly represent the true and false classifications which is outside of the scope of this article. The data imported below includes all of those data cleaning steps ... Let’s complete the preparation by splitting the data into testing and training so we can optimise against the training data and come back to the test data later on ... ((4754, 32), (1189, 32), (4754,), (1189,)) OK, let’s fit a basic LogisticRegression to the test data and then review the results ... array([0, 0, 0, ..., 1, 0, 0], dtype=int64) A visualisation of the confusion matrix will help us to evaluate the performance ... The banking data is being used to predict customers who will go on to default against their credit agreements and those who will not default. We can see straight away that a basic logistic regression has 79% accuracy having predicted 352 customers that will default and 3395 customers who will not. That sounds pretty good right? Well if I was one of the managers taking delivery of this algorithm my immediate question would be — “what about the 934 false negatives?”. There are nearly a 1000 customers that the algorithm did not predict as defaulting who went on to default. If the average cost of a default account to the bank is £10,000 my data science team has just cost the business £9.34m and I would definitely not be happy with that! This simple analysis reveals three key points - The accuracy measure may not always be the best way to evaluate the performance of a classification algorithm. The way in which a classification algorithm is optimised is heavily dependent on what the business is trying to achieve. The algorithm must be appropriately optimised to achieve the desired business outcomes. A bit more digging will reveal all of the key metrics for the performance of our basic algorithm - accuracy = 0.7881783761043332 precision = 0.8282352941176471 recall = 0.2737169517884914 f1 score = 0.4114552893045003 true positive rate (tpr) = 0.2737169517884914 false positive rate (fpr) = 0.02104959630911188 tpr-fpr = 0.2526673554793796 I would also usually take a look at the ROC (Receiver Operating Characteristic) curve - The black dot represents one interpretation of the optimum point. One measure that can be used is for calculating the optimum point on a ROC curve is TPR−FPR where TPR= True Positive Rate and FPR= False Positive Rate. The point at which the TPR−FPR is at its maximum value is the optimum point. The graph is showing that if we set the threshold of the logistic regression to 0.31261 instead of the default which is 0.5 then we optimise the logistic regression algorithm for TPR−FPR. If all this talk of thresholds is confusing there are many online articles that will explain the details, but the easiest way of envisaging it is this - Each row of our data will be classified as Default=True or Default=False. The logistic regression assigns each row a probability of bring True and then makes a prediction for each row where that prbability is >= 0.5 i.e. 0.5 is the default threshold. Once we understand a bit more about how this works we can play around with that 0.5 default to improve and optimise the outcome of our predictive algorithm. From this quick analysis, the evidence suggests we can do better than accepting the default threshold of 0.5 that is implemented within the LogisticRegression algorithm that is part of the sklearn.linear_model library. For example, we already know that if we change that default to 0.31261 we will optimise for TPR−FPRTPR−FPR. However, there is no easy way to change the threshold within the LogisticRegression class and typically data scientists will do this bit manually and duplicate effort across multiple projects. What we need is a simple class that will do this for us every time we want to optimise the threshold. Here is my first attempt at writing a class that extends the LogisticRegression class to optimise the threshold based on the TPR−FPRTPR−FPR calcualtion. It consists of a class definition, a method called threshold_from_optimal_tpr_minus_fpr and a predict method which over-rides the base class method enabling the threshold parameter to be passed in ... Armed with this new utility class we can now easily fit the training data to it, ask the class to tell us the optimal threshold for TPR−FPRTPR−FPR and then use that threshold to return a new set of predictions ... (0.3126109044627986, 0.3383474055618039) Well, this optimisation has certainly changed the shape of the outcomes as shown by the confusion matrix. The false negatives and true negatives have reduced whilst the false positives and true positives have increased. This finding led me to ask the question — “what other approaches are there to optimisation?” Another way of evaluating the outcomes of a classification algorithm is to plot the precision and recall for the confusion matrix rather than the FPR and TPR. As a quick reminder, precision and recall are calculated as follows - I.e. Precision is the right hand column of the confusion matrix and precision is the bottom row. Whereas TPR−FPR is commonly used to pick the optimum point on the ROC curve, the F1 score can be used to pick the optimum point on the precision-recall curve. The F1 Score is calculated as follows - The F1 score is the harmonic mean of precision and recall. We use the harmonic mean instead of a simple average because it punishes extreme values. The plot of precision vs. recall for our default algorithm looks like this - Here we can see that the optimum (i.e. the maximum) F1 score is 0.5237148537347345 with the optimum precision and recall being 0.41 and 0.72 respectively. The threshold that would produce this outcome from the algorithm is 0.3126109044627986 This second attempt at extending the LogisticRegression class added a new method for optimising for the F1 score to produce the optimal precision and threshold values - Now we can easily use the new version of the class to tell me what the threshold needs to be to optimise the f1 score and then to use that value to fine-tune the algorithm for the optimum precision and recall ... (0.3126109044627986, 0.5237148537347345) This version has significantly reduced the false negatives and represents the maximum possible optimisation of precision and recall. Now imagine I took the new model back to the management team at the bank and they said “Well, that is an improvement but we absolutely have to have a recall of 90% for this model to be effective”. Remember, recall is TP/(TP+FN) and at the moment this model has 922 / (364+922) = 71.7%. We would need to explain to the management team that recall and precision are trade offs so if the model is tuned for 90% recall the precision must decrease but if that were acceptable, how could this be achieved? This third attempt adds two new methods to calculate the required threshold for a given specific recall (and precision) which can now be used to achieve the performance requested by the management team - (0.19142214362243234, 0.35382262996941893) We can see that the recall requested by the management team has been achieved and that as a result the precision has been traded off from 41.3% to 35.4%. At this point, I was getting rather carried away and I wanted a version of the optimisation that would implement a custom cost function. Let’s suppose the management team now give us the following new information - Every true negative means we can sell £10,000 of additional credit products to customers who will not default. Every false positive costs us £1,000 because we could have engaged those customers but instead, we avoided them. Every false negative costs us £1,500 because we failed to intervene and stop those customers defaulting. Every true positive helps us to prevent credit default and each one generates £20,000 of new income. A “cost function” to implement this can easily be constructed - And with a bit more work we can modify our class to work out the threshold required to optimise this cost function and then apply it - ... which can be used as follows - (0.4324142856743824, -40033500) The new confusion matrix looks like this .. ... and here is the plot of our custom cost function values vs. the threshold values ... Given that I had realised that the threshold for optimal accuracy could be calculated using a very similar approach to that for a custom cost function, I thought I would add that into the final version. After all, many of the data science competitions do evaluate based on accuracy even though I had come to consider that it is not always, and in fact not often, the best measure of effectiveness of a classification algorithm. That being said when I plugged the threshold for optimum accuracy calculated using the training data into the test data it lifted the accuracy measure of the predictions by a whole 1% and in a data science competition that might just make a difference! The final version of the LogisticRegressionWithThreshold class adds a new method to calculate the threshold needed to optimize accuracy - (0.5654501621491699, 0.7968026924694994) Here is the confusion matrix for the optimal (highest) accuracy ... ... and here is the plot of accuracy vs. threshold ... We have seen that there are many ways to optimise a logistic regression which incidentally can be applied to other classification algorithms. These optimisations include finding and setting thresholds for the optimisation of precision, recall, f1 score, accuracy, tpr — fpr or custom cost functions. We have also seen that the chosen optimisation is heavily dependent on the desired business outcomes. We have seen that the LogisticRegression class in sklearn.linear_model does not have a way to set the threshold so that the algorithm can be optimised but that we can use the LogististicRegressionWithThreshold class developed in this article to give us instant access to all the functionality necessary to tune the base algorithm according to the desired business outcomes. The full code can be found on GitHub using this link - github.com If you enjoyed reading this article, why not check out my other articles at https://grahamharrison-86487.medium.com/? Also, I would love to hear from you to get your thoughts on this piece, any of my other articles or anything else related to data science and data analytics. If you would like to get in touch to discuss any of these topics please look me up on LinkedIn — https://www.linkedin.com/in/grahamharrison1 or feel free to e-mail me at [email protected].
[ { "code": null, "e": 391, "s": 171, "text": "I had learned about logistic regression, confusion matrices, ROC curves, thresholds etc. on the various data science courses I have undertaken but I never fully understood them and wanted to explore them in more detail." }, { "code": null, "e": 615, "s": 391, "text": "Also, I had seen various examples online about how to recalculate the true and false classifications given a chosen threshold but these examples fell short of the detail I needed to put thresholds to work in the real world." }, { "code": null, "e": 831, "s": 615, "text": "I suspected there might be a way to wrap threshold optimisation into a simple, object-oriented class so I could use them easily in future hence this article documents my learning journey to achieve these objectives." }, { "code": null, "e": 887, "s": 831, "text": "Let’s start by importing the libraries we will need ..." }, { "code": null, "e": 1070, "s": 887, "text": "We will also need some data to operate on. The data I selected was the bank credit default data from Kaggle — https://www.kaggle.com/c/credit-default-prediction-ai-big-data/overview." }, { "code": null, "e": 1385, "s": 1070, "text": "I have performed some cleaning of that data including dealing with the null values, converting the categorical features and balancing the data to evenly represent the true and false classifications which is outside of the scope of this article. The data imported below includes all of those data cleaning steps ..." }, { "code": null, "e": 1553, "s": 1385, "text": "Let’s complete the preparation by splitting the data into testing and training so we can optimise against the training data and come back to the test data later on ..." }, { "code": null, "e": 1596, "s": 1553, "text": "((4754, 32), (1189, 32), (4754,), (1189,))" }, { "code": null, "e": 1686, "s": 1596, "text": "OK, let’s fit a basic LogisticRegression to the test data and then review the results ..." }, { "code": null, "e": 1730, "s": 1686, "text": "array([0, 0, 0, ..., 1, 0, 0], dtype=int64)" }, { "code": null, "e": 1815, "s": 1730, "text": "A visualisation of the confusion matrix will help us to evaluate the performance ..." }, { "code": null, "e": 1957, "s": 1815, "text": "The banking data is being used to predict customers who will go on to default against their credit agreements and those who will not default." }, { "code": null, "e": 2114, "s": 1957, "text": "We can see straight away that a basic logistic regression has 79% accuracy having predicted 352 customers that will default and 3395 customers who will not." }, { "code": null, "e": 2392, "s": 2114, "text": "That sounds pretty good right? Well if I was one of the managers taking delivery of this algorithm my immediate question would be — “what about the 934 false negatives?”. There are nearly a 1000 customers that the algorithm did not predict as defaulting who went on to default." }, { "code": null, "e": 2558, "s": 2392, "text": "If the average cost of a default account to the bank is £10,000 my data science team has just cost the business £9.34m and I would definitely not be happy with that!" }, { "code": null, "e": 2606, "s": 2558, "text": "This simple analysis reveals three key points -" }, { "code": null, "e": 2717, "s": 2606, "text": "The accuracy measure may not always be the best way to evaluate the performance of a classification algorithm." }, { "code": null, "e": 2838, "s": 2717, "text": "The way in which a classification algorithm is optimised is heavily dependent on what the business is trying to achieve." }, { "code": null, "e": 2926, "s": 2838, "text": "The algorithm must be appropriately optimised to achieve the desired business outcomes." }, { "code": null, "e": 3025, "s": 2926, "text": "A bit more digging will reveal all of the key metrics for the performance of our basic algorithm -" }, { "code": null, "e": 3086, "s": 3025, "text": "accuracy = 0.7881783761043332 precision = 0.8282352941176471" }, { "code": null, "e": 3114, "s": 3086, "text": "recall = 0.2737169517884914" }, { "code": null, "e": 3144, "s": 3114, "text": "f1 score = 0.4114552893045003" }, { "code": null, "e": 3190, "s": 3144, "text": "true positive rate (tpr) = 0.2737169517884914" }, { "code": null, "e": 3238, "s": 3190, "text": "false positive rate (fpr) = 0.02104959630911188" }, { "code": null, "e": 3267, "s": 3238, "text": "tpr-fpr = 0.2526673554793796" }, { "code": null, "e": 3355, "s": 3267, "text": "I would also usually take a look at the ROC (Receiver Operating Characteristic) curve -" }, { "code": null, "e": 3421, "s": 3355, "text": "The black dot represents one interpretation of the optimum point." }, { "code": null, "e": 3650, "s": 3421, "text": "One measure that can be used is for calculating the optimum point on a ROC curve is TPR−FPR where TPR= True Positive Rate and FPR= False Positive Rate. The point at which the TPR−FPR is at its maximum value is the optimum point." }, { "code": null, "e": 3838, "s": 3650, "text": "The graph is showing that if we set the threshold of the logistic regression to 0.31261 instead of the default which is 0.5 then we optimise the logistic regression algorithm for TPR−FPR." }, { "code": null, "e": 3991, "s": 3838, "text": "If all this talk of thresholds is confusing there are many online articles that will explain the details, but the easiest way of envisaging it is this -" }, { "code": null, "e": 4242, "s": 3991, "text": "Each row of our data will be classified as Default=True or Default=False. The logistic regression assigns each row a probability of bring True and then makes a prediction for each row where that prbability is >= 0.5 i.e. 0.5 is the default threshold." }, { "code": null, "e": 4399, "s": 4242, "text": "Once we understand a bit more about how this works we can play around with that 0.5 default to improve and optimise the outcome of our predictive algorithm." }, { "code": null, "e": 4726, "s": 4399, "text": "From this quick analysis, the evidence suggests we can do better than accepting the default threshold of 0.5 that is implemented within the LogisticRegression algorithm that is part of the sklearn.linear_model library. For example, we already know that if we change that default to 0.31261 we will optimise for TPR−FPRTPR−FPR." }, { "code": null, "e": 4919, "s": 4726, "text": "However, there is no easy way to change the threshold within the LogisticRegression class and typically data scientists will do this bit manually and duplicate effort across multiple projects." }, { "code": null, "e": 5021, "s": 4919, "text": "What we need is a simple class that will do this for us every time we want to optimise the threshold." }, { "code": null, "e": 5375, "s": 5021, "text": "Here is my first attempt at writing a class that extends the LogisticRegression class to optimise the threshold based on the TPR−FPRTPR−FPR calcualtion. It consists of a class definition, a method called threshold_from_optimal_tpr_minus_fpr and a predict method which over-rides the base class method enabling the threshold parameter to be passed in ..." }, { "code": null, "e": 5589, "s": 5375, "text": "Armed with this new utility class we can now easily fit the training data to it, ask the class to tell us the optimal threshold for TPR−FPRTPR−FPR and then use that threshold to return a new set of predictions ..." }, { "code": null, "e": 5630, "s": 5589, "text": "(0.3126109044627986, 0.3383474055618039)" }, { "code": null, "e": 5850, "s": 5630, "text": "Well, this optimisation has certainly changed the shape of the outcomes as shown by the confusion matrix. The false negatives and true negatives have reduced whilst the false positives and true positives have increased." }, { "code": null, "e": 5943, "s": 5850, "text": "This finding led me to ask the question — “what other approaches are there to optimisation?”" }, { "code": null, "e": 6102, "s": 5943, "text": "Another way of evaluating the outcomes of a classification algorithm is to plot the precision and recall for the confusion matrix rather than the FPR and TPR." }, { "code": null, "e": 6172, "s": 6102, "text": "As a quick reminder, precision and recall are calculated as follows -" }, { "code": null, "e": 6269, "s": 6172, "text": "I.e. Precision is the right hand column of the confusion matrix and precision is the bottom row." }, { "code": null, "e": 6468, "s": 6269, "text": "Whereas TPR−FPR is commonly used to pick the optimum point on the ROC curve, the F1 score can be used to pick the optimum point on the precision-recall curve. The F1 Score is calculated as follows -" }, { "code": null, "e": 6616, "s": 6468, "text": "The F1 score is the harmonic mean of precision and recall. We use the harmonic mean instead of a simple average because it punishes extreme values." }, { "code": null, "e": 6693, "s": 6616, "text": "The plot of precision vs. recall for our default algorithm looks like this -" }, { "code": null, "e": 6935, "s": 6693, "text": "Here we can see that the optimum (i.e. the maximum) F1 score is 0.5237148537347345 with the optimum precision and recall being 0.41 and 0.72 respectively. The threshold that would produce this outcome from the algorithm is 0.3126109044627986" }, { "code": null, "e": 7104, "s": 6935, "text": "This second attempt at extending the LogisticRegression class added a new method for optimising for the F1 score to produce the optimal precision and threshold values -" }, { "code": null, "e": 7317, "s": 7104, "text": "Now we can easily use the new version of the class to tell me what the threshold needs to be to optimise the f1 score and then to use that value to fine-tune the algorithm for the optimum precision and recall ..." }, { "code": null, "e": 7358, "s": 7317, "text": "(0.3126109044627986, 0.5237148537347345)" }, { "code": null, "e": 7491, "s": 7358, "text": "This version has significantly reduced the false negatives and represents the maximum possible optimisation of precision and recall." }, { "code": null, "e": 7688, "s": 7491, "text": "Now imagine I took the new model back to the management team at the bank and they said “Well, that is an improvement but we absolutely have to have a recall of 90% for this model to be effective”." }, { "code": null, "e": 7777, "s": 7688, "text": "Remember, recall is TP/(TP+FN) and at the moment this model has 922 / (364+922) = 71.7%." }, { "code": null, "e": 7991, "s": 7777, "text": "We would need to explain to the management team that recall and precision are trade offs so if the model is tuned for 90% recall the precision must decrease but if that were acceptable, how could this be achieved?" }, { "code": null, "e": 8195, "s": 7991, "text": "This third attempt adds two new methods to calculate the required threshold for a given specific recall (and precision) which can now be used to achieve the performance requested by the management team -" }, { "code": null, "e": 8238, "s": 8195, "text": "(0.19142214362243234, 0.35382262996941893)" }, { "code": null, "e": 8392, "s": 8238, "text": "We can see that the recall requested by the management team has been achieved and that as a result the precision has been traded off from 41.3% to 35.4%." }, { "code": null, "e": 8529, "s": 8392, "text": "At this point, I was getting rather carried away and I wanted a version of the optimisation that would implement a custom cost function." }, { "code": null, "e": 8607, "s": 8529, "text": "Let’s suppose the management team now give us the following new information -" }, { "code": null, "e": 8718, "s": 8607, "text": "Every true negative means we can sell £10,000 of additional credit products to customers who will not default." }, { "code": null, "e": 8831, "s": 8718, "text": "Every false positive costs us £1,000 because we could have engaged those customers but instead, we avoided them." }, { "code": null, "e": 8936, "s": 8831, "text": "Every false negative costs us £1,500 because we failed to intervene and stop those customers defaulting." }, { "code": null, "e": 9037, "s": 8936, "text": "Every true positive helps us to prevent credit default and each one generates £20,000 of new income." }, { "code": null, "e": 9101, "s": 9037, "text": "A “cost function” to implement this can easily be constructed -" }, { "code": null, "e": 9236, "s": 9101, "text": "And with a bit more work we can modify our class to work out the threshold required to optimise this cost function and then apply it -" }, { "code": null, "e": 9271, "s": 9236, "text": "... which can be used as follows -" }, { "code": null, "e": 9303, "s": 9271, "text": "(0.4324142856743824, -40033500)" }, { "code": null, "e": 9347, "s": 9303, "text": "The new confusion matrix looks like this .." }, { "code": null, "e": 9436, "s": 9347, "text": "... and here is the plot of our custom cost function values vs. the threshold values ..." }, { "code": null, "e": 9639, "s": 9436, "text": "Given that I had realised that the threshold for optimal accuracy could be calculated using a very similar approach to that for a custom cost function, I thought I would add that into the final version." }, { "code": null, "e": 9864, "s": 9639, "text": "After all, many of the data science competitions do evaluate based on accuracy even though I had come to consider that it is not always, and in fact not often, the best measure of effectiveness of a classification algorithm." }, { "code": null, "e": 10117, "s": 9864, "text": "That being said when I plugged the threshold for optimum accuracy calculated using the training data into the test data it lifted the accuracy measure of the predictions by a whole 1% and in a data science competition that might just make a difference!" }, { "code": null, "e": 10255, "s": 10117, "text": "The final version of the LogisticRegressionWithThreshold class adds a new method to calculate the threshold needed to optimize accuracy -" }, { "code": null, "e": 10296, "s": 10255, "text": "(0.5654501621491699, 0.7968026924694994)" }, { "code": null, "e": 10364, "s": 10296, "text": "Here is the confusion matrix for the optimal (highest) accuracy ..." }, { "code": null, "e": 10419, "s": 10364, "text": "... and here is the plot of accuracy vs. threshold ..." }, { "code": null, "e": 10719, "s": 10419, "text": "We have seen that there are many ways to optimise a logistic regression which incidentally can be applied to other classification algorithms. These optimisations include finding and setting thresholds for the optimisation of precision, recall, f1 score, accuracy, tpr — fpr or custom cost functions." }, { "code": null, "e": 10821, "s": 10719, "text": "We have also seen that the chosen optimisation is heavily dependent on the desired business outcomes." }, { "code": null, "e": 11195, "s": 10821, "text": "We have seen that the LogisticRegression class in sklearn.linear_model does not have a way to set the threshold so that the algorithm can be optimised but that we can use the LogististicRegressionWithThreshold class developed in this article to give us instant access to all the functionality necessary to tune the base algorithm according to the desired business outcomes." }, { "code": null, "e": 11250, "s": 11195, "text": "The full code can be found on GitHub using this link -" }, { "code": null, "e": 11261, "s": 11250, "text": "github.com" }, { "code": null, "e": 11379, "s": 11261, "text": "If you enjoyed reading this article, why not check out my other articles at https://grahamharrison-86487.medium.com/?" }, { "code": null, "e": 11537, "s": 11379, "text": "Also, I would love to hear from you to get your thoughts on this piece, any of my other articles or anything else related to data science and data analytics." } ]
How to subtract one data frame from another in R?
If we have two data frames with same number of columns of same data type and equal number of rows then we might want to find the difference between the corresponding values of the data frames. To do this, we simply need to use minus sign. For example, if we have data-frames df1 and df2 then the subtraction can be found as df1-df2. Consider the below data frame − Live Demo x1<-rpois(20,5) x2<-rpois(20,8) df1<-data.frame(x1,x2) df1 x1 x2 1 8 9 2 3 10 3 5 4 4 3 10 5 6 4 6 4 11 7 6 4 8 4 14 9 8 13 10 5 8 11 7 7 12 8 9 13 3 4 14 6 12 15 3 9 16 11 10 17 3 4 18 5 10 19 10 7 20 7 10 Live Demo y1<-sample(0:10,20,replace=TRUE) y2<-sample(0:10,20,replace=TRUE) df2<-data.frame(y1,y2) df2 y1 y2 1 6 9 2 0 3 3 2 5 4 7 6 5 2 9 6 8 3 7 4 9 8 4 1 9 4 1 10 1 2 11 3 0 12 5 7 13 3 4 14 1 6 15 8 8 16 6 9 17 7 3 18 9 4 19 5 0 20 9 8 Subtracting df2 from df1 − df1-df2 x1 x2 1 5 2 2 6 4 3 2 6 4 0 -4 5 2 0 6 1 3 7 2 -2 8 3 11 9 1 5 10 5 1 11 0 4 12 -5 -3 13 3 7 14 2 -3 15 -3 8 16 2 2 17 3 6 18 -6 7 19 -1 4 20 2 -2 Let’s have a look at another example − Subtracting df2 from df1 − Live Demo V1<-rpois(20,1) V2<-rpois(20,10) V3<-rpois(20,12) df_V<-data.frame(V1,V2,V3) df_V V1 V2 V3 1 0 6 13 2 3 9 13 3 1 9 14 4 3 12 10 5 1 11 4 6 1 5 11 7 1 5 17 8 1 9 7 9 2 14 13 10 1 4 16 11 0 8 9 12 1 6 9 13 3 12 3 14 1 11 18 15 1 5 13 16 0 13 12 17 1 11 12 18 1 9 6 19 0 10 12 20 0 10 13 Live Demo W1<-sample(0:5,20,replace=TRUE) W2<-sample(0:10,20,replace=TRUE) W3<-sample(0:15,20,replace=TRUE) df_W<-data.frame(W1,W2,W3) df_W W1 W2 W3 1 0 8 14 2 3 2 5 3 3 2 10 4 0 1 9 5 1 9 8 6 1 5 12 7 3 2 13 8 1 9 7 9 0 5 2 10 1 9 12 11 3 1 0 12 4 10 0 13 4 2 0 14 4 4 13 15 5 3 15 16 2 6 0 17 4 1 14 18 0 7 10 19 1 4 15 20 2 0 15 Subtracting df_W from df_V − df_V-df_W V1 V2 V3 1 -5 5 12 2 -3 12 7 3 0 10 7 4 -1 9 14 5 -2 6 17 6 2 -2 4 7 0 7 5 8 0 2 -1 9 -1 6 -4 10 -2 5 -4 11 -3 0 7 12 -2 11 -4 13 -3 2 -1 14 0 3 - 3 15 -1 7 2 16 2 2 9 17 -3 6 2 18 -2 -2 -1 19 2 6 14 20 -3 10 4
[ { "code": null, "e": 1395, "s": 1062, "text": "If we have two data frames with same number of columns of same data type and equal number of rows then we might want to find the difference between the corresponding values of the data frames. To do this, we simply need to use minus sign. For example, if we have data-frames df1 and df2 then the subtraction can be found as df1-df2." }, { "code": null, "e": 1427, "s": 1395, "text": "Consider the below data frame −" }, { "code": null, "e": 1438, "s": 1427, "text": " Live Demo" }, { "code": null, "e": 1497, "s": 1438, "text": "x1<-rpois(20,5)\nx2<-rpois(20,8)\ndf1<-data.frame(x1,x2)\ndf1" }, { "code": null, "e": 1645, "s": 1497, "text": "x1 x2\n1 8 9\n2 3 10\n3 5 4\n4 3 10\n5 6 4\n6 4 11\n7 6 4\n8 4 14\n9 8 13\n10 5 8\n11 7 7\n12 8 9\n13 3 4\n14 6 12\n15 3 9\n16 11 10\n17 3 4\n18 5 10\n19 10 7\n20 7 10" }, { "code": null, "e": 1656, "s": 1645, "text": " Live Demo" }, { "code": null, "e": 1749, "s": 1656, "text": "y1<-sample(0:10,20,replace=TRUE)\ny2<-sample(0:10,20,replace=TRUE)\ndf2<-data.frame(y1,y2)\ndf2" }, { "code": null, "e": 1886, "s": 1749, "text": "y1 y2\n1 6 9\n2 0 3\n3 2 5\n4 7 6\n5 2 9\n6 8 3\n7 4 9\n8 4 1\n9 4 1\n10 1 2\n11 3 0\n12 5 7\n13 3 4\n14 1 6\n15 8 8\n16 6 9\n17 7 3\n18 9 4\n19 5 0\n20 9 8" }, { "code": null, "e": 1913, "s": 1886, "text": "Subtracting df2 from df1 −" }, { "code": null, "e": 1921, "s": 1913, "text": "df1-df2" }, { "code": null, "e": 2069, "s": 1921, "text": "x1 x2\n1 5 2\n2 6 4\n3 2 6\n4 0 -4\n 5 2 0\n6 1 3\n7 2 -2\n8 3 11\n9 1 5\n10 5 1\n11 0 4\n12 -5 -3\n13 3 7\n14 2 -3\n15 -3 8\n16 2 2\n17 3 6\n18 -6 7\n19 -1 4\n20 2 -2" }, { "code": null, "e": 2108, "s": 2069, "text": "Let’s have a look at another example −" }, { "code": null, "e": 2135, "s": 2108, "text": "Subtracting df2 from df1 −" }, { "code": null, "e": 2146, "s": 2135, "text": " Live Demo" }, { "code": null, "e": 2228, "s": 2146, "text": "V1<-rpois(20,1)\nV2<-rpois(20,10)\nV3<-rpois(20,12)\ndf_V<-data.frame(V1,V2,V3)\ndf_V" }, { "code": null, "e": 2431, "s": 2228, "text": "V1 V2 V3\n1 0 6 13\n2 3 9 13\n3 1 9 14\n4 3 12 10\n5 1 11 4\n6 1 5 11\n7 1 5 17\n8 1 9 7\n9 2 14 13\n10 1 4 16\n11 0 8 9\n12 1 6 9\n13 3 12 3\n14 1 11 18\n15 1 5 13\n16 0 13 12\n17 1 11 12\n18 1 9 6\n19 0 10 12\n20 0 10 13" }, { "code": null, "e": 2442, "s": 2431, "text": " Live Demo" }, { "code": null, "e": 2572, "s": 2442, "text": "W1<-sample(0:5,20,replace=TRUE)\nW2<-sample(0:10,20,replace=TRUE)\nW3<-sample(0:15,20,replace=TRUE)\ndf_W<-data.frame(W1,W2,W3)\ndf_W" }, { "code": null, "e": 2764, "s": 2572, "text": "W1 W2 W3\n1 0 8 14\n2 3 2 5\n3 3 2 10\n4 0 1 9\n5 1 9 8\n6 1 5 12\n7 3 2 13\n8 1 9 7\n9 0 5 2\n10 1 9 12\n11 3 1 0\n12 4 10 0\n13 4 2 0\n14 4 4 13\n15 5 3 15\n16 2 6 0\n17 4 1 14\n18 0 7 10\n19 1 4 15\n20 2 0 15" }, { "code": null, "e": 2793, "s": 2764, "text": "Subtracting df_W from df_V −" }, { "code": null, "e": 2803, "s": 2793, "text": "df_V-df_W" }, { "code": null, "e": 3014, "s": 2803, "text": "V1 V2 V3\n1 -5 5 12\n2 -3 12 7\n3 0 10 7\n4 -1 9 14\n5 -2 6 17\n6 2 -2 4\n7 0 7 5\n8 0 2 -1\n9 -1 6 -4\n10 -2 5 -4\n11 -3 0 7\n12 -2 11 -4\n13 -3 2 -1\n14 0 3 - 3\n15 -1 7 2\n16 2 2 9\n17 -3 6 2\n18 -2 -2 -1\n19 2 6 14\n20 -3 10 4" } ]
A Simple Guide to Using Keras Pretrained Models | by Shiva Verma | Towards Data Science
Keras contains 10 pretrained models for image classification which are trained on Imagenet data. Imagenet is a large collection of image data containing 1000 categories of images. These pretrained models are capable of classifying any image that falls into these 1000 categories of images. This guide will cover the following concepts. Image classification models. Using the pretrained models in Keras. Attaching our own classifier on the pretrained model. Input shape in pretrained models. Using Pooling. Freezing layers in the pretrained model. Using specific layers of the pretrained model. In a simplified way, the Image classification model looks like the following. Which contains convolutional layers followed by fully connected layers. Convolution layers extract features from the image and fully connected layers classify the image using extracted features. When we train a CNN on image data, It is seen that top layers of the network learn to extract general features from images such as edges, distribution of colours, etc. As we keep going deep in the network, the layers tend to extract more specific features. Now we can use these pretrained models which already know how to extract features and avoid the training from scratch. This concept is known as transfer learning. There are 2 ways to create models in Keras. One is the sequential model and the other is functional API. The sequential model is a linear stack of layers. You can simply keep adding layers in a sequential model just by calling add method. The other is functional API, which lets you create more complex models that might contain multiple input and output. I am going to use examples of the VGG16 pretrained model throughout this guide. We can use other pretrained models similarly. All pretrained models are available in the application module of Keras. First, we have to import pretrained models as follows. from keras.applications.vgg16 import VGG16 Then we can add the pretrained model like the following, Either in a sequential model or functional API. To use the pretrained weights we have to set the argument weights to imagenet. The default value is also set to imagenet. But if we want to train the model from scratch, we can set the weights argument to None. This will initialize the weights randomly in the network. We can remove the default classifier and attach our own classifier in the pretrained model. To exclude the default classifier we have to set argument include_top to false. In the following example, I am removing default classifier from VGG, then attaching my own classifier which is just one dense layer. We also have to include a flatten layer before adding a dense layer to convert the 4D output from the Convolution layer to 2D, since the dense layer accepts 2D input. VGG16 is trained on RGB images of size (224, 224), which is a default input size of the network. We can also feed the input image other than the default size. But the height and width of the image should be more than 32 pixels. We can only feed other size images when we exclude the default classifier from the network. Following is an example showing the input size of (32, 64, 3). The last dimension which is 3, represents the number of color channels. We can also define input shape by providing input tensor as shown in the following example. We can notice that the output dimension is also squeezed when we provide a smaller sized image which makes sense. We can apply 2 types of pooling on the final output from Convolution Layers. global average pooling and global maximum pooling. In global maximum pooling, we select a maximum number over each slide of a tensor as shown in the following image. Suppose the output tensor from the convolution layers is of shape (7, 7, 512). If we apply global maximum pooling, we select a maximum number from each (7, 7) slide, which gives us a total of 512 numbers. Average pooling does the same except for taking the average instead of the maximum. In order to use pooling, we have to set argument pooling to max or avg to use this 2 pooling. In the following example, I am using global average pooling. Global pooling is useful when we have a variable size of input images. Suppose we have 2 different sizes of output tensor from different sizes of images. The shape of the output tensor is (3, 3, 512) and (7, 7, 512). After applying global pooling on any of these tensors will get us a fixed-size vector of length 512. So the final output of variable size images will still be a fixed size vector after applying global pooling. Before training the network you may want to freeze some of its layers depending upon the task. Once a layer is frozen, its weights are not updated while training. In the following example, I am freezing the top 10 layers of the network. I have printed all layers in the network and whether they are trainable or not. We can see only the top 10 layers are not trainable. If the current dataset is similar to the dataset these networks were trained on, then its good to freeze all layers since images in both datasets would have similar features. But if the dataset if different then we should only freeze top layers and train bottom layers because top layers extract general features. More similar the dataset more layers we should freeze. In the above example, we can see what are all the layers model contains. We can also separately pick any of these layers and use them in our models. In the following example, I am adding the 3rd layer of pretrained model (block1_conv2) to a sequential model. This covers almost all the use-cases you need to know while using the pretrained model in Keras. Thanks for your time.
[ { "code": null, "e": 462, "s": 172, "text": "Keras contains 10 pretrained models for image classification which are trained on Imagenet data. Imagenet is a large collection of image data containing 1000 categories of images. These pretrained models are capable of classifying any image that falls into these 1000 categories of images." }, { "code": null, "e": 508, "s": 462, "text": "This guide will cover the following concepts." }, { "code": null, "e": 537, "s": 508, "text": "Image classification models." }, { "code": null, "e": 575, "s": 537, "text": "Using the pretrained models in Keras." }, { "code": null, "e": 629, "s": 575, "text": "Attaching our own classifier on the pretrained model." }, { "code": null, "e": 663, "s": 629, "text": "Input shape in pretrained models." }, { "code": null, "e": 678, "s": 663, "text": "Using Pooling." }, { "code": null, "e": 719, "s": 678, "text": "Freezing layers in the pretrained model." }, { "code": null, "e": 766, "s": 719, "text": "Using specific layers of the pretrained model." }, { "code": null, "e": 844, "s": 766, "text": "In a simplified way, the Image classification model looks like the following." }, { "code": null, "e": 1039, "s": 844, "text": "Which contains convolutional layers followed by fully connected layers. Convolution layers extract features from the image and fully connected layers classify the image using extracted features." }, { "code": null, "e": 1296, "s": 1039, "text": "When we train a CNN on image data, It is seen that top layers of the network learn to extract general features from images such as edges, distribution of colours, etc. As we keep going deep in the network, the layers tend to extract more specific features." }, { "code": null, "e": 1459, "s": 1296, "text": "Now we can use these pretrained models which already know how to extract features and avoid the training from scratch. This concept is known as transfer learning." }, { "code": null, "e": 1815, "s": 1459, "text": "There are 2 ways to create models in Keras. One is the sequential model and the other is functional API. The sequential model is a linear stack of layers. You can simply keep adding layers in a sequential model just by calling add method. The other is functional API, which lets you create more complex models that might contain multiple input and output." }, { "code": null, "e": 1941, "s": 1815, "text": "I am going to use examples of the VGG16 pretrained model throughout this guide. We can use other pretrained models similarly." }, { "code": null, "e": 2068, "s": 1941, "text": "All pretrained models are available in the application module of Keras. First, we have to import pretrained models as follows." }, { "code": null, "e": 2111, "s": 2068, "text": "from keras.applications.vgg16 import VGG16" }, { "code": null, "e": 2216, "s": 2111, "text": "Then we can add the pretrained model like the following, Either in a sequential model or functional API." }, { "code": null, "e": 2485, "s": 2216, "text": "To use the pretrained weights we have to set the argument weights to imagenet. The default value is also set to imagenet. But if we want to train the model from scratch, we can set the weights argument to None. This will initialize the weights randomly in the network." }, { "code": null, "e": 2657, "s": 2485, "text": "We can remove the default classifier and attach our own classifier in the pretrained model. To exclude the default classifier we have to set argument include_top to false." }, { "code": null, "e": 2957, "s": 2657, "text": "In the following example, I am removing default classifier from VGG, then attaching my own classifier which is just one dense layer. We also have to include a flatten layer before adding a dense layer to convert the 4D output from the Convolution layer to 2D, since the dense layer accepts 2D input." }, { "code": null, "e": 3412, "s": 2957, "text": "VGG16 is trained on RGB images of size (224, 224), which is a default input size of the network. We can also feed the input image other than the default size. But the height and width of the image should be more than 32 pixels. We can only feed other size images when we exclude the default classifier from the network. Following is an example showing the input size of (32, 64, 3). The last dimension which is 3, represents the number of color channels." }, { "code": null, "e": 3504, "s": 3412, "text": "We can also define input shape by providing input tensor as shown in the following example." }, { "code": null, "e": 3618, "s": 3504, "text": "We can notice that the output dimension is also squeezed when we provide a smaller sized image which makes sense." }, { "code": null, "e": 3746, "s": 3618, "text": "We can apply 2 types of pooling on the final output from Convolution Layers. global average pooling and global maximum pooling." }, { "code": null, "e": 3861, "s": 3746, "text": "In global maximum pooling, we select a maximum number over each slide of a tensor as shown in the following image." }, { "code": null, "e": 4150, "s": 3861, "text": "Suppose the output tensor from the convolution layers is of shape (7, 7, 512). If we apply global maximum pooling, we select a maximum number from each (7, 7) slide, which gives us a total of 512 numbers. Average pooling does the same except for taking the average instead of the maximum." }, { "code": null, "e": 4305, "s": 4150, "text": "In order to use pooling, we have to set argument pooling to max or avg to use this 2 pooling. In the following example, I am using global average pooling." }, { "code": null, "e": 4732, "s": 4305, "text": "Global pooling is useful when we have a variable size of input images. Suppose we have 2 different sizes of output tensor from different sizes of images. The shape of the output tensor is (3, 3, 512) and (7, 7, 512). After applying global pooling on any of these tensors will get us a fixed-size vector of length 512. So the final output of variable size images will still be a fixed size vector after applying global pooling." }, { "code": null, "e": 4895, "s": 4732, "text": "Before training the network you may want to freeze some of its layers depending upon the task. Once a layer is frozen, its weights are not updated while training." }, { "code": null, "e": 5102, "s": 4895, "text": "In the following example, I am freezing the top 10 layers of the network. I have printed all layers in the network and whether they are trainable or not. We can see only the top 10 layers are not trainable." }, { "code": null, "e": 5471, "s": 5102, "text": "If the current dataset is similar to the dataset these networks were trained on, then its good to freeze all layers since images in both datasets would have similar features. But if the dataset if different then we should only freeze top layers and train bottom layers because top layers extract general features. More similar the dataset more layers we should freeze." }, { "code": null, "e": 5620, "s": 5471, "text": "In the above example, we can see what are all the layers model contains. We can also separately pick any of these layers and use them in our models." }, { "code": null, "e": 5730, "s": 5620, "text": "In the following example, I am adding the 3rd layer of pretrained model (block1_conv2) to a sequential model." } ]
Tailwind CSS Table Layout
23 Mar, 2022 This class accepts lots of value in tailwind CSS in which all the properties are covered in class form. By using this class we can set the display of the layout of the table. In CSS, we do that by using the CSS table-layout property. Table Layout classes: table-auto table-fixed table-auto: This class is used to allow the table to automatically size columns to fit the contents of the cell. Syntax: <element class="table-auto">...</element> Example: HTML <!DOCTYPE html> <html><head> <link href= "https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center mx-4 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Table Layout Class</b> <div class="bg-green-200"> <table class="table-auto border-separate border border-green-900"> <thead> <tr> <th class="border border-green-600">Frameworks</th> <th class="border border-green-600">About</th> </tr> </thead> <tbody> <tr> <td class="border border-green-600">Tailwind CSS</td> <td class="border border-green-600"> Tailwind CSS is a highly customizable, low-level CSS framework that gives you all of the building blocks </td> </tr> <tr> <td class="border border-green-600">Bulma</td> <td class="border border-green-600"> Bulma CSS by @jgthms is just perfect. Simple, easily customizable and doesn't impose Javascript implementations. </td> </tr> <tr> <td class="border border-green-600">Bootstrap</td> <td class="border border-green-600"> Bootstrap is a free and open-source CSS framework directed at responsive, mobile-first front-end web development. </td> </tr> </tbody> </table> </div> </body> </html> Output: Tailwind CSS table layout table-fixed: This class is used to allow the table to ignore the content and use fixed widths for columns. The width of the first row will set the column widths for the whole table. Syntax: <element class="table-fixed">...</element> Example: HTML <!DOCTYPE html> <html><head> <link href= "https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center mx-4 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Table Layout Class</b> <div class="bg-green-200"> <table class="table-fixed border-separate border border-green-900"> <thead> <tr> <th class="border border-green-600 w-1/4">Frameworks</th> <th class="border border-green-600 w-3/4">About</th> </tr> </thead> <tbody> <tr> <td class="border border-green-600">Tailwind CSS</td> <td class="border border-green-600"> Tailwind CSS is a highly customizable, low-level CSS framework that gives you all of the building blocks </td> </tr> <tr> <td class="border border-green-600">Bulma</td> <td class="border border-green-600"> Bulma CSS by @jgthms is just perfect. Simple, easily customizable and doesn't impose Javascript implementations. </td> </tr> <tr> <td class="border border-green-600">Bootstrap</td> <td class="border border-green-600"> Bootstrap is a free and open-source CSS framework directed at responsive, mobile-first front-end web development. </td> </tr> </tbody> </table> </div> </body> </html> Output: Tailwind CSS layout Tailwind CSS Tailwind-Tables CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Mar, 2022" }, { "code": null, "e": 288, "s": 54, "text": "This class accepts lots of value in tailwind CSS in which all the properties are covered in class form. By using this class we can set the display of the layout of the table. In CSS, we do that by using the CSS table-layout property." }, { "code": null, "e": 310, "s": 288, "text": "Table Layout classes:" }, { "code": null, "e": 321, "s": 310, "text": "table-auto" }, { "code": null, "e": 333, "s": 321, "text": "table-fixed" }, { "code": null, "e": 446, "s": 333, "text": "table-auto: This class is used to allow the table to automatically size columns to fit the contents of the cell." }, { "code": null, "e": 454, "s": 446, "text": "Syntax:" }, { "code": null, "e": 496, "s": 454, "text": "<element class=\"table-auto\">...</element>" }, { "code": null, "e": 505, "s": 496, "text": "Example:" }, { "code": null, "e": 510, "s": 505, "text": "HTML" }, { "code": "<!DOCTYPE html> <html><head> <link href= \"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center mx-4 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Table Layout Class</b> <div class=\"bg-green-200\"> <table class=\"table-auto border-separate border border-green-900\"> <thead> <tr> <th class=\"border border-green-600\">Frameworks</th> <th class=\"border border-green-600\">About</th> </tr> </thead> <tbody> <tr> <td class=\"border border-green-600\">Tailwind CSS</td> <td class=\"border border-green-600\"> Tailwind CSS is a highly customizable, low-level CSS framework that gives you all of the building blocks </td> </tr> <tr> <td class=\"border border-green-600\">Bulma</td> <td class=\"border border-green-600\"> Bulma CSS by @jgthms is just perfect. Simple, easily customizable and doesn't impose Javascript implementations. </td> </tr> <tr> <td class=\"border border-green-600\">Bootstrap</td> <td class=\"border border-green-600\"> Bootstrap is a free and open-source CSS framework directed at responsive, mobile-first front-end web development. </td> </tr> </tbody> </table> </div> </body> </html> ", "e": 2119, "s": 510, "text": null }, { "code": null, "e": 2127, "s": 2119, "text": "Output:" }, { "code": null, "e": 2153, "s": 2127, "text": "Tailwind CSS table layout" }, { "code": null, "e": 2335, "s": 2153, "text": "table-fixed: This class is used to allow the table to ignore the content and use fixed widths for columns. The width of the first row will set the column widths for the whole table." }, { "code": null, "e": 2343, "s": 2335, "text": "Syntax:" }, { "code": null, "e": 2386, "s": 2343, "text": "<element class=\"table-fixed\">...</element>" }, { "code": null, "e": 2395, "s": 2386, "text": "Example:" }, { "code": null, "e": 2400, "s": 2395, "text": "HTML" }, { "code": "<!DOCTYPE html> <html><head> <link href= \"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center mx-4 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Table Layout Class</b> <div class=\"bg-green-200\"> <table class=\"table-fixed border-separate border border-green-900\"> <thead> <tr> <th class=\"border border-green-600 w-1/4\">Frameworks</th> <th class=\"border border-green-600 w-3/4\">About</th> </tr> </thead> <tbody> <tr> <td class=\"border border-green-600\">Tailwind CSS</td> <td class=\"border border-green-600\"> Tailwind CSS is a highly customizable, low-level CSS framework that gives you all of the building blocks </td> </tr> <tr> <td class=\"border border-green-600\">Bulma</td> <td class=\"border border-green-600\"> Bulma CSS by @jgthms is just perfect. Simple, easily customizable and doesn't impose Javascript implementations. </td> </tr> <tr> <td class=\"border border-green-600\">Bootstrap</td> <td class=\"border border-green-600\"> Bootstrap is a free and open-source CSS framework directed at responsive, mobile-first front-end web development. </td> </tr> </tbody> </table> </div> </body> </html> ", "e": 4022, "s": 2400, "text": null }, { "code": null, "e": 4030, "s": 4022, "text": "Output:" }, { "code": null, "e": 4050, "s": 4030, "text": "Tailwind CSS layout" }, { "code": null, "e": 4063, "s": 4050, "text": "Tailwind CSS" }, { "code": null, "e": 4079, "s": 4063, "text": "Tailwind-Tables" }, { "code": null, "e": 4083, "s": 4079, "text": "CSS" }, { "code": null, "e": 4100, "s": 4083, "text": "Web Technologies" }, { "code": null, "e": 4198, "s": 4100, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4246, "s": 4198, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 4308, "s": 4246, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4358, "s": 4308, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4416, "s": 4358, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 4466, "s": 4416, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 4499, "s": 4466, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4561, "s": 4499, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4622, "s": 4561, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4672, "s": 4622, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python | Pandas Series.reset_index()
10 Feb, 2019 Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.reset_index() function generate a new DataFrame or Series with the index reset. This comes handy when index is need to be used as a column. Syntax: Series.reset_index(level=None, drop=False, name=None, inplace=False) Parameter :level : For a Series with a MultiIndexdrop : Just reset the index, without inserting it as a column in the new DataFrame.name : The name to use for the column containing the original Series values.inplace : Modify the Series in place Returns : result : Series Example #1: Use Series.reset_index() function to reset the index of the given Series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Now we will use Series.reset_index() function to reset the index of the given series object. # reset the indexresult = sr.reset_index() # Print the resultprint(result) Output :As we can see in the output, the Series.reset_index() function has reset the index of the given Series object to default. It has preserved the index and it has converted it to a column. Example #2: Use Series.reset_index() function to reset the index of the given Series object. Do not keep the original index labels of the given series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Now we will use Series.reset_index() function to reset the index of the given series object and also we will be dropping the original index labels. # reset the indexresult = sr.reset_index(drop = True) # Print the resultprint(result) Output :As we can see in the output, the Series.reset_index() function has reset the index of the given Series object to default. It has dropped the original index. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Feb, 2019" }, { "code": null, "e": 285, "s": 28, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 439, "s": 285, "text": "Pandas Series.reset_index() function generate a new DataFrame or Series with the index reset. This comes handy when index is need to be used as a column." }, { "code": null, "e": 516, "s": 439, "text": "Syntax: Series.reset_index(level=None, drop=False, name=None, inplace=False)" }, { "code": null, "e": 761, "s": 516, "text": "Parameter :level : For a Series with a MultiIndexdrop : Just reset the index, without inserting it as a column in the new DataFrame.name : The name to use for the column containing the original Series values.inplace : Modify the Series in place" }, { "code": null, "e": 787, "s": 761, "text": "Returns : result : Series" }, { "code": null, "e": 880, "s": 787, "text": "Example #1: Use Series.reset_index() function to reset the index of the given Series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 1136, "s": 880, "text": null }, { "code": null, "e": 1145, "s": 1136, "text": "Output :" }, { "code": null, "e": 1238, "s": 1145, "text": "Now we will use Series.reset_index() function to reset the index of the given series object." }, { "code": "# reset the indexresult = sr.reset_index() # Print the resultprint(result)", "e": 1314, "s": 1238, "text": null }, { "code": null, "e": 1667, "s": 1314, "text": "Output :As we can see in the output, the Series.reset_index() function has reset the index of the given Series object to default. It has preserved the index and it has converted it to a column. Example #2: Use Series.reset_index() function to reset the index of the given Series object. Do not keep the original index labels of the given series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 1923, "s": 1667, "text": null }, { "code": null, "e": 1932, "s": 1923, "text": "Output :" }, { "code": null, "e": 2080, "s": 1932, "text": "Now we will use Series.reset_index() function to reset the index of the given series object and also we will be dropping the original index labels." }, { "code": "# reset the indexresult = sr.reset_index(drop = True) # Print the resultprint(result)", "e": 2167, "s": 2080, "text": null }, { "code": null, "e": 2332, "s": 2167, "text": "Output :As we can see in the output, the Series.reset_index() function has reset the index of the given Series object to default. It has dropped the original index." }, { "code": null, "e": 2353, "s": 2332, "text": "Python pandas-series" }, { "code": null, "e": 2382, "s": 2353, "text": "Python pandas-series-methods" }, { "code": null, "e": 2396, "s": 2382, "text": "Python-pandas" }, { "code": null, "e": 2403, "s": 2396, "text": "Python" } ]
Prototypal Inheritance using __proto__ in JavaScript
02 Jun, 2020 Every object with its methods and properties contains an internal and hidden property known as [[Prototype]]. The Prototypal Inheritance is a feature in javascript used to add methods and properties in objects. It is a method by which an object can inherit the properties and methods of another object. Traditionally, in order to get and set the [[Prototype]] of an object, we use Object.getPrototypeOf and Object.setPrototypeOf. Nowadays, in modern language, it is being set using __proto__. Syntax: ChildObject.__proto__ = ParentObject Example In the given example, there are two objects ‘person’ and ‘GFGuser’. The object ‘GFGuser’ inherits the methods and properties of the object ‘person’ and further uses them. <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <title>prototype</title> </head> <body> <script> // object person let person = { talk: true, Canfly() { return "Sorry, Can't fly"; }, }; // Object GFGuser let GFGuser = { CanCode: true, CanCook() { return "Can't say"; }, // Inheriting the properties and methods of person __proto__: person, }; // Printing on console // Property of person console.log("Can a GFG User talk: " + GFGuser.talk); // Method of person console.log("Can a GFG User fly: " + GFGuser.Canfly()); // Property of GFGuser console.log("Can a GFG User code: " + GFGuser.CanCode); // Method of GFGuser console.log("Can a GFG User cook: " + GFGuser.CanCook()); </script> </body></html> Output JavaScript-Misc JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Jun, 2020" }, { "code": null, "e": 545, "s": 52, "text": "Every object with its methods and properties contains an internal and hidden property known as [[Prototype]]. The Prototypal Inheritance is a feature in javascript used to add methods and properties in objects. It is a method by which an object can inherit the properties and methods of another object. Traditionally, in order to get and set the [[Prototype]] of an object, we use Object.getPrototypeOf and Object.setPrototypeOf. Nowadays, in modern language, it is being set using __proto__." }, { "code": null, "e": 553, "s": 545, "text": "Syntax:" }, { "code": null, "e": 590, "s": 553, "text": "ChildObject.__proto__ = ParentObject" }, { "code": null, "e": 769, "s": 590, "text": "Example In the given example, there are two objects ‘person’ and ‘GFGuser’. The object ‘GFGuser’ inherits the methods and properties of the object ‘person’ and further uses them." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <title>prototype</title> </head> <body> <script> // object person let person = { talk: true, Canfly() { return \"Sorry, Can't fly\"; }, }; // Object GFGuser let GFGuser = { CanCode: true, CanCook() { return \"Can't say\"; }, // Inheriting the properties and methods of person __proto__: person, }; // Printing on console // Property of person console.log(\"Can a GFG User talk: \" + GFGuser.talk); // Method of person console.log(\"Can a GFG User fly: \" + GFGuser.Canfly()); // Property of GFGuser console.log(\"Can a GFG User code: \" + GFGuser.CanCode); // Method of GFGuser console.log(\"Can a GFG User cook: \" + GFGuser.CanCook()); </script> </body></html>", "e": 1905, "s": 769, "text": null }, { "code": null, "e": 1912, "s": 1905, "text": "Output" }, { "code": null, "e": 1928, "s": 1912, "text": "JavaScript-Misc" }, { "code": null, "e": 1939, "s": 1928, "text": "JavaScript" }, { "code": null, "e": 1956, "s": 1939, "text": "Web Technologies" }, { "code": null, "e": 2054, "s": 1956, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2115, "s": 2054, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2155, "s": 2115, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2196, "s": 2155, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2238, "s": 2196, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2260, "s": 2238, "text": "JavaScript | Promises" }, { "code": null, "e": 2293, "s": 2260, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2355, "s": 2293, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2416, "s": 2355, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2466, "s": 2416, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Reverse the order of all nodes at even position in given Linked List
07 Mar, 2022 Given a linked list A[] of N integers, the task is to reverse the order of all integers at an even position. Examples: Input: A[] = 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULLOutput: 1 6 3 4 5 2Explanation: Nodes at even position in the given linked list are 2, 4 and 6. So, after reversing there order, the new linked list will be 1 -> 6 -> 3 -> 4 -> 5 -> 2 -> NULL. Input: A[] = 1 -> 5 -> 3->NULLOutput: 1 5 3 Approach: The given problem can be solved by maintaining two linked lists, one list for all odd positioned nodes and another list for all even positioned nodes. Traverse the given linked list which will be considered as the odd list. Hence, for all the nodes at even positions, remove it from the odd list and insert it to the front of the even node list. Since the nodes are added at the front, their order will be reversed. Merge the two lists at alternate positions which is the required answer. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Node of the linked listclass Node {public: int data; Node* next;}; // Function to reverse all the even// positioned node of given linked listNode* reverse_even(Node* A){ // Stores the nodes with // even positions Node* even = NULL; // Stores the nodes with // odd positions Node* odd = A; // If size of list is less that // 3, no change is required if (!odd || !odd->next || !odd->next->next) return odd; // Loop to traverse the list while (odd && odd->next) { // Store the even positioned // node in temp Node* temp = odd->next; odd->next = temp->next; // Add the even node to the // beginning of even list temp->next = even; // Make temp as new even list even = temp; // Move odd to it's next node odd = odd->next; } odd = A; // Merge the evenlist into // odd list alternatively while (even) { // Stores the even's next // node in temp Node* temp = even->next; // Link the next odd node // to next of even node even->next = odd->next; // Link even to next odd node odd->next = even; // Make new even as temp node even = temp; // Move odd to it's 2nd next node odd = odd->next->next; } return A;} // Function to add a node at// the beginning of Linked Listvoid push(Node** head_ref, int new_data){ Node* new_node = new Node(); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Function to print nodes// in a given linked listvoid printList(Node* node){ while (node != NULL) { cout << node->data << " "; node = node->next; }} // Driver Codeint main(){ Node* start = NULL; push(&start, 6); push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); start = reverse_even(start); printList(start); return 0;} // Java program for the above approach import java.util.*; class GFG{ // Node of the linked liststatic class Node { int data; Node next;};static Node start = null;// Function to reverse all the even// positioned node of given linked liststatic Node reverse_even(Node A){ // Stores the nodes with // even positions Node even = null; // Stores the nodes with // odd positions Node odd = A; // If size of list is less that // 3, no change is required if (odd==null || odd.next==null || odd.next.next==null) return odd; // Loop to traverse the list while (odd!=null && odd.next!=null) { // Store the even positioned // node in temp Node temp = odd.next; odd.next = temp.next; // Add the even node to the // beginning of even list temp.next = even; // Make temp as new even list even = temp; // Move odd to it's next node odd = odd.next; } odd = A; // Merge the evenlist into // odd list alternatively while (even!=null) { // Stores the even's next // node in temp Node temp = even.next; // Link the next odd node // to next of even node even.next = odd.next; // Link even to next odd node odd.next = even; // Make new even as temp node even = temp; // Move odd to it's 2nd next node odd = odd.next.next; } return A;} // Function to add a node at// the beginning of Linked Liststatic void push(int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = start; start = new_node;} // Function to print nodes// in a given linked liststatic void printList(Node node){ while (node != null) { System.out.print(node.data+ " "); node = node.next; }} // Driver Codepublic static void main(String[] args){ push(6); push(5); push(4); push(3); push(2); push(1); start = reverse_even(start); printList(start); }} // This code is contributed by 29AjayKumar # Python program for the above approachstart = None # Node of the linked listclass Node: def __init__(self, data): self.data = data self.next = None # Function to reverse all the even# positioned node of given linked listdef reverse_even(A): # Stores the nodes with # even positions even = None # Stores the nodes with # odd positions odd = A # If size of list is less that # 3, no change is required if (odd == None or odd.next == None or odd.next.next == None): return odd # Loop to traverse the list while (odd and odd.next): # Store the even positioned # node in temp temp = odd.next odd.next = temp.next # Add the even node to the # beginning of even list temp.next = even # Make temp as new even list even = temp # Move odd to it's next node odd = odd.next odd = A # Merge the evenlist into # odd list alternatively while (even): # Stores the even's next # node in temp temp = even.next # Link the next odd node # to next of even node even.next = odd.next # Link even to next odd node odd.next = even # Make new even as temp node even = temp # Move odd to it's 2nd next node odd = odd.next.next return A # Function to add a node at# the beginning of Linked Listdef push(new_data): global start new_node = Node(new_data) new_node.next = start start = new_node # Function to print nodes# in a given linked listdef printList(node): while (node != None): print(node.data, end=" ") node = node.next # Driver Codestart = None push(6)push(5)push(4)push(3)push(2)push(1) start = reverse_even(start)printList(start) # This code is contributed by saurabh_jaiswal. // C# program for the above approachusing System;public class GFG{ // Node of the linked listclass Node { public int data; public Node next;};static Node start = null; // Function to reverse all the even// positioned node of given linked liststatic Node reverse_even(Node A){ // Stores the nodes with // even positions Node even = null; // Stores the nodes with // odd positions Node odd = A; // If size of list is less that // 3, no change is required if (odd==null || odd.next==null || odd.next.next==null) return odd; // Loop to traverse the list while (odd!=null && odd.next!=null) { // Store the even positioned // node in temp Node temp = odd.next; odd.next = temp.next; // Add the even node to the // beginning of even list temp.next = even; // Make temp as new even list even = temp; // Move odd to it's next node odd = odd.next; } odd = A; // Merge the evenlist into // odd list alternatively while (even!=null) { // Stores the even's next // node in temp Node temp = even.next; // Link the next odd node // to next of even node even.next = odd.next; // Link even to next odd node odd.next = even; // Make new even as temp node even = temp; // Move odd to it's 2nd next node odd = odd.next.next; } return A;} // Function to add a node at// the beginning of Linked Liststatic void push(int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = start; start = new_node;} // Function to print nodes// in a given linked liststatic void printList(Node node){ while (node != null) { Console.Write(node.data+ " "); node = node.next; }} // Driver Codepublic static void Main(String[] args){ push(6); push(5); push(4); push(3); push(2); push(1); start = reverse_even(start); printList(start); }} // This code is contributed by shikhasingrajput <script>// Javascript program for the above approach // Node of the linked listclass Node { constructor(data) { this.data = data; this.next = null; }}; // Function to reverse all the even// positioned node of given linked listfunction reverse_even(A) { // Stores the nodes with // even positions let even = null; // Stores the nodes with // odd positions let odd = A; // If size of list is less that // 3, no change is required if (odd == null || odd.next == null || odd.next.next == null) return odd; // Loop to traverse the list while (odd && odd.next) { // Store the even positioned // node in temp let temp = odd.next; odd.next = temp.next; // Add the even node to the // beginning of even list temp.next = even; // Make temp as new even list even = temp; // Move odd to it's next node odd = odd.next; } odd = A; // Merge the evenlist into // odd list alternatively while (even) { // Stores the even's next // node in temp let temp = even.next; // Link the next odd node // to next of even node even.next = odd.next; // Link even to next odd node odd.next = even; // Make new even as temp node even = temp; // Move odd to it's 2nd next node odd = odd.next.next; } return A;} // Function to add a node at// the beginning of Linked Listfunction push(new_data) { let new_node = new Node(); new_node.data = new_data; new_node.next = start; start = new_node;} // Function to print nodes// in a given linked listfunction printList(node) { while (node != null) { document.write(node.data + " "); node = node.next; }} // Driver Codelet start = null; push(6);push(5);push(4);push(3);push(2);push(1); start = reverse_even(start);printList(start); // This code is contributed by saurabh_jaiswal.</script> 1 6 3 4 5 2 Time Complexity: O(N)Auxiliary Space: O(1) 29AjayKumar _saurabh_jaiswal shikhasingrajput surindertarika1234 sundeepchand Linked Lists Reverse Linked List Linked List Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Types of Linked List Rearrange a given linked list in-place. Find first node of loop in a linked list Circular Singly Linked List | Insertion Add two numbers represented by linked lists | Set 2 Flattening a Linked List Real-time application of Data Structures Insert a node at a specific position in a linked list
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Mar, 2022" }, { "code": null, "e": 161, "s": 52, "text": "Given a linked list A[] of N integers, the task is to reverse the order of all integers at an even position." }, { "code": null, "e": 171, "s": 161, "text": "Examples:" }, { "code": null, "e": 412, "s": 171, "text": "Input: A[] = 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULLOutput: 1 6 3 4 5 2Explanation: Nodes at even position in the given linked list are 2, 4 and 6. So, after reversing there order, the new linked list will be 1 -> 6 -> 3 -> 4 -> 5 -> 2 -> NULL." }, { "code": null, "e": 457, "s": 412, "text": "Input: A[] = 1 -> 5 -> 3->NULLOutput: 1 5 3" }, { "code": null, "e": 956, "s": 457, "text": "Approach: The given problem can be solved by maintaining two linked lists, one list for all odd positioned nodes and another list for all even positioned nodes. Traverse the given linked list which will be considered as the odd list. Hence, for all the nodes at even positions, remove it from the odd list and insert it to the front of the even node list. Since the nodes are added at the front, their order will be reversed. Merge the two lists at alternate positions which is the required answer." }, { "code": null, "e": 1007, "s": 956, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 1011, "s": 1007, "text": "C++" }, { "code": null, "e": 1016, "s": 1011, "text": "Java" }, { "code": null, "e": 1024, "s": 1016, "text": "Python3" }, { "code": null, "e": 1027, "s": 1024, "text": "C#" }, { "code": null, "e": 1038, "s": 1027, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Node of the linked listclass Node {public: int data; Node* next;}; // Function to reverse all the even// positioned node of given linked listNode* reverse_even(Node* A){ // Stores the nodes with // even positions Node* even = NULL; // Stores the nodes with // odd positions Node* odd = A; // If size of list is less that // 3, no change is required if (!odd || !odd->next || !odd->next->next) return odd; // Loop to traverse the list while (odd && odd->next) { // Store the even positioned // node in temp Node* temp = odd->next; odd->next = temp->next; // Add the even node to the // beginning of even list temp->next = even; // Make temp as new even list even = temp; // Move odd to it's next node odd = odd->next; } odd = A; // Merge the evenlist into // odd list alternatively while (even) { // Stores the even's next // node in temp Node* temp = even->next; // Link the next odd node // to next of even node even->next = odd->next; // Link even to next odd node odd->next = even; // Make new even as temp node even = temp; // Move odd to it's 2nd next node odd = odd->next->next; } return A;} // Function to add a node at// the beginning of Linked Listvoid push(Node** head_ref, int new_data){ Node* new_node = new Node(); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Function to print nodes// in a given linked listvoid printList(Node* node){ while (node != NULL) { cout << node->data << \" \"; node = node->next; }} // Driver Codeint main(){ Node* start = NULL; push(&start, 6); push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); start = reverse_even(start); printList(start); return 0;}", "e": 3098, "s": 1038, "text": null }, { "code": "// Java program for the above approach import java.util.*; class GFG{ // Node of the linked liststatic class Node { int data; Node next;};static Node start = null;// Function to reverse all the even// positioned node of given linked liststatic Node reverse_even(Node A){ // Stores the nodes with // even positions Node even = null; // Stores the nodes with // odd positions Node odd = A; // If size of list is less that // 3, no change is required if (odd==null || odd.next==null || odd.next.next==null) return odd; // Loop to traverse the list while (odd!=null && odd.next!=null) { // Store the even positioned // node in temp Node temp = odd.next; odd.next = temp.next; // Add the even node to the // beginning of even list temp.next = even; // Make temp as new even list even = temp; // Move odd to it's next node odd = odd.next; } odd = A; // Merge the evenlist into // odd list alternatively while (even!=null) { // Stores the even's next // node in temp Node temp = even.next; // Link the next odd node // to next of even node even.next = odd.next; // Link even to next odd node odd.next = even; // Make new even as temp node even = temp; // Move odd to it's 2nd next node odd = odd.next.next; } return A;} // Function to add a node at// the beginning of Linked Liststatic void push(int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = start; start = new_node;} // Function to print nodes// in a given linked liststatic void printList(Node node){ while (node != null) { System.out.print(node.data+ \" \"); node = node.next; }} // Driver Codepublic static void main(String[] args){ push(6); push(5); push(4); push(3); push(2); push(1); start = reverse_even(start); printList(start); }} // This code is contributed by 29AjayKumar", "e": 5166, "s": 3098, "text": null }, { "code": "# Python program for the above approachstart = None # Node of the linked listclass Node: def __init__(self, data): self.data = data self.next = None # Function to reverse all the even# positioned node of given linked listdef reverse_even(A): # Stores the nodes with # even positions even = None # Stores the nodes with # odd positions odd = A # If size of list is less that # 3, no change is required if (odd == None or odd.next == None or odd.next.next == None): return odd # Loop to traverse the list while (odd and odd.next): # Store the even positioned # node in temp temp = odd.next odd.next = temp.next # Add the even node to the # beginning of even list temp.next = even # Make temp as new even list even = temp # Move odd to it's next node odd = odd.next odd = A # Merge the evenlist into # odd list alternatively while (even): # Stores the even's next # node in temp temp = even.next # Link the next odd node # to next of even node even.next = odd.next # Link even to next odd node odd.next = even # Make new even as temp node even = temp # Move odd to it's 2nd next node odd = odd.next.next return A # Function to add a node at# the beginning of Linked Listdef push(new_data): global start new_node = Node(new_data) new_node.next = start start = new_node # Function to print nodes# in a given linked listdef printList(node): while (node != None): print(node.data, end=\" \") node = node.next # Driver Codestart = None push(6)push(5)push(4)push(3)push(2)push(1) start = reverse_even(start)printList(start) # This code is contributed by saurabh_jaiswal.", "e": 7005, "s": 5166, "text": null }, { "code": "// C# program for the above approachusing System;public class GFG{ // Node of the linked listclass Node { public int data; public Node next;};static Node start = null; // Function to reverse all the even// positioned node of given linked liststatic Node reverse_even(Node A){ // Stores the nodes with // even positions Node even = null; // Stores the nodes with // odd positions Node odd = A; // If size of list is less that // 3, no change is required if (odd==null || odd.next==null || odd.next.next==null) return odd; // Loop to traverse the list while (odd!=null && odd.next!=null) { // Store the even positioned // node in temp Node temp = odd.next; odd.next = temp.next; // Add the even node to the // beginning of even list temp.next = even; // Make temp as new even list even = temp; // Move odd to it's next node odd = odd.next; } odd = A; // Merge the evenlist into // odd list alternatively while (even!=null) { // Stores the even's next // node in temp Node temp = even.next; // Link the next odd node // to next of even node even.next = odd.next; // Link even to next odd node odd.next = even; // Make new even as temp node even = temp; // Move odd to it's 2nd next node odd = odd.next.next; } return A;} // Function to add a node at// the beginning of Linked Liststatic void push(int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = start; start = new_node;} // Function to print nodes// in a given linked liststatic void printList(Node node){ while (node != null) { Console.Write(node.data+ \" \"); node = node.next; }} // Driver Codepublic static void Main(String[] args){ push(6); push(5); push(4); push(3); push(2); push(1); start = reverse_even(start); printList(start); }} // This code is contributed by shikhasingrajput", "e": 9082, "s": 7005, "text": null }, { "code": "<script>// Javascript program for the above approach // Node of the linked listclass Node { constructor(data) { this.data = data; this.next = null; }}; // Function to reverse all the even// positioned node of given linked listfunction reverse_even(A) { // Stores the nodes with // even positions let even = null; // Stores the nodes with // odd positions let odd = A; // If size of list is less that // 3, no change is required if (odd == null || odd.next == null || odd.next.next == null) return odd; // Loop to traverse the list while (odd && odd.next) { // Store the even positioned // node in temp let temp = odd.next; odd.next = temp.next; // Add the even node to the // beginning of even list temp.next = even; // Make temp as new even list even = temp; // Move odd to it's next node odd = odd.next; } odd = A; // Merge the evenlist into // odd list alternatively while (even) { // Stores the even's next // node in temp let temp = even.next; // Link the next odd node // to next of even node even.next = odd.next; // Link even to next odd node odd.next = even; // Make new even as temp node even = temp; // Move odd to it's 2nd next node odd = odd.next.next; } return A;} // Function to add a node at// the beginning of Linked Listfunction push(new_data) { let new_node = new Node(); new_node.data = new_data; new_node.next = start; start = new_node;} // Function to print nodes// in a given linked listfunction printList(node) { while (node != null) { document.write(node.data + \" \"); node = node.next; }} // Driver Codelet start = null; push(6);push(5);push(4);push(3);push(2);push(1); start = reverse_even(start);printList(start); // This code is contributed by saurabh_jaiswal.</script>", "e": 11071, "s": 9082, "text": null }, { "code": null, "e": 11084, "s": 11071, "text": "1 6 3 4 5 2 " }, { "code": null, "e": 11127, "s": 11084, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 11139, "s": 11127, "text": "29AjayKumar" }, { "code": null, "e": 11156, "s": 11139, "text": "_saurabh_jaiswal" }, { "code": null, "e": 11173, "s": 11156, "text": "shikhasingrajput" }, { "code": null, "e": 11192, "s": 11173, "text": "surindertarika1234" }, { "code": null, "e": 11205, "s": 11192, "text": "sundeepchand" }, { "code": null, "e": 11218, "s": 11205, "text": "Linked Lists" }, { "code": null, "e": 11226, "s": 11218, "text": "Reverse" }, { "code": null, "e": 11238, "s": 11226, "text": "Linked List" }, { "code": null, "e": 11250, "s": 11238, "text": "Linked List" }, { "code": null, "e": 11258, "s": 11250, "text": "Reverse" }, { "code": null, "e": 11356, "s": 11258, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11388, "s": 11356, "text": "Introduction to Data Structures" }, { "code": null, "e": 11452, "s": 11388, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 11473, "s": 11452, "text": "Types of Linked List" }, { "code": null, "e": 11513, "s": 11473, "text": "Rearrange a given linked list in-place." }, { "code": null, "e": 11554, "s": 11513, "text": "Find first node of loop in a linked list" }, { "code": null, "e": 11594, "s": 11554, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 11646, "s": 11594, "text": "Add two numbers represented by linked lists | Set 2" }, { "code": null, "e": 11671, "s": 11646, "text": "Flattening a Linked List" }, { "code": null, "e": 11712, "s": 11671, "text": "Real-time application of Data Structures" } ]