title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Bootstrap 4 card styled with bg-secondary class
Add less important stuff, using the card class with the bg-secondary contextual class in Bootstrap. This class adds a gray background − <div class="card bg-secondary text-white"> Inside that, add the card body − <div class="card bg-secondary text-white"> <div class="card-body">English</div> </div> You can try to run the following code to implement the card class with bg-secondary class in Bootstrap − Live Demo <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h3>Languages</h3> <div class="card bg-secondary text-white"> <div class="card-body">English</div> </div><br> <div class="card bg-secondary text-white"> <div class="card-body">French</div> </div><br> <div class="card bg-secondary text-white"> <div class="card-body">Chinese</div> </div><br> <div class="card bg-secondary text-white"> <div class="card-body">Russian</div> </div> </div> </body> </html>
[ { "code": null, "e": 1162, "s": 1062, "text": "Add less important stuff, using the card class with the bg-secondary contextual class in Bootstrap." }, { "code": null, "e": 1198, "s": 1162, "text": "This class adds a gray background −" }, { "code": null, "e": 1241, "s": 1198, "text": "<div class=\"card bg-secondary text-white\">" }, { "code": null, "e": 1274, "s": 1241, "text": "Inside that, add the card body −" }, { "code": null, "e": 1363, "s": 1274, "text": "<div class=\"card bg-secondary text-white\">\n <div class=\"card-body\">English</div>\n</div>" }, { "code": null, "e": 1468, "s": 1363, "text": "You can try to run the following code to implement the card class with bg-secondary class in Bootstrap −" }, { "code": null, "e": 1478, "s": 1468, "text": "Live Demo" }, { "code": null, "e": 2460, "s": 1478, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n\n<body>\n <div class=\"container\">\n <h3>Languages</h3>\n <div class=\"card bg-secondary text-white\">\n <div class=\"card-body\">English</div>\n </div><br>\n <div class=\"card bg-secondary text-white\">\n <div class=\"card-body\">French</div>\n </div><br>\n <div class=\"card bg-secondary text-white\">\n <div class=\"card-body\">Chinese</div>\n </div><br>\n <div class=\"card bg-secondary text-white\">\n <div class=\"card-body\">Russian</div>\n </div>\n </div>\n\n</body>\n</html>" } ]
Facade Design Pattern | Introduction - GeeksforGeeks
01 Sep, 2021 Facade is a part of Gang of Four design pattern and it is categorized under Structural design patterns. Before we dig into the details of it, let us discuss some examples which will be solved by this particular Pattern. So, As the name suggests, it means the face of the building. The people walking past the road can only see this glass face of the building. They do not know anything about it, the wiring, the pipes and other complexities. It hides all the complexities of the building and displays a friendly face. More examples In Java, the interface JDBC can be called a facade because, we as users or clients create connection using the “java.sql.Connection” interface, the implementation of which we are not concerned about. The implementation is left to the vendor of driver. Another good example can be the startup of a computer. When a computer starts up, it involves the work of cpu, memory, hard drive, etc. To make it easy to use for users, we can add a facade which wrap the complexity of the task, and provide one simple interface instead.Same goes for the Facade Design Pattern. It hides the complexities of the system and provides an interface to the client from where the client can access the system. Facade Design Pattern Diagram Now Let’s try and understand the facade pattern better using a simple example. Let’s consider a hotel. This hotel has a hotel keeper. There are a lot of restaurants inside hotel e.g. Veg restaurants, Non-Veg restaurants and Veg/Non Both restaurants.You, as client want access to different menus of different restaurants . You do not know what are the different menus they have. You just have access to hotel keeper who knows his hotel well. Whichever menu you want, you tell the hotel keeper and he takes it out of from the respective restaurants and hands it over to you. Here, the hotel keeper acts as the facade, as he hides the complexities of the system hotel.Let’s see how it works : Interface of Hotel package structural.facade;public interface Hotel{ public Menus getMenus();} The hotel interface only returns Menus.Similarly, the Restaurant are of three types and can implement the hotel interface. Let’s have a look at the code for one of the Restaurants. NonVegRestaurant.java package structural.facade; public class NonVegRestaurant implements Hotel{ public Menus getMenus() { NonVegMenu nv = new NonVegMenu(); return nv; }} VegRestaurant.java package structural.facade; public class VegRestaurant implements Hotel{ public Menus getMenus() { VegMenu v = new VegMenu(); return v; }} VegNonBothRestaurant.java package structural.facade; public class VegNonBothRestaurant implements Hotel{ public Menus getMenus() { Both b = new Both(); return b; }} Now let’s consider the facade, HotelKeeper.java package structural.facade; public class HotelKeeper{ public VegMenu getVegMenu() { VegRestaurant v = new VegRestaurant(); VegMenu vegMenu = (VegMenu)v.getMenus(); return vegMenu; } public NonVegMenu getNonVegMenu() { NonVegRestaurant v = new NonVegRestaurant(); NonVegMenu NonvegMenu = (NonVegMenu)v.getMenus(); return NonvegMenu; } public Both getVegNonMenu() { VegNonBothRestaurant v = new VegNonBothRestaurant(); Both bothMenu = (Both)v.getMenus(); return bothMenu; } } From this, It is clear that the complex implementation will be done by HotelKeeper himself. The client will just access the HotelKeeper and ask for either Veg, NonVeg or VegNon Both Restaurant menu. How will the client program access this façade? package structural.facade; public class Client{ public static void main (String[] args) { HotelKeeper keeper = new HotelKeeper(); VegMenu v = keeper.getVegMenu(); NonVegMenu nv = keeper.getNonVegMenu(); Both = keeper.getVegNonMenu(); }} In this way the implementation is sent to the façade. The client is given just one interface and can access only that. This hides all the complexities. When Should this pattern be used? The facade pattern is appropriate when you have a complex system that you want to expose to clients in a simplified way, or you want to make an external communication layer over an existing system which is incompatible with the system. Facade deals with interfaces, not implementation. Its purpose is to hide internal complexity behind a single interface that appears simple on the outside. Further Read: Facade Method in Python This article is contributed by Saket 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. Design Pattern Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SDE SHEET - A Complete Guide for SDE Preparation Factory method design pattern in Java Unified Modeling Language (UML) | An Introduction Builder Design Pattern Unified Modeling Language (UML) | Activity Diagrams MVC Design Pattern Unified Modeling Language (UML) | State Diagrams Introduction of Programming Paradigms Monolithic vs Microservices architecture Unified Modeling Language (UML) | Class Diagrams
[ { "code": null, "e": 24212, "s": 24184, "text": "\n01 Sep, 2021" }, { "code": null, "e": 24432, "s": 24212, "text": "Facade is a part of Gang of Four design pattern and it is categorized under Structural design patterns. Before we dig into the details of it, let us discuss some examples which will be solved by this particular Pattern." }, { "code": null, "e": 24730, "s": 24432, "text": "So, As the name suggests, it means the face of the building. The people walking past the road can only see this glass face of the building. They do not know anything about it, the wiring, the pipes and other complexities. It hides all the complexities of the building and displays a friendly face." }, { "code": null, "e": 24744, "s": 24730, "text": "More examples" }, { "code": null, "e": 24996, "s": 24744, "text": "In Java, the interface JDBC can be called a facade because, we as users or clients create connection using the “java.sql.Connection” interface, the implementation of which we are not concerned about. The implementation is left to the vendor of driver." }, { "code": null, "e": 25432, "s": 24996, "text": "Another good example can be the startup of a computer. When a computer starts up, it involves the work of cpu, memory, hard drive, etc. To make it easy to use for users, we can add a facade which wrap the complexity of the task, and provide one simple interface instead.Same goes for the Facade Design Pattern. It hides the complexities of the system and provides an interface to the client from where the client can access the system." }, { "code": null, "e": 25462, "s": 25432, "text": "Facade Design Pattern Diagram" }, { "code": null, "e": 26152, "s": 25462, "text": "Now Let’s try and understand the facade pattern better using a simple example. Let’s consider a hotel. This hotel has a hotel keeper. There are a lot of restaurants inside hotel e.g. Veg restaurants, Non-Veg restaurants and Veg/Non Both restaurants.You, as client want access to different menus of different restaurants . You do not know what are the different menus they have. You just have access to hotel keeper who knows his hotel well. Whichever menu you want, you tell the hotel keeper and he takes it out of from the respective restaurants and hands it over to you. Here, the hotel keeper acts as the facade, as he hides the complexities of the system hotel.Let’s see how it works :" }, { "code": null, "e": 26171, "s": 26152, "text": "Interface of Hotel" }, { "code": "package structural.facade;public interface Hotel{ public Menus getMenus();}", "e": 26250, "s": 26171, "text": null }, { "code": null, "e": 26431, "s": 26250, "text": "The hotel interface only returns Menus.Similarly, the Restaurant are of three types and can implement the hotel interface. Let’s have a look at the code for one of the Restaurants." }, { "code": null, "e": 26453, "s": 26431, "text": "NonVegRestaurant.java" }, { "code": "package structural.facade; public class NonVegRestaurant implements Hotel{ public Menus getMenus() { NonVegMenu nv = new NonVegMenu(); return nv; }}", "e": 26626, "s": 26453, "text": null }, { "code": null, "e": 26645, "s": 26626, "text": "VegRestaurant.java" }, { "code": "package structural.facade; public class VegRestaurant implements Hotel{ public Menus getMenus() { VegMenu v = new VegMenu(); return v; }}", "e": 26807, "s": 26645, "text": null }, { "code": null, "e": 26833, "s": 26807, "text": "VegNonBothRestaurant.java" }, { "code": "package structural.facade; public class VegNonBothRestaurant implements Hotel{ public Menus getMenus() { Both b = new Both(); return b; }}", "e": 26996, "s": 26833, "text": null }, { "code": null, "e": 27027, "s": 26996, "text": "Now let’s consider the facade," }, { "code": null, "e": 27044, "s": 27027, "text": "HotelKeeper.java" }, { "code": "package structural.facade; public class HotelKeeper{ public VegMenu getVegMenu() { VegRestaurant v = new VegRestaurant(); VegMenu vegMenu = (VegMenu)v.getMenus(); return vegMenu; } public NonVegMenu getNonVegMenu() { NonVegRestaurant v = new NonVegRestaurant(); NonVegMenu NonvegMenu = (NonVegMenu)v.getMenus(); return NonvegMenu; } public Both getVegNonMenu() { VegNonBothRestaurant v = new VegNonBothRestaurant(); Both bothMenu = (Both)v.getMenus(); return bothMenu; } }", "e": 27623, "s": 27044, "text": null }, { "code": null, "e": 27822, "s": 27623, "text": "From this, It is clear that the complex implementation will be done by HotelKeeper himself. The client will just access the HotelKeeper and ask for either Veg, NonVeg or VegNon Both Restaurant menu." }, { "code": null, "e": 27871, "s": 27822, "text": "How will the client program access this façade?" }, { "code": "package structural.facade; public class Client{ public static void main (String[] args) { HotelKeeper keeper = new HotelKeeper(); VegMenu v = keeper.getVegMenu(); NonVegMenu nv = keeper.getNonVegMenu(); Both = keeper.getVegNonMenu(); }}", "e": 28158, "s": 27871, "text": null }, { "code": null, "e": 28311, "s": 28158, "text": "In this way the implementation is sent to the façade. The client is given just one interface and can access only that. This hides all the complexities." }, { "code": null, "e": 28345, "s": 28311, "text": "When Should this pattern be used?" }, { "code": null, "e": 28737, "s": 28345, "text": "The facade pattern is appropriate when you have a complex system that you want to expose to clients in a simplified way, or you want to make an external communication layer over an existing system which is incompatible with the system. Facade deals with interfaces, not implementation. Its purpose is to hide internal complexity behind a single interface that appears simple on the outside. " }, { "code": null, "e": 28775, "s": 28737, "text": "Further Read: Facade Method in Python" }, { "code": null, "e": 29070, "s": 28775, "text": "This article is contributed by Saket 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." }, { "code": null, "e": 29195, "s": 29070, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29210, "s": 29195, "text": "Design Pattern" }, { "code": null, "e": 29308, "s": 29210, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29317, "s": 29308, "text": "Comments" }, { "code": null, "e": 29330, "s": 29317, "text": "Old Comments" }, { "code": null, "e": 29379, "s": 29330, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 29417, "s": 29379, "text": "Factory method design pattern in Java" }, { "code": null, "e": 29467, "s": 29417, "text": "Unified Modeling Language (UML) | An Introduction" }, { "code": null, "e": 29490, "s": 29467, "text": "Builder Design Pattern" }, { "code": null, "e": 29542, "s": 29490, "text": "Unified Modeling Language (UML) | Activity Diagrams" }, { "code": null, "e": 29561, "s": 29542, "text": "MVC Design Pattern" }, { "code": null, "e": 29610, "s": 29561, "text": "Unified Modeling Language (UML) | State Diagrams" }, { "code": null, "e": 29648, "s": 29610, "text": "Introduction of Programming Paradigms" }, { "code": null, "e": 29689, "s": 29648, "text": "Monolithic vs Microservices architecture" } ]
Coding Neural Network — Forward Propagation and Backpropagtion | by Imad Dabbura | Towards Data Science
Why Neural Networks? According to Universal Approximate Theorem, Neural Networks can approximate as well as learn and represent any function given a large enough layer and desired error margin. The way neural network learns the true function is by building complex representations on top of simple ones. On each hidden layer, the neural network learns new feature space by first compute the affine (linear) transformations of the given inputs and then apply non-linear function which in turn will be the input of the next layer. This process will continue until we reach the output layer. Therefore, we can define neural network as information flows from inputs through hidden layers towards the output. For a 3-layers neural network, the learned function would be: f(x) = f_3(f_2(f_1(x))) where: f_1(x): Function learned on first hidden layer f_2(x): Function learned on second hidden layer f_3(x): Function learned on output layer Therefore, on each layer we learn different representation that gets more complicated with later hidden layers.Below is an example of a 3-layers neural network (we don’t count input layer): For example, computers can’t understand images directly and don’t know what to do with pixels data. However, a neural network can build a simple representation of the image in the early hidden layers that identifies edges. Given the first hidden layer output, it can learn corners and contours. Given the second hidden layer, it can learn parts such as nose. Finally, it can learn the object identity. Since truth is never linear and representation is very critical to the performance of a machine learning algorithm, neural network can help us build very complex models and leave it to the algorithm to learn such representations without worrying about feature engineering that takes practitioners very long time and effort to curate a good representation. The post has two parts: Coding the neural network: This entails writing all the helper functions that would allow us to implement a multi-layer neural network. While doing so, I’ll explain the theoretical parts whenever possible and give some advices on implementations.Application: We’ll implement the neural network we coded in the first part on image recognition problem to see if the network we built will be able to detect if the image has a cat or a dog and see it working :) Coding the neural network: This entails writing all the helper functions that would allow us to implement a multi-layer neural network. While doing so, I’ll explain the theoretical parts whenever possible and give some advices on implementations. Application: We’ll implement the neural network we coded in the first part on image recognition problem to see if the network we built will be able to detect if the image has a cat or a dog and see it working :) This post will be the first in a series of posts that cover implementing neural network in numpy including gradient checking, parameter initialization, L2 regularization, dropout. The source code that created this post can be found here. # Import packagesimport h5py importmatplotlib.pyplot as pltimport numpy as npimport seaborn as sns The input X provides the initial information that then propagates to the hidden units at each layer and finally produce the output y^. The architecture of the network entails determining its depth, width, and activation functions used on each layer. Depth is the number of hidden layers. Width is the number of units (nodes) on each hidden layer since we don’t control neither input layer nor output layer dimensions. There are quite a few set of activation functions such Rectified Linear Unit, Sigmoid, Hyperbolic tangent, etc. Research has proven that deeper networks outperform networks with more hidden units. Therefore, it’s always better and won’t hurt to train a deeper network (with diminishing returns). Lets first introduce some notations that will be used throughout the post: Next, we’ll write down the dimensions of a multi-layer neural network in the general form to help us in matrix multiplication because one of the major challenges in implementing a neural network is getting the dimensions right. The two equations we need to implement forward propagations are: These computations will take place on each layer. We’ll first initialize the weight matrices and the bias vectors. It’s important to note that we shouldn’t initialize all the parameters to zero because doing so will lead the gradients to be equal and on each iteration the output would be the same and the learning algorithm won’t learn anything. Therefore, it’s important to randomly initialize the parameters to values between 0 and 1. It’s also recommended to multiply the random values by small scalar such as 0.01 to make the activation units active and be on the regions where activation functions’ derivatives are not close to zero. There is no definitive guide for which activation function works best on specific problems. It’s a trial and error process where one should try different set of functions and see which one works best on the problem at hand. We’ll cover 4 of the most commonly used activation functions: Sigmoid function (σ): g(z) = 1 / (1 + e^{-z}). It’s recommended to be used only on the output layer so that we can easily interpret the output as probabilities since it has restricted output between 0 and 1. One of the main disadvantages for using sigmoid function on hidden layers is that the gradient is very close to zero over a large portion of its domain which makes it slow and harder for the learning algorithm to learn. Hyperbolic Tangent function: g(z) = (e^z -e^{-z}) / (e^z + e^{-z}). It’s superior to sigmoid function in which the mean of its output is very close to zero, which in other words center the output of the activation units around zero and make the range of values very small which means faster to learn. The disadvantage that it shares with sigmoid function is that the gradient is very small on good portion of the domain. Rectified Linear Unit (ReLU): g(z) = max{0, z}. The models that are close to linear are easy to optimize. Since ReLU shares a lot of the properties of linear functions, it tends to work well on most of the problems. The only issue is that the derivative is not defined at z = 0, which we can overcome by assigning the derivative to 0 at z = 0. However, this means that for z ≤ 0 the gradient is zero and again can’t learn. Leaky Rectified Linear Unit: g(z) = max{α*z, z}. It overcomes the zero gradient issue from ReLU and assigns α which is a small value for z ≤ 0. If you’re not sure which activation function to choose, start with ReLU. Next, we’ll implement the above activation functions and draw a graph for each one to make it easier to see the domain and range of each function. Given its inputs from previous layer, each unit computes affine transformation z = W^Tx + b and then apply an activation function g(z) such as ReLU element-wise. During the process, we’ll store (cache) all variables computed and used on each layer to be used in back-propagation. We’ll write first two helper functions that will be used in the L-model forward propagation to make it easier to debug. Keep in mind that on each layer, we may have different activation function. We’ll use the binary Cross-Entropy cost. It uses the log-likelihood method to estimate its error. The cost is: The above cost function is convex; however, neural network usually stuck on a local minimum and is not guaranteed to find the optimal parameters. We’ll use here gradient-based learning. Allows the information to go back from the cost backward through the network in order to compute the gradient. Therefore, loop over the nodes starting at the final node in reverse topological order to compute the derivative of the final node output with respect to each edge’s node tail. Doing so will help us know who is responsible for the most error and change the parameters in that direction. The following derivatives’ formulas will help us write the back-propagate functions: Since b^l is always a vector, the sum would be across rows (since each column is an example). The dataset that we’ll be working on has 209 images. Each image is 64 x 64 pixels on RGB scale. We’ll build a neural network to classify if the image has a cat or not. Therefore, y^i ∈ {0, 1}. We’ll first load the images. Show sample image for a cat. Reshape input matrix so that each column would be one example. Also, since each image is 64 x 64 x 3, we’ll end up having 12,288 features for each image. Therefore, the input matrix would be 12,288 x 209. Standardize the data so that the gradients don’t go out of control. Also, it will help hidden units have similar range of values. For now, we’ll divide every pixel by 255 which shouldn’t be an issue. However, it’s better to standardize the data to have a mean of 0 and a standard deviation of 1. Original dimensions:--------------------Training: (209, 64, 64, 3), (209,)Test: (50, 64, 64, 3), (50,)New dimensions:---------------Training: (12288, 209), (1, 209)Test: (12288, 50), (1, 50) Now, our dataset is ready to be used and test our neural network implementation. Let’s first write multi-layer model function to implement gradient-based learning using predefined number of iterations and learning rate. Next, we’ll train two versions of the neural network where each one will use different activation function on hidden layers: One will use rectified linear unit (ReLU) and the second one will use hyperbolic tangent function (tanh). Finally we’ll use the parameters we get from both neural networks to classify training examples and compute the training accuracy rates for each version to see which activation function works best on this problem. # Setting layers dimslayers_dims = [X_train.shape[0], 5, 5, 1]# NN with tanh activation fnparameters_tanh = L_layer_model( X_train, y_train, layers_dims, learning_rate=0.03, num_iterations=3000, hidden_layers_activation_fn="tanh")# Print the accuracyaccuracy(X_test, parameters_tanh, y_test, activation_fn="tanh")The cost after 100 iterations is: 0.6556 The cost after 200 iterations is: 0.6468The cost after 300 iterations is: 0.6447The cost after 400 iterations is: 0.6441The cost after 500 iterations is: 0.6440The cost after 600 iterations is: 0.6440The cost after 700 iterations is: 0.6440The cost after 800 iterations is: 0.6439The cost after 900 iterations is: 0.6439The cost after 1000 iterations is: 0.6439The cost after 1100 iterations is: 0.6439The cost after 1200 iterations is: 0.6439The cost after 1300 iterations is: 0.6438The cost after 1400 iterations is: 0.6438The cost after 1500 iterations is: 0.6437The cost after 1600 iterations is: 0.6434The cost after 1700 iterations is: 0.6429The cost after 1800 iterations is: 0.6413The cost after 1900 iterations is: 0.6361The cost after 2000 iterations is: 0.6124The cost after 2100 iterations is: 0.5112The cost after 2200 iterations is: 0.5288The cost after 2300 iterations is: 0.4312The cost after 2400 iterations is: 0.3821The cost after 2500 iterations is: 0.3387The cost after 2600 iterations is: 0.2349The cost after 2700 iterations is: 0.2206The cost after 2800 iterations is: 0.1927The cost after 2900 iterations is: 0.4669The cost after 3000 iterations is: 0.1040 'The accuracy rate is: 68.00%.' # NN with relu activation fnparameters_relu = L_layer_model( X_train, y_train, layers_dims, learning_rate=0.03, num_iterations=3000, hidden_layers_activation_fn="relu")# Print the accuracyaccuracy(X_test, parameters_relu, y_test, activation_fn="relu")The cost after 100 iterations is: 0.6556The cost after 200 iterations is: 0.6468The cost after 300 iterations is: 0.6447The cost after 400 iterations is: 0.6441The cost after 500 iterations is: 0.6440The cost after 600 iterations is: 0.6440 The cost after 700 iterations is: 0.6440 The cost after 800 iterations is: 0.6440 The cost after 900 iterations is: 0.6440 The cost after 1000 iterations is: 0.6440 The cost after 1100 iterations is: 0.6439 The cost after 1200 iterations is: 0.6439 The cost after 1300 iterations is: 0.6439 The cost after 1400 iterations is: 0.6439 The cost after 1500 iterations is: 0.6439 The cost after 1600 iterations is: 0.6439 The cost after 1700 iterations is: 0.6438 The cost after 1800 iterations is: 0.6437 The cost after 1900 iterations is: 0.6435 The cost after 2000 iterations is: 0.6432 The cost after 2100 iterations is: 0.6423 The cost after 2200 iterations is: 0.6395 The cost after 2300 iterations is: 0.6259 The cost after 2400 iterations is: 0.5408 The cost after 2500 iterations is: 0.5262 The cost after 2600 iterations is: 0.4727 The cost after 2700 iterations is: 0.4386 The cost after 2800 iterations is: 0.3493 The cost after 2900 iterations is: 0.1877 The cost after 3000 iterations is: 0.3641'The accuracy rate is: 42.00%.' Please note that the accuracy rates above are expected to overestimate the generalization accuracy rates. The purpose of this post is to code Deep Neural Network step-by-step and explain the important concepts while doing that. We don’t really care about the accuracy rate at this moment since there are tons of things we could’ve done to increase the accuracy which would be the subject of following posts. Below are some takeaways: Even if neural network can represent any function, it may fail to learn for two reasons: The optimization algorithm may fail to find the best value for the parameters of the desired (true) function. It can stuck in a local optimum.The learning algorithm may find different functional form that is different than the intended function due to overfitting. The optimization algorithm may fail to find the best value for the parameters of the desired (true) function. It can stuck in a local optimum. The learning algorithm may find different functional form that is different than the intended function due to overfitting. Even if neural network rarely converges and always stuck in a local minimum, it is still able to reduce the cost significantly and come up with very complex models with high test accuracy. The neural network we used in this post is standard fully connected network. However, there are two other kinds of networks: Convolutional NN: Where not all nodes are connected. It’s best in class for image recognition.Recurrent NN: There is a feedback connections where output of the model is fed back into itself. It’s used mainly in sequence modeling. Convolutional NN: Where not all nodes are connected. It’s best in class for image recognition. Recurrent NN: There is a feedback connections where output of the model is fed back into itself. It’s used mainly in sequence modeling. The fully connected neural network also forgets what happened in previous steps and also doesn’t know anything about the output. There are number of hyperparameters that we can tune using cross validation to get the best performance of our network: Learning rate (α): Determines how big the step for each update of parameters. Learning rate (α): Determines how big the step for each update of parameters. A. Small α leads to slow convergence and may become computationally very expensive. B. Large α may lead to overshooting where our learning algorithm may never converge. 2. Number of hidden layers (depth): The more hidden layers the better, but comes at a cost computationally. 3. Number of units per hidden layer (width): Research proven that huge number of hidden units per layer doesn’t add to the improvement of the network. 4. Activation function: Which function to use on hidden layers differs among applications and domains. It’s a trial and error process to try different functions and see which one works best. 5. Number of iterations. Standardize data would help activation units have similar range of values and avoid gradients to go out of control. Originally published at imaddabbura.github.io on April 1, 2018.
[ { "code": null, "e": 193, "s": 172, "text": "Why Neural Networks?" }, { "code": null, "e": 969, "s": 193, "text": "According to Universal Approximate Theorem, Neural Networks can approximate as well as learn and represent any function given a large enough layer and desired error margin. The way neural network learns the true function is by building complex representations on top of simple ones. On each hidden layer, the neural network learns new feature space by first compute the affine (linear) transformations of the given inputs and then apply non-linear function which in turn will be the input of the next layer. This process will continue until we reach the output layer. Therefore, we can define neural network as information flows from inputs through hidden layers towards the output. For a 3-layers neural network, the learned function would be: f(x) = f_3(f_2(f_1(x))) where:" }, { "code": null, "e": 1016, "s": 969, "text": "f_1(x): Function learned on first hidden layer" }, { "code": null, "e": 1064, "s": 1016, "text": "f_2(x): Function learned on second hidden layer" }, { "code": null, "e": 1105, "s": 1064, "text": "f_3(x): Function learned on output layer" }, { "code": null, "e": 1295, "s": 1105, "text": "Therefore, on each layer we learn different representation that gets more complicated with later hidden layers.Below is an example of a 3-layers neural network (we don’t count input layer):" }, { "code": null, "e": 1697, "s": 1295, "text": "For example, computers can’t understand images directly and don’t know what to do with pixels data. However, a neural network can build a simple representation of the image in the early hidden layers that identifies edges. Given the first hidden layer output, it can learn corners and contours. Given the second hidden layer, it can learn parts such as nose. Finally, it can learn the object identity." }, { "code": null, "e": 2053, "s": 1697, "text": "Since truth is never linear and representation is very critical to the performance of a machine learning algorithm, neural network can help us build very complex models and leave it to the algorithm to learn such representations without worrying about feature engineering that takes practitioners very long time and effort to curate a good representation." }, { "code": null, "e": 2077, "s": 2053, "text": "The post has two parts:" }, { "code": null, "e": 2535, "s": 2077, "text": "Coding the neural network: This entails writing all the helper functions that would allow us to implement a multi-layer neural network. While doing so, I’ll explain the theoretical parts whenever possible and give some advices on implementations.Application: We’ll implement the neural network we coded in the first part on image recognition problem to see if the network we built will be able to detect if the image has a cat or a dog and see it working :)" }, { "code": null, "e": 2782, "s": 2535, "text": "Coding the neural network: This entails writing all the helper functions that would allow us to implement a multi-layer neural network. While doing so, I’ll explain the theoretical parts whenever possible and give some advices on implementations." }, { "code": null, "e": 2994, "s": 2782, "text": "Application: We’ll implement the neural network we coded in the first part on image recognition problem to see if the network we built will be able to detect if the image has a cat or a dog and see it working :)" }, { "code": null, "e": 3232, "s": 2994, "text": "This post will be the first in a series of posts that cover implementing neural network in numpy including gradient checking, parameter initialization, L2 regularization, dropout. The source code that created this post can be found here." }, { "code": null, "e": 3331, "s": 3232, "text": "# Import packagesimport h5py importmatplotlib.pyplot as pltimport numpy as npimport seaborn as sns" }, { "code": null, "e": 4045, "s": 3331, "text": "The input X provides the initial information that then propagates to the hidden units at each layer and finally produce the output y^. The architecture of the network entails determining its depth, width, and activation functions used on each layer. Depth is the number of hidden layers. Width is the number of units (nodes) on each hidden layer since we don’t control neither input layer nor output layer dimensions. There are quite a few set of activation functions such Rectified Linear Unit, Sigmoid, Hyperbolic tangent, etc. Research has proven that deeper networks outperform networks with more hidden units. Therefore, it’s always better and won’t hurt to train a deeper network (with diminishing returns)." }, { "code": null, "e": 4120, "s": 4045, "text": "Lets first introduce some notations that will be used throughout the post:" }, { "code": null, "e": 4348, "s": 4120, "text": "Next, we’ll write down the dimensions of a multi-layer neural network in the general form to help us in matrix multiplication because one of the major challenges in implementing a neural network is getting the dimensions right." }, { "code": null, "e": 4463, "s": 4348, "text": "The two equations we need to implement forward propagations are: These computations will take place on each layer." }, { "code": null, "e": 5053, "s": 4463, "text": "We’ll first initialize the weight matrices and the bias vectors. It’s important to note that we shouldn’t initialize all the parameters to zero because doing so will lead the gradients to be equal and on each iteration the output would be the same and the learning algorithm won’t learn anything. Therefore, it’s important to randomly initialize the parameters to values between 0 and 1. It’s also recommended to multiply the random values by small scalar such as 0.01 to make the activation units active and be on the regions where activation functions’ derivatives are not close to zero." }, { "code": null, "e": 5339, "s": 5053, "text": "There is no definitive guide for which activation function works best on specific problems. It’s a trial and error process where one should try different set of functions and see which one works best on the problem at hand. We’ll cover 4 of the most commonly used activation functions:" }, { "code": null, "e": 5767, "s": 5339, "text": "Sigmoid function (σ): g(z) = 1 / (1 + e^{-z}). It’s recommended to be used only on the output layer so that we can easily interpret the output as probabilities since it has restricted output between 0 and 1. One of the main disadvantages for using sigmoid function on hidden layers is that the gradient is very close to zero over a large portion of its domain which makes it slow and harder for the learning algorithm to learn." }, { "code": null, "e": 6188, "s": 5767, "text": "Hyperbolic Tangent function: g(z) = (e^z -e^{-z}) / (e^z + e^{-z}). It’s superior to sigmoid function in which the mean of its output is very close to zero, which in other words center the output of the activation units around zero and make the range of values very small which means faster to learn. The disadvantage that it shares with sigmoid function is that the gradient is very small on good portion of the domain." }, { "code": null, "e": 6611, "s": 6188, "text": "Rectified Linear Unit (ReLU): g(z) = max{0, z}. The models that are close to linear are easy to optimize. Since ReLU shares a lot of the properties of linear functions, it tends to work well on most of the problems. The only issue is that the derivative is not defined at z = 0, which we can overcome by assigning the derivative to 0 at z = 0. However, this means that for z ≤ 0 the gradient is zero and again can’t learn." }, { "code": null, "e": 6755, "s": 6611, "text": "Leaky Rectified Linear Unit: g(z) = max{α*z, z}. It overcomes the zero gradient issue from ReLU and assigns α which is a small value for z ≤ 0." }, { "code": null, "e": 6975, "s": 6755, "text": "If you’re not sure which activation function to choose, start with ReLU. Next, we’ll implement the above activation functions and draw a graph for each one to make it easier to see the domain and range of each function." }, { "code": null, "e": 7451, "s": 6975, "text": "Given its inputs from previous layer, each unit computes affine transformation z = W^Tx + b and then apply an activation function g(z) such as ReLU element-wise. During the process, we’ll store (cache) all variables computed and used on each layer to be used in back-propagation. We’ll write first two helper functions that will be used in the L-model forward propagation to make it easier to debug. Keep in mind that on each layer, we may have different activation function." }, { "code": null, "e": 7748, "s": 7451, "text": "We’ll use the binary Cross-Entropy cost. It uses the log-likelihood method to estimate its error. The cost is: The above cost function is convex; however, neural network usually stuck on a local minimum and is not guaranteed to find the optimal parameters. We’ll use here gradient-based learning." }, { "code": null, "e": 8325, "s": 7748, "text": "Allows the information to go back from the cost backward through the network in order to compute the gradient. Therefore, loop over the nodes starting at the final node in reverse topological order to compute the derivative of the final node output with respect to each edge’s node tail. Doing so will help us know who is responsible for the most error and change the parameters in that direction. The following derivatives’ formulas will help us write the back-propagate functions: Since b^l is always a vector, the sum would be across rows (since each column is an example)." }, { "code": null, "e": 8518, "s": 8325, "text": "The dataset that we’ll be working on has 209 images. Each image is 64 x 64 pixels on RGB scale. We’ll build a neural network to classify if the image has a cat or not. Therefore, y^i ∈ {0, 1}." }, { "code": null, "e": 8547, "s": 8518, "text": "We’ll first load the images." }, { "code": null, "e": 8576, "s": 8547, "text": "Show sample image for a cat." }, { "code": null, "e": 8781, "s": 8576, "text": "Reshape input matrix so that each column would be one example. Also, since each image is 64 x 64 x 3, we’ll end up having 12,288 features for each image. Therefore, the input matrix would be 12,288 x 209." }, { "code": null, "e": 9077, "s": 8781, "text": "Standardize the data so that the gradients don’t go out of control. Also, it will help hidden units have similar range of values. For now, we’ll divide every pixel by 255 which shouldn’t be an issue. However, it’s better to standardize the data to have a mean of 0 and a standard deviation of 1." }, { "code": null, "e": 9268, "s": 9077, "text": "Original dimensions:--------------------Training: (209, 64, 64, 3), (209,)Test: (50, 64, 64, 3), (50,)New dimensions:---------------Training: (12288, 209), (1, 209)Test: (12288, 50), (1, 50)" }, { "code": null, "e": 9488, "s": 9268, "text": "Now, our dataset is ready to be used and test our neural network implementation. Let’s first write multi-layer model function to implement gradient-based learning using predefined number of iterations and learning rate." }, { "code": null, "e": 9933, "s": 9488, "text": "Next, we’ll train two versions of the neural network where each one will use different activation function on hidden layers: One will use rectified linear unit (ReLU) and the second one will use hyperbolic tangent function (tanh). Finally we’ll use the parameters we get from both neural networks to classify training examples and compute the training accuracy rates for each version to see which activation function works best on this problem." }, { "code": null, "e": 11501, "s": 9933, "text": "# Setting layers dimslayers_dims = [X_train.shape[0], 5, 5, 1]# NN with tanh activation fnparameters_tanh = L_layer_model( X_train, y_train, layers_dims, learning_rate=0.03, num_iterations=3000, hidden_layers_activation_fn=\"tanh\")# Print the accuracyaccuracy(X_test, parameters_tanh, y_test, activation_fn=\"tanh\")The cost after 100 iterations is: 0.6556 The cost after 200 iterations is: 0.6468The cost after 300 iterations is: 0.6447The cost after 400 iterations is: 0.6441The cost after 500 iterations is: 0.6440The cost after 600 iterations is: 0.6440The cost after 700 iterations is: 0.6440The cost after 800 iterations is: 0.6439The cost after 900 iterations is: 0.6439The cost after 1000 iterations is: 0.6439The cost after 1100 iterations is: 0.6439The cost after 1200 iterations is: 0.6439The cost after 1300 iterations is: 0.6438The cost after 1400 iterations is: 0.6438The cost after 1500 iterations is: 0.6437The cost after 1600 iterations is: 0.6434The cost after 1700 iterations is: 0.6429The cost after 1800 iterations is: 0.6413The cost after 1900 iterations is: 0.6361The cost after 2000 iterations is: 0.6124The cost after 2100 iterations is: 0.5112The cost after 2200 iterations is: 0.5288The cost after 2300 iterations is: 0.4312The cost after 2400 iterations is: 0.3821The cost after 2500 iterations is: 0.3387The cost after 2600 iterations is: 0.2349The cost after 2700 iterations is: 0.2206The cost after 2800 iterations is: 0.1927The cost after 2900 iterations is: 0.4669The cost after 3000 iterations is: 0.1040 'The accuracy rate is: 68.00%.'" }, { "code": null, "e": 13029, "s": 11501, "text": "# NN with relu activation fnparameters_relu = L_layer_model( X_train, y_train, layers_dims, learning_rate=0.03, num_iterations=3000, hidden_layers_activation_fn=\"relu\")# Print the accuracyaccuracy(X_test, parameters_relu, y_test, activation_fn=\"relu\")The cost after 100 iterations is: 0.6556The cost after 200 iterations is: 0.6468The cost after 300 iterations is: 0.6447The cost after 400 iterations is: 0.6441The cost after 500 iterations is: 0.6440The cost after 600 iterations is: 0.6440 The cost after 700 iterations is: 0.6440 The cost after 800 iterations is: 0.6440 The cost after 900 iterations is: 0.6440 The cost after 1000 iterations is: 0.6440 The cost after 1100 iterations is: 0.6439 The cost after 1200 iterations is: 0.6439 The cost after 1300 iterations is: 0.6439 The cost after 1400 iterations is: 0.6439 The cost after 1500 iterations is: 0.6439 The cost after 1600 iterations is: 0.6439 The cost after 1700 iterations is: 0.6438 The cost after 1800 iterations is: 0.6437 The cost after 1900 iterations is: 0.6435 The cost after 2000 iterations is: 0.6432 The cost after 2100 iterations is: 0.6423 The cost after 2200 iterations is: 0.6395 The cost after 2300 iterations is: 0.6259 The cost after 2400 iterations is: 0.5408 The cost after 2500 iterations is: 0.5262 The cost after 2600 iterations is: 0.4727 The cost after 2700 iterations is: 0.4386 The cost after 2800 iterations is: 0.3493 The cost after 2900 iterations is: 0.1877 The cost after 3000 iterations is: 0.3641'The accuracy rate is: 42.00%.'" }, { "code": null, "e": 13135, "s": 13029, "text": "Please note that the accuracy rates above are expected to overestimate the generalization accuracy rates." }, { "code": null, "e": 13463, "s": 13135, "text": "The purpose of this post is to code Deep Neural Network step-by-step and explain the important concepts while doing that. We don’t really care about the accuracy rate at this moment since there are tons of things we could’ve done to increase the accuracy which would be the subject of following posts. Below are some takeaways:" }, { "code": null, "e": 13552, "s": 13463, "text": "Even if neural network can represent any function, it may fail to learn for two reasons:" }, { "code": null, "e": 13817, "s": 13552, "text": "The optimization algorithm may fail to find the best value for the parameters of the desired (true) function. It can stuck in a local optimum.The learning algorithm may find different functional form that is different than the intended function due to overfitting." }, { "code": null, "e": 13960, "s": 13817, "text": "The optimization algorithm may fail to find the best value for the parameters of the desired (true) function. It can stuck in a local optimum." }, { "code": null, "e": 14083, "s": 13960, "text": "The learning algorithm may find different functional form that is different than the intended function due to overfitting." }, { "code": null, "e": 14272, "s": 14083, "text": "Even if neural network rarely converges and always stuck in a local minimum, it is still able to reduce the cost significantly and come up with very complex models with high test accuracy." }, { "code": null, "e": 14397, "s": 14272, "text": "The neural network we used in this post is standard fully connected network. However, there are two other kinds of networks:" }, { "code": null, "e": 14627, "s": 14397, "text": "Convolutional NN: Where not all nodes are connected. It’s best in class for image recognition.Recurrent NN: There is a feedback connections where output of the model is fed back into itself. It’s used mainly in sequence modeling." }, { "code": null, "e": 14722, "s": 14627, "text": "Convolutional NN: Where not all nodes are connected. It’s best in class for image recognition." }, { "code": null, "e": 14858, "s": 14722, "text": "Recurrent NN: There is a feedback connections where output of the model is fed back into itself. It’s used mainly in sequence modeling." }, { "code": null, "e": 14987, "s": 14858, "text": "The fully connected neural network also forgets what happened in previous steps and also doesn’t know anything about the output." }, { "code": null, "e": 15107, "s": 14987, "text": "There are number of hyperparameters that we can tune using cross validation to get the best performance of our network:" }, { "code": null, "e": 15185, "s": 15107, "text": "Learning rate (α): Determines how big the step for each update of parameters." }, { "code": null, "e": 15263, "s": 15185, "text": "Learning rate (α): Determines how big the step for each update of parameters." }, { "code": null, "e": 15347, "s": 15263, "text": "A. Small α leads to slow convergence and may become computationally very expensive." }, { "code": null, "e": 15432, "s": 15347, "text": "B. Large α may lead to overshooting where our learning algorithm may never converge." }, { "code": null, "e": 15540, "s": 15432, "text": "2. Number of hidden layers (depth): The more hidden layers the better, but comes at a cost computationally." }, { "code": null, "e": 15691, "s": 15540, "text": "3. Number of units per hidden layer (width): Research proven that huge number of hidden units per layer doesn’t add to the improvement of the network." }, { "code": null, "e": 15882, "s": 15691, "text": "4. Activation function: Which function to use on hidden layers differs among applications and domains. It’s a trial and error process to try different functions and see which one works best." }, { "code": null, "e": 15907, "s": 15882, "text": "5. Number of iterations." }, { "code": null, "e": 16023, "s": 15907, "text": "Standardize data would help activation units have similar range of values and avoid gradients to go out of control." } ]
How do I open Chrome in selenium WebDriver?
We can open Chrome browser in Selenium webdriver. We can launch Chrome by instantiating an object of the ChromeDriver class with the help of the below statement. WebDriver driver = new ChromeDriver(); Next we have to download the chromedriver and configure it to our project by following the below step by step processes − Navigate to the link − https://www.selenium.dev/downloads/ and below the Browser, there is a Chrome section available. Click on the documentation link just below that. Navigate to the link − https://www.selenium.dev/downloads/ and below the Browser, there is a Chrome section available. Click on the documentation link just below that. As per version of the Chrome browser in the system, we have to select the download link. The next page shall be navigated where links to chrome drivers compatible with various operating systems are present. As per version of the Chrome browser in the system, we have to select the download link. The next page shall be navigated where links to chrome drivers compatible with various operating systems are present. After selecting the chrome driver as per the system configuration for download, a zip file gets created. We need to extract that and save the chromedriver.exe file at any location. After selecting the chrome driver as per the system configuration for download, a zip file gets created. We need to extract that and save the chromedriver.exe file at any location. Let us discuss how to configure chromedriver with System properties within the Selenium code − Add the System.setProperty method in the code which takes the browser type and the path of the chromedriver executable path as parameters. Add the System.setProperty method in the code which takes the browser type and the path of the chromedriver executable path as parameters. System.setProperty("webdriver.chrome.driver","<chromedriver path>"); Code Implementation import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class ChromeBrw{ public static void main(String[] args) { // creating object of ChromeDriver WebDriver driver = new ChromeDriver(); // to configure the path of the chromedriver.exe System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); String url = "https://www.tutorialspoint.com/index.htm"; driver.get(url); } }
[ { "code": null, "e": 1224, "s": 1062, "text": "We can open Chrome browser in Selenium webdriver. We can launch Chrome by instantiating an object of the ChromeDriver class with the help of the below statement." }, { "code": null, "e": 1263, "s": 1224, "text": "WebDriver driver = new ChromeDriver();" }, { "code": null, "e": 1385, "s": 1263, "text": "Next we have to download the chromedriver and configure it to our project by following the below step by step processes −" }, { "code": null, "e": 1553, "s": 1385, "text": "Navigate to the link − https://www.selenium.dev/downloads/ and below the Browser, there is a Chrome section available. Click on the documentation link just below that." }, { "code": null, "e": 1721, "s": 1553, "text": "Navigate to the link − https://www.selenium.dev/downloads/ and below the Browser, there is a Chrome section available. Click on the documentation link just below that." }, { "code": null, "e": 1928, "s": 1721, "text": "As per version of the Chrome browser in the system, we have to select the download link. The next page shall be navigated where links to chrome drivers compatible with various operating systems are present." }, { "code": null, "e": 2135, "s": 1928, "text": "As per version of the Chrome browser in the system, we have to select the download link. The next page shall be navigated where links to chrome drivers compatible with various operating systems are present." }, { "code": null, "e": 2316, "s": 2135, "text": "After selecting the chrome driver as per the system configuration for download, a zip file gets created. We need to extract that and save the chromedriver.exe file at any location." }, { "code": null, "e": 2497, "s": 2316, "text": "After selecting the chrome driver as per the system configuration for download, a zip file gets created. We need to extract that and save the chromedriver.exe file at any location." }, { "code": null, "e": 2592, "s": 2497, "text": "Let us discuss how to configure chromedriver with System properties within the Selenium code −" }, { "code": null, "e": 2731, "s": 2592, "text": "Add the System.setProperty method in the code which takes the browser type and the path of the chromedriver executable path as parameters." }, { "code": null, "e": 2870, "s": 2731, "text": "Add the System.setProperty method in the code which takes the browser type and the path of the chromedriver executable path as parameters." }, { "code": null, "e": 2939, "s": 2870, "text": "System.setProperty(\"webdriver.chrome.driver\",\"<chromedriver path>\");" }, { "code": null, "e": 2959, "s": 2939, "text": "Code Implementation" }, { "code": null, "e": 3455, "s": 2959, "text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.chrome.ChromeDriver;\npublic class ChromeBrw{\n public static void main(String[] args) {\n // creating object of ChromeDriver\n WebDriver driver = new ChromeDriver();\n // to configure the path of the chromedriver.exe\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n String url = \"https://www.tutorialspoint.com/index.htm\";\n driver.get(url);\n }\n}" } ]
Julia - Dictionaries and Sets
Many of the functions we have seen so far are working on arrays and tuples. Arrays are just one type of collection, but Julia has other kind of collections too. One such collection is Dictionary object which associates keys with values. That is why it is called an ‘associative collection’. To understand it better, we can compare it with simple look-up table in which many types of data are organized and provide us the single piece of information such as number, string or symbol called the key. It doesn’t provide us the corresponding data value. The syntax for creating a simple dictionary is as follows − Dict(“key1” => value1, “key2” => value2,,..., “keyn” => valuen) In the above syntax, key1, key2...keyn are the keys and value1, value2,...valuen are the corresponding values. The operator => is the Pair() function. We can not have two keys with the same name because keys are always unique in dictionaries. julia> first_dict = Dict("X" => 100, "Y" => 110, "Z" => 220) Dict{String,Int64} with 3 entries: "Y" => 110 "Z" => 220 "X" => 100 We can also create dictionaries with the help of comprehension syntax. The example is given below − julia> first_dict = Dict(string(x) => sind(x) for x = 0:5:360) Dict{String,Float64} with 73 entries: "320" => -0.642788 "65" => 0.906308 "155" => 0.422618 "335" => -0.422618 "75" => 0.965926 "50" => 0.766044 ⋮ => ⋮ As discussed earlier, dictionaries have unique keys. It means that if we assign a value to a key that already exists, we will not be creating a new one but modifying the existing key. Following are some operations on dictionaries regarding keys − We can use haskey() function to check whether the dictionary contains a key or not − julia> first_dict = Dict("X" => 100, "Y" => 110, "Z" => 220) Dict{String,Int64} with 3 entries: "Y" => 110 "Z" => 220 "X" => 100 julia> haskey(first_dict, "Z") true julia> haskey(first_dict, "A") false We can use in() function to check whether the dictionary contains a key/value pair or not − julia> in(("X" => 100), first_dict) true julia> in(("X" => 220), first_dict) false We can add a new key-value in the existing dictionary as follows − julia> first_dict["R"] = 400 400 julia> first_dict Dict{String,Int64} with 4 entries: "Y" => 110 "Z" => 220 "X" => 100 "R" => 400 We can use delete!() function to delete a key from an existing dictionary − julia> delete!(first_dict, "R") Dict{String,Int64} with 3 entries: "Y" => 110 "Z" => 220 "X" => 100 We can use keys() function to get all the keys from an existing dictionary − julia> keys(first_dict) Base.KeySet for a Dict{String,Int64} with 3 entries. Keys: "Y" "Z" "X" Every key in dictionary has a corresponding value. Following are some operations on dictionaries regarding values − We can use values() function to get all the values from an existing dictionary − julia> values(first_dict) Base.ValueIterator for a Dict{String,Int64} with 3 entries. Values: 110 220 100 We can process each key/value pair to see the dictionaries are actually iterable objects − for kv in first_dict println(kv) end "Y" => 110 "Z" => 220 "X" => 100 Here the kv is a tuple that contains each key/value pair. Dictionaries do not store the keys in any particular order hence the output of the dictionary would not be a sorted array. To obtain items in order, we can sort the dictionary − julia> first_dict = Dict("R" => 100, "S" => 220, "T" => 350, "U" => 400, "V" => 575, "W" => 670) Dict{String,Int64} with 6 entries: "S" => 220 "U" => 400 "T" => 350 "W" => 670 "V" => 575 "R" => 100 julia> for key in sort(collect(keys(first_dict))) println("$key => $(first_dict[key])") end R => 100 S => 220 T => 350 U => 400 V => 575 W => 670 We can also use SortedDict data type from the DataStructures.ji Julia package to make sure that the dictionary remains sorted all the times. You can check the example below − julia> import DataStructures julia> first_dict = DataStructures.SortedDict("S" => 220, "T" => 350, "U" => 400, "V" => 575, "W" => 670) DataStructures.SortedDict{String,Int64,Base.Order.ForwardOrdering} with 5 entries: "S" => 220 "T" => 350 "U" => 400 "V" => 575 "W" => 670 julia> first_dict["R"] = 100 100 julia> first_dict DataStructures.SortedDict{String,Int64,Base.Order.ForwardOrdering} with 6 entries: “R” => 100 “S” => 220 “T” => 350 “U” => 400 “V” => 575 “W” => 670 One of the simple applications of dictionaries is to count how many times each word appears in text. The concept behind this application is that each word is a key-value set and the value of that key is the number of times that particular word appears in that piece of text. In the following example, we will be counting the words in a file name NLP.txtb(saved on the desktop) − julia> f = open("C://Users//Leekha//Desktop//NLP.txt") IOStream() julia> wordlist = String[] String[] julia> for line in eachline(f) words = split(line, r"\W") map(w -> push!(wordlist, lowercase(w)), words) end julia> filter!(!isempty, wordlist) 984-element Array{String,1}: "natural" "language" "processing" "semantic" "analysis" "introduction" "to" "semantic" "analysis" "the" "purpose" ........................ ........................ julia> close(f) We can see from the above output that wordlist is now an array of 984 elements. We can create a dictionary to store the words and word count − julia> wordcounts = Dict{String,Int64}() Dict{String,Int64}() julia> for word in wordlist wordcounts[word]=get(wordcounts, word, 0) + 1 end To find out how many times the words appear, we can look up the words in the dictionary as follows − julia> wordcounts["natural"] 1 julia> wordcounts["processing"] 1 julia> wordcounts["and"] 14 We can also sort the dictionary as follows − julia> for i in sort(collect(keys(wordcounts))) println("$i, $(wordcounts[i])") end 1, 2 2, 2 3, 2 4, 2 5, 1 a, 28 about, 3 above, 2 act, 1 affixes, 3 all, 2 also, 5 an, 5 analysis, 15 analyze, 1 analyzed, 1 analyzer, 2 and, 14 answer, 5 antonymies, 1 antonymy, 1 application, 3 are, 11 ... ... ... ... To find the most common words we can use collect() to convert the dictionary to an array of tuples and then sort the array as follows − julia> sort(collect(wordcounts), by = tuple -> last(tuple), rev=true) 276-element Array{Pair{String,Int64},1}: "the" => 76 "of" => 47 "is" => 39 "a" => 28 "words" => 23 "meaning" => 23 "semantic" => 22 "lexical" => 21 "analysis" => 15 "and" => 14 "in" => 14 "be" => 13 "it" => 13 "example" => 13 "or" => 12 "word" => 12 "for" => 11 "are" => 11 "between" => 11 "as" => 11 ⋮ "each" => 1 "river" => 1 "homonym" => 1 "classification" => 1 "analyze" => 1 "nocturnal" => 1 "axis" => 1 "concept" => 1 "deals" => 1 "larger" => 1 "destiny" => 1 "what" => 1 "reservation" => 1 "characterization" => 1 "second" => 1 "certitude" => 1 "into" => 1 "compound" => 1 "introduction" => 1 We can check the first 10 words as follows − julia> sort(collect(wordcounts), by = tuple -> last(tuple), rev=true)[1:10] 10-element Array{Pair{String,Int64},1}: "the" => 76 "of" => 47 "is" => 39 "a" => 28 "words" => 23 "meaning" => 23 "semantic" => 22 "lexical" => 21 "analysis" => 15 "and" => 14 We can use filter() function to find all the words that start with a particular alphabet (say ’n’). julia> filter(tuple -> startswith(first(tuple), "n") && last(tuple) < 4, collect(wordcounts)) 6-element Array{Pair{String,Int64},1}: "none" => 2 "not" => 3 "namely" => 1 "name" => 1 "natural" => 1 "nocturnal" => 1 Like an array or dictionary, a set may be defined as a collection of unique elements. Following are the differences between sets and other kind of collections − In a set, we can have only one of each element. In a set, we can have only one of each element. The order of element is not important in a set. The order of element is not important in a set. With the help of Set constructor function, we can create a set as follows − julia> var_color = Set() Set{Any}() We can also specify the types of set as follows − julia> num_primes = Set{Int64}() Set{Int64}() We can also create and fill the set as follows − julia> var_color = Set{String}(["red","green","blue"]) Set{String} with 3 elements: "blue" "green" "red" Alternatively we can also use push!() function, as arrays, to add elements in sets as follows − julia> push!(var_color, "black") Set{String} with 4 elements: "blue" "green" "black" "red" We can use in() function to check what is in the set − julia> in("red", var_color) true julia> in("yellow", var_color) false Union, intersection, and difference are some standard operations we can do with sets. The corresponding functions for these operations are union(), intersect() and setdiff(). In general, the union (set) operation returns the combined results of the two statements. Example julia> color_rainbow = Set(["red","orange","yellow","green","blue","indigo","violet"]) Set{String} with 7 elements: "indigo" "yellow" "orange" "blue" "violet" "green" "red" julia> union(var_color, color_rainbow) Set{String} with 8 elements: "indigo" "yellow" "orange" "blue" "violet" "green" "black" "red" In general, an intersection operation takes two or more variables as inputs and returns the intersection between them. Example julia> intersect(var_color, color_rainbow) Set{String} with 3 elements: "blue" "green" "red" In general, the difference operation takes two or more variables as an input. Then, it returns the value of the first set excluding the value overlapped by the second set. Example julia> setdiff(var_color, color_rainbow) Set{String} with 1 element: "black" In the below example, you will see that the functions that work on arrays as well as sets also works on collections like dictionaries − julia> dict1 = Dict(100=>"X", 220 => "Y") Dict{Int64,String} with 2 entries: 100 => "X" 220 => "Y" julia> dict2 = Dict(220 => "Y", 300 => "Z", 450 => "W") Dict{Int64,String} with 3 entries: 450 => "W" 220 => "Y" 300 => "Z" julia> union(dict1, dict2) 4-element Array{Pair{Int64,String},1}: 100 => "X" 220 => "Y" 450 => "W" 300 => "Z" julia> intersect(dict1, dict2) 1-element Array{Pair{Int64,String},1}: 220 => "Y" julia> setdiff(dict1, dict2) 1-element Array{Pair{Int64,String},1}: 100 => "X" julia> merge(dict1, dict2) Dict{Int64,String} with 4 entries: 100 => "X" 450 => "W" 220 => "Y" 300 => "Z" julia> dict1 Dict{Int64,String} with 2 entries: 100 => "X" 220 => "Y" julia> findmin(dict1) ("X", 100) 73 Lectures 4 hours Lemuel Ogbunude 24 Lectures 3 hours Mohammad Nauman 29 Lectures 2.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2369, "s": 2078, "text": "Many of the functions we have seen so far are working on arrays and tuples. Arrays are just one type of collection, but Julia has other kind of collections too. One such collection is Dictionary object which associates keys with values. That is why it is called an ‘associative collection’." }, { "code": null, "e": 2628, "s": 2369, "text": "To understand it better, we can compare it with simple look-up table in which many types of data are organized and provide us the single piece of information such as number, string or symbol called the key. It doesn’t provide us the corresponding data value." }, { "code": null, "e": 2688, "s": 2628, "text": "The syntax for creating a simple dictionary is as follows −" }, { "code": null, "e": 2753, "s": 2688, "text": "Dict(“key1” => value1, “key2” => value2,,..., “keyn” => valuen)\n" }, { "code": null, "e": 2996, "s": 2753, "text": "In the above syntax, key1, key2...keyn are the keys and value1, value2,...valuen are the corresponding values. The operator => is the Pair() function. We can not have two keys with the same name because keys are always unique in dictionaries." }, { "code": null, "e": 3128, "s": 2996, "text": "julia> first_dict = Dict(\"X\" => 100, \"Y\" => 110, \"Z\" => 220)\nDict{String,Int64} with 3 entries:\n \"Y\" => 110\n \"Z\" => 220\n \"X\" => 100" }, { "code": null, "e": 3228, "s": 3128, "text": "We can also create dictionaries with the help of comprehension syntax. The example is given below −" }, { "code": null, "e": 3450, "s": 3228, "text": "julia> first_dict = Dict(string(x) => sind(x) for x = 0:5:360)\nDict{String,Float64} with 73 entries:\n \"320\" => -0.642788\n \"65\" => 0.906308\n \"155\" => 0.422618\n \"335\" => -0.422618\n \"75\" => 0.965926\n \"50\" => 0.766044\n ⋮ => ⋮" }, { "code": null, "e": 3697, "s": 3450, "text": "As discussed earlier, dictionaries have unique keys. It means that if we assign a value to a key that already exists, we will not be creating a new one but modifying the existing key. Following are some operations on dictionaries regarding keys −" }, { "code": null, "e": 3782, "s": 3697, "text": "We can use haskey() function to check whether the dictionary contains a key or not −" }, { "code": null, "e": 3990, "s": 3782, "text": "julia> first_dict = Dict(\"X\" => 100, \"Y\" => 110, \"Z\" => 220)\nDict{String,Int64} with 3 entries:\n \"Y\" => 110\n \"Z\" => 220\n \"X\" => 100\n \njulia> haskey(first_dict, \"Z\")\ntrue\n\njulia> haskey(first_dict, \"A\")\nfalse" }, { "code": null, "e": 4082, "s": 3990, "text": "We can use in() function to check whether the dictionary contains a key/value pair or not −" }, { "code": null, "e": 4166, "s": 4082, "text": "julia> in((\"X\" => 100), first_dict)\ntrue\n\njulia> in((\"X\" => 220), first_dict)\nfalse" }, { "code": null, "e": 4233, "s": 4166, "text": "We can add a new key-value in the existing dictionary as follows −" }, { "code": null, "e": 4368, "s": 4233, "text": "julia> first_dict[\"R\"] = 400\n400\n\njulia> first_dict\nDict{String,Int64} with 4 entries:\n \"Y\" => 110\n \"Z\" => 220\n \"X\" => 100\n \"R\" => 400" }, { "code": null, "e": 4444, "s": 4368, "text": "We can use delete!() function to delete a key from an existing dictionary −" }, { "code": null, "e": 4547, "s": 4444, "text": "julia> delete!(first_dict, \"R\")\nDict{String,Int64} with 3 entries:\n \"Y\" => 110\n \"Z\" => 220\n \"X\" => 100" }, { "code": null, "e": 4624, "s": 4547, "text": "We can use keys() function to get all the keys from an existing dictionary −" }, { "code": null, "e": 4722, "s": 4624, "text": "julia> keys(first_dict)\nBase.KeySet for a Dict{String,Int64} with 3 entries. Keys:\n \"Y\"\n \"Z\"\n \"X\"" }, { "code": null, "e": 4838, "s": 4722, "text": "Every key in dictionary has a corresponding value. Following are some operations on dictionaries regarding values −" }, { "code": null, "e": 4919, "s": 4838, "text": "We can use values() function to get all the values from an existing dictionary −" }, { "code": null, "e": 5028, "s": 4919, "text": "julia> values(first_dict)\nBase.ValueIterator for a Dict{String,Int64} with 3 entries. Values:\n 110\n 220\n 100" }, { "code": null, "e": 5119, "s": 5028, "text": "We can process each key/value pair to see the dictionaries are actually iterable objects −" }, { "code": null, "e": 5207, "s": 5119, "text": "for kv in first_dict\n println(kv)\n end\n \"Y\" => 110\n \"Z\" => 220\n \"X\" => 100" }, { "code": null, "e": 5265, "s": 5207, "text": "Here the kv is a tuple that contains each key/value pair." }, { "code": null, "e": 5443, "s": 5265, "text": "Dictionaries do not store the keys in any particular order hence the output of the dictionary would not be a sorted array. To obtain items in order, we can sort the dictionary −" }, { "code": null, "e": 5811, "s": 5443, "text": "julia> first_dict = Dict(\"R\" => 100, \"S\" => 220, \"T\" => 350, \"U\" => 400, \"V\" => 575, \"W\" => 670)\nDict{String,Int64} with 6 entries:\n \"S\" => 220\n \"U\" => 400\n \"T\" => 350\n \"W\" => 670\n \"V\" => 575\n \"R\" => 100\njulia> for key in sort(collect(keys(first_dict)))\n println(\"$key => $(first_dict[key])\")\n end\nR => 100\nS => 220\nT => 350\nU => 400\nV => 575\nW => 670" }, { "code": null, "e": 5986, "s": 5811, "text": "We can also use SortedDict data type from the DataStructures.ji Julia package to make sure that the dictionary remains sorted all the times. You can check the example below −" }, { "code": null, "e": 6470, "s": 5986, "text": "julia> import DataStructures\njulia> first_dict = DataStructures.SortedDict(\"S\" => 220, \"T\" => 350, \"U\" => 400, \"V\" => 575, \"W\" => 670)\nDataStructures.SortedDict{String,Int64,Base.Order.ForwardOrdering} with 5 entries:\n \"S\" => 220\n \"T\" => 350\n \"U\" => 400\n \"V\" => 575\n \"W\" => 670\njulia> first_dict[\"R\"] = 100\n100\njulia> first_dict\nDataStructures.SortedDict{String,Int64,Base.Order.ForwardOrdering} with 6 entries:\n “R” => 100\n “S” => 220\n “T” => 350\n “U” => 400\n “V” => 575\n “W” => 670" }, { "code": null, "e": 6745, "s": 6470, "text": "One of the simple applications of dictionaries is to count how many times each word appears in text. The concept behind this application is that each word is a key-value set and the value of that key is the number of times that particular word appears in that piece of text." }, { "code": null, "e": 6849, "s": 6745, "text": "In the following example, we will be counting the words in a file name NLP.txtb(saved on the desktop) −" }, { "code": null, "e": 7357, "s": 6849, "text": "julia> f = open(\"C://Users//Leekha//Desktop//NLP.txt\")\nIOStream()\n\njulia> wordlist = String[]\nString[]\n\njulia> for line in eachline(f)\n words = split(line, r\"\\W\")\n map(w -> push!(wordlist, lowercase(w)), words)\n end\n julia> filter!(!isempty, wordlist)\n984-element Array{String,1}:\n \"natural\"\n \"language\"\n \"processing\"\n \"semantic\"\n \"analysis\"\n \"introduction\"\n \"to\"\n \"semantic\"\n \"analysis\"\n \"the\"\n \"purpose\"\n ........................\n ........................\njulia> close(f)" }, { "code": null, "e": 7437, "s": 7357, "text": "We can see from the above output that wordlist is now an array of 984 elements." }, { "code": null, "e": 7500, "s": 7437, "text": "We can create a dictionary to store the words and word count −" }, { "code": null, "e": 7662, "s": 7500, "text": "julia> wordcounts = Dict{String,Int64}()\nDict{String,Int64}()\n\njulia> for word in wordlist\n wordcounts[word]=get(wordcounts, word, 0) + 1\n end" }, { "code": null, "e": 7763, "s": 7662, "text": "To find out how many times the words appear, we can look up the words in the dictionary as follows −" }, { "code": null, "e": 7859, "s": 7763, "text": "julia> wordcounts[\"natural\"]\n1\n\njulia> wordcounts[\"processing\"]\n1\n\njulia> wordcounts[\"and\"]\n14\n" }, { "code": null, "e": 7904, "s": 7859, "text": "We can also sort the dictionary as follows −" }, { "code": null, "e": 8222, "s": 7904, "text": "julia> for i in sort(collect(keys(wordcounts)))\n println(\"$i, $(wordcounts[i])\")\n end\n1, 2\n2, 2\n3, 2\n4, 2\n5, 1\na, 28\nabout, 3\nabove, 2\nact, 1\naffixes, 3\nall, 2\nalso, 5\nan, 5\nanalysis, 15\nanalyze, 1\nanalyzed, 1\nanalyzer, 2\nand, 14\nanswer, 5\nantonymies, 1\nantonymy, 1\napplication, 3\nare, 11\n...\n...\n...\n..." }, { "code": null, "e": 8358, "s": 8222, "text": "To find the most common words we can use collect() to convert the dictionary to an array of tuples and then sort the array as follows −" }, { "code": null, "e": 9425, "s": 8358, "text": "julia> sort(collect(wordcounts), by = tuple -> last(tuple), rev=true)\n276-element Array{Pair{String,Int64},1}:\n \"the\" => 76\n \"of\" => 47\n \"is\" => 39\n \"a\" => 28\n \"words\" => 23\n \"meaning\" => 23\n \"semantic\" => 22\n \"lexical\" => 21\n \"analysis\" => 15\n \"and\" => 14\n \"in\" => 14\n \"be\" => 13\n \"it\" => 13\n \"example\" => 13\n \"or\" => 12\n \"word\" => 12\n \"for\" => 11\n \"are\" => 11\n \"between\" => 11\n \"as\" => 11\n ⋮\n \"each\" => 1\n \"river\" => 1\n \"homonym\" => 1\n \"classification\" => 1\n \"analyze\" => 1\n \"nocturnal\" => 1\n \"axis\" => 1\n \"concept\" => 1\n \"deals\" => 1\n \"larger\" => 1\n \"destiny\" => 1\n \"what\" => 1\n \"reservation\" => 1\n\"characterization\" => 1\n \"second\" => 1\n \"certitude\" => 1\n \"into\" => 1\n \"compound\" => 1\n \"introduction\" => 1" }, { "code": null, "e": 9470, "s": 9425, "text": "We can check the first 10 words as follows −" }, { "code": null, "e": 9766, "s": 9470, "text": "julia> sort(collect(wordcounts), by = tuple -> last(tuple), rev=true)[1:10]\n10-element Array{Pair{String,Int64},1}:\n \"the\" => 76\n \"of\" => 47\n \"is\" => 39\n \"a\" => 28\n \"words\" => 23\n \"meaning\" => 23\n \"semantic\" => 22\n \"lexical\" => 21\n \"analysis\" => 15\n \"and\" => 14" }, { "code": null, "e": 9866, "s": 9766, "text": "We can use filter() function to find all the words that start with a particular alphabet (say ’n’)." }, { "code": null, "e": 10107, "s": 9866, "text": "julia> filter(tuple -> startswith(first(tuple), \"n\") && last(tuple) < 4, collect(wordcounts))\n6-element Array{Pair{String,Int64},1}:\n \"none\" => 2\n \"not\" => 3\n \"namely\" => 1\n \"name\" => 1\n \"natural\" => 1\n \"nocturnal\" => 1" }, { "code": null, "e": 10268, "s": 10107, "text": "Like an array or dictionary, a set may be defined as a collection of unique elements. Following are the differences between sets and other kind of collections −" }, { "code": null, "e": 10316, "s": 10268, "text": "In a set, we can have only one of each element." }, { "code": null, "e": 10364, "s": 10316, "text": "In a set, we can have only one of each element." }, { "code": null, "e": 10412, "s": 10364, "text": "The order of element is not important in a set." }, { "code": null, "e": 10460, "s": 10412, "text": "The order of element is not important in a set." }, { "code": null, "e": 10536, "s": 10460, "text": "With the help of Set constructor function, we can create a set as follows −" }, { "code": null, "e": 10572, "s": 10536, "text": "julia> var_color = Set()\nSet{Any}()" }, { "code": null, "e": 10622, "s": 10572, "text": "We can also specify the types of set as follows −" }, { "code": null, "e": 10668, "s": 10622, "text": "julia> num_primes = Set{Int64}()\nSet{Int64}()" }, { "code": null, "e": 10717, "s": 10668, "text": "We can also create and fill the set as follows −" }, { "code": null, "e": 10825, "s": 10717, "text": "julia> var_color = Set{String}([\"red\",\"green\",\"blue\"])\nSet{String} with 3 elements:\n \"blue\"\n \"green\"\n \"red\"" }, { "code": null, "e": 10921, "s": 10825, "text": "Alternatively we can also use push!() function, as arrays, to add elements in sets as follows −" }, { "code": null, "e": 11016, "s": 10921, "text": "julia> push!(var_color, \"black\")\nSet{String} with 4 elements:\n \"blue\"\n \"green\"\n \"black\"\n \"red\"" }, { "code": null, "e": 11071, "s": 11016, "text": "We can use in() function to check what is in the set −" }, { "code": null, "e": 11142, "s": 11071, "text": "julia> in(\"red\", var_color)\ntrue\n\njulia> in(\"yellow\", var_color)\nfalse" }, { "code": null, "e": 11317, "s": 11142, "text": "Union, intersection, and difference are some standard operations we can do with sets. The corresponding functions for these operations are union(), intersect() and setdiff()." }, { "code": null, "e": 11407, "s": 11317, "text": "In general, the union (set) operation returns the combined results of the two statements." }, { "code": null, "e": 11415, "s": 11407, "text": "Example" }, { "code": null, "e": 11738, "s": 11415, "text": "julia> color_rainbow = Set([\"red\",\"orange\",\"yellow\",\"green\",\"blue\",\"indigo\",\"violet\"])\nSet{String} with 7 elements:\n \"indigo\"\n \"yellow\"\n \"orange\"\n \"blue\"\n \"violet\"\n \"green\"\n \"red\"\n \njulia> union(var_color, color_rainbow)\nSet{String} with 8 elements:\n \"indigo\"\n \"yellow\"\n \"orange\"\n \"blue\"\n \"violet\"\n \"green\"\n \"black\"\n \"red\"" }, { "code": null, "e": 11857, "s": 11738, "text": "In general, an intersection operation takes two or more variables as inputs and returns the intersection between them." }, { "code": null, "e": 11865, "s": 11857, "text": "Example" }, { "code": null, "e": 11961, "s": 11865, "text": "julia> intersect(var_color, color_rainbow)\nSet{String} with 3 elements:\n \"blue\"\n \"green\"\n \"red\"" }, { "code": null, "e": 12133, "s": 11961, "text": "In general, the difference operation takes two or more variables as an input. Then, it returns the value of the first set excluding the value overlapped by the second set." }, { "code": null, "e": 12141, "s": 12133, "text": "Example" }, { "code": null, "e": 12219, "s": 12141, "text": "julia> setdiff(var_color, color_rainbow)\nSet{String} with 1 element:\n \"black\"" }, { "code": null, "e": 12355, "s": 12219, "text": "In the below example, you will see that the functions that work on arrays as well as sets also works on collections like dictionaries −" }, { "code": null, "e": 12585, "s": 12355, "text": "julia> dict1 = Dict(100=>\"X\", 220 => \"Y\")\nDict{Int64,String} with 2 entries:\n 100 => \"X\"\n 220 => \"Y\"\n \njulia> dict2 = Dict(220 => \"Y\", 300 => \"Z\", 450 => \"W\")\nDict{Int64,String} with 3 entries:\n 450 => \"W\"\n 220 => \"Y\"\n 300 => \"Z\"" }, { "code": null, "e": 12699, "s": 12585, "text": "julia> union(dict1, dict2)\n4-element Array{Pair{Int64,String},1}:\n 100 => \"X\"\n 220 => \"Y\"\n 450 => \"W\"\n 300 => \"Z\"" }, { "code": null, "e": 12781, "s": 12699, "text": "julia> intersect(dict1, dict2)\n1-element Array{Pair{Int64,String},1}:\n 220 => \"Y\"" }, { "code": null, "e": 12861, "s": 12781, "text": "julia> setdiff(dict1, dict2)\n1-element Array{Pair{Int64,String},1}:\n 100 => \"X\"" }, { "code": null, "e": 12971, "s": 12861, "text": "julia> merge(dict1, dict2)\nDict{Int64,String} with 4 entries:\n 100 => \"X\"\n 450 => \"W\"\n 220 => \"Y\"\n 300 => \"Z\"" }, { "code": null, "e": 13080, "s": 12971, "text": "julia> dict1\nDict{Int64,String} with 2 entries:\n 100 => \"X\"\n 220 => \"Y\"\n \n \njulia> findmin(dict1)\n(\"X\", 100)" }, { "code": null, "e": 13113, "s": 13080, "text": "\n 73 Lectures \n 4 hours \n" }, { "code": null, "e": 13130, "s": 13113, "text": " Lemuel Ogbunude" }, { "code": null, "e": 13163, "s": 13130, "text": "\n 24 Lectures \n 3 hours \n" }, { "code": null, "e": 13180, "s": 13163, "text": " Mohammad Nauman" }, { "code": null, "e": 13215, "s": 13180, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13238, "s": 13215, "text": " Stone River ELearning" }, { "code": null, "e": 13245, "s": 13238, "text": " Print" }, { "code": null, "e": 13256, "s": 13245, "text": " Add Notes" } ]
Top Python Libraries: Numpy & Pandas | by Md Arman Hossen | Towards Data Science
In this tutorial, I’ll try to make a brief description about two of the most important libraries in Python Numpy and Pandas. Without further delay lets go through Numpy first. numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object and tools for working with these arrays. Numpy is a powerful N-dimensional array object which is Linear algebra for Python. Numpy arrays essentially come in two flavors: Vectors and Matrics. Vectors are strictly 1-d array whereas Matrices are 2-d but matrices can have only one row/column. To install numpy library in your system and to know further about python basics you can follow the below link: towardsdatascience.com Now to use numpy in the program we need to import the module. Generally, numpy package is defined as np of abbreviation for convenience. But you can import it using anything you want. import numpy as npnp.array([1, 2, 3]) # Create a rank 1 arraynp.arange(15) # generate an 1-d array from 0 to 14np.arange(15).reshape(3, 5) # generate array and change dimensions Now to learn more about numpy pakages and its function you can follow directly https://numpy.org/ , the official website. Here we’ll discuss some important commands and functions of numpy library. In the example figure above we can observe numpy is imported first and then a 1-d numpy array a is defined. Then we can examine the type, dimension, shape, and length of the array using mentioned commands. Here are some important commands for creating arrays: np.linespace(0,3,4) #create 4 equally spaced points 0-3 range inclusivelynp.linespace(0,3,4, endpoint=False) # remove endpoint and other equally spaced values.np.random.randint(1,100,6) #create array of 6 random values in 0-100 range.np.random.randint(1,100,6).reshape(3,2) #reshape the array according to row and column vectors.np.random.rand(4) #create an array of uniform distribution (0,1)np.eye(3) #create a 3*3 identity matrixnp.zeros(3) #create array([0,0,0])np.zeros((5,5)) #create a 5*5 2-d array of zerosnp.random.randn(2,2) #return standard normal distribution vcenter around zreo.np.empty((2,3)) # uninitializednp.arange(0, 2, 0.3) # from 0 to a number less than 2 with 0.3 intervalsnp.ones((2,3,4), dtype=np.int16) # all element are 1np.array([[1,2],[3,4]], dtype=complex) # complex arraynp.array([(1.5,2,3),(4,5,6)]) # two-dimensional arraynp.array([2,3,4]) # one-dimensional array Important attributes of the ndarray object ndarray.shape : The dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be(n,m) . ndarray.ndim : The number of axes (dimensions) of the array. ndarray.dtype : If you want to know the data type of an array, you can query the attributes of dtype. An object describing the type of the elements in the array. One can create or specify dtype using standard Python types.Additionally, numpy provides types of its own. numpy.int32, numpy.int16, and numpy.float64 are some examples. ndarray.itemsize : The size in bytes of each element of the array. For example, an array of elements of type float64 has itemsize 8 (=64/8), while one of type complex32 has itemsize 4 (=32/8). It is equivalent to ndarray.dtype.itemsize. ndarray.size: The total number of elements of the array. This is equal to the product of the elements of shape. Printing an array: When you print an array, numpy displays it in a similar way to nested lists, but with the following layout: the last axis is printed from left to right, the second-to-last is printed from top to bottom, the rest are also printed from top to bottom, with each slice separated from the next by an empty line. Basic Operations of ndarray: A = np.array([[1,1],[0,1]])B = np.array([[2,0],[3,4]])A+B #addition of two arraynp.add(A,B) #addition of two arrayA * B # elementwise productA @ B # matrix productA.dot(B) # another matrix productB.T #Transpose of B arrayA.flatten() #form 1-d arrayB < 3 #Boolean of Matrix B. True for elements less than 3A.sum() # sum of all elements of AA.sum(axis=0) # sum of each columnA.sum(axis=1) # sum of each rowA.cumsum(axis=1) # cumulative sum along each rowA.min() # min value of all elementsA.max() # max value of all elementsnp.exp(B) # exponentialnp.sqrt(B) # squre rootA.argmin() #position of min value of elements A.argmax() #position of max value of elementsA[1,1] #member of a array in (1,1) position Indexing, Slicing and Iterating in numpy: a = np.arange(4)**3 # create array aa[2] # member of a array in 2nd positiona[::-1] # reversed aa[0:4,1] # each row in the second column of ba[1,...] # same as a[1,:,:] or a[1]a[a>5] # a with values greater than 5x = a[0:4] # assign x with 4 values of ax[:]=99 # change the values of x to 99 which will change the 4 values of a also. If any position of an array is allocated to another array and its being broadcasted to a new value, then the original array also changed. This is because numpy doesn’t want to use more memory for the same array. As shown in the following figure, the value of a is changed with changing the values of x which is a part of the array a. When we use a comparison operator in an array it returns a boolean array. Then using the boolean array we could select elements conditionally from the original array. pandas is an open-source library built on top of numpy providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language. It allows for fast analysis and data cleaning and preparation. It excels in performance and productivity. It can work with data from a wide variety of sources. pandasis suited for many different kinds of data: tabular data, time-series data, arbitrary matrix data with row and column labels, and Any other form of observational/statistical data sets. To install pandas in your system you can use this command pip install pandas or conda install pandas . import numpy as np #importing numpyimport pandas as pd #importing pandasarr=np.array([1,3,5,7,9]) #create arr arrays2=pd.Series(arr) #create pandas series s2print(s2) #print s2print(type(s2)) #print type of s2 Output: 0 11 32 53 74 9dtype: int64<class 'pandas.core.series.Series'> To make series in pandaswe need to use pd.Series(data, index)format where data are input data and index are selected index for data. To understand it fully we can follow the below example. Pandas series works the same way both in list and numpy array as well as dictionary also. Panel, a three-dimensional data structure, has three axes,Axis 0 (items), Axis 1 (major_axis), and Axis 2 (minor_axis). Axis 0 corresponds to a two-dimensional DataFrame. Corresponds to the row of, and Axis 2 corresponds to the column of the DataFrame. The example below uses numpy to generate a three-dimensional random number and then applies it topandas.Panel(). The output shows that a Panel object of size 2 (items) x 3 (major_axis) x 4 (minor_axis) was created. If you look up p[0]from Panel object p, you can see that DataFrame, the first element of Axis 0, is displayed. Pandas DataFrames create a tabular data structure with labeled axes(rows and columns). The default format of a DataFrame would be pd.Dataframe(data, index, column) . You need to mention the data, index and columns value to generate a DataFrame. Data should be at least two-dimensional, index will be the row name and columns values for the columns. Below I’ve mentioned some basic commands used in pandas libraries along with their usage: s4=pd.DataFrame(np.random.randn(20,7), columns=['A','B','C','D','E','F','G'])s4[(5<s4.index) & (s4.index<10)] # s4 with values that satisfy both conditions s4.head() # First five rows of s4s4.tail() # Last five rows of s4s4.describe() # statistical information of datas4['B'] # data of the 'B' columns4[['B','E']] # data of the 'B' and 'E' columns4[0:3] # data of the 1~3 rowss4.iloc[0:3] # data of the 1~3 rowss4.loc[[2,3],['A','B']] # value of row 2,3 column 'A' ,'B's4[2 < s4] # s4 with values matching conditionss4.mean() # means of each columns4.mean(1) # mean of each rows4.drop('A') # delete row 'A's4.drop('D',axis=1) # delete 'D' columns4.drop('D',axis=1, inplace=True) # delete 'D' column permanentlys4['H']=np.random.rand(20,1) # add a new column of same length. Dictionary can be used in creating both pandas Series and DataFrames. Dictionary can be used as data to create tabular data but values should be more than one for each key and all values should be of same length whereas in pandas Series different value length is okay. To reset the index of the frame and add the previous index in a column we need to follow the below command. Reset index will be numerical value. df.reset_index(inplace=True)df.set_index('Name') #index will be 'Name' column but not permanent. df.set_index('Name', inplace=True)#permanent new index 'Name' column Most of the DataFrames has several Nan values in different columns. Sometimes we need to remove the Nan items or replace them with something else. We can remove or replace the Nan value in pandas DataFrame in following ways: df.dropna() # remove the rows that have Nan valuedf.dropna(inplace=True) # remove the Nan value rows parmenentlydf.dropna(axis=1) # remove columns that has Nan valuedf.dropna(axis=1, inplace=True) # remove the Nan valued columns parmanently. df.fillna(value='Arman') # fill Nan values with 'Arman'.df.fillna(value='Arman', inplace=True) #fill values parmanently.df.fillna(value=df.mean(), inplace=True) #fill Nan value with each column mean value.df['A'].fillna(value=df['A'].mean()) #fill Nan value of column 'A' with its mean. In my next tutorial, I’ll try to summarize about Matplotlib and seaborn, two mostly used visualization libraries. I’ll try to add a repo for this tutorial ASAP. Thanks for your time and any kind of suggestions or criticism is highly appreciable. You can follow my profile to have a look at several tutorials. medium.com Numpy: https://numpy.org/Stanford cs231 : http://cs231n.github.io/python-numpy-tutorial/Numpy basic cheetsheet: https://s3.amazonaws.com/assets.datacamp.com/blog_assets/Numpy_Python_Cheat_Sheet.pdfPandas : https://pandas.pydata.org/Pandas cheetsheet: https://pandas.pydata.org/Pandas_Cheat_Sheet.pdf https://assets.datacamp.com/blog_assets/PandasPythonForDataScience.pdf Numpy: https://numpy.org/ Stanford cs231 : http://cs231n.github.io/python-numpy-tutorial/ Numpy basic cheetsheet: https://s3.amazonaws.com/assets.datacamp.com/blog_assets/Numpy_Python_Cheat_Sheet.pdf Pandas : https://pandas.pydata.org/ Pandas cheetsheet: https://pandas.pydata.org/Pandas_Cheat_Sheet.pdf https://assets.datacamp.com/blog_assets/PandasPythonForDataScience.pdf
[ { "code": null, "e": 348, "s": 172, "text": "In this tutorial, I’ll try to make a brief description about two of the most important libraries in Python Numpy and Pandas. Without further delay lets go through Numpy first." }, { "code": null, "e": 761, "s": 348, "text": "numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object and tools for working with these arrays. Numpy is a powerful N-dimensional array object which is Linear algebra for Python. Numpy arrays essentially come in two flavors: Vectors and Matrics. Vectors are strictly 1-d array whereas Matrices are 2-d but matrices can have only one row/column." }, { "code": null, "e": 872, "s": 761, "text": "To install numpy library in your system and to know further about python basics you can follow the below link:" }, { "code": null, "e": 895, "s": 872, "text": "towardsdatascience.com" }, { "code": null, "e": 1079, "s": 895, "text": "Now to use numpy in the program we need to import the module. Generally, numpy package is defined as np of abbreviation for convenience. But you can import it using anything you want." }, { "code": null, "e": 1279, "s": 1079, "text": "import numpy as npnp.array([1, 2, 3]) # Create a rank 1 arraynp.arange(15) # generate an 1-d array from 0 to 14np.arange(15).reshape(3, 5) # generate array and change dimensions" }, { "code": null, "e": 1476, "s": 1279, "text": "Now to learn more about numpy pakages and its function you can follow directly https://numpy.org/ , the official website. Here we’ll discuss some important commands and functions of numpy library." }, { "code": null, "e": 1736, "s": 1476, "text": "In the example figure above we can observe numpy is imported first and then a 1-d numpy array a is defined. Then we can examine the type, dimension, shape, and length of the array using mentioned commands. Here are some important commands for creating arrays:" }, { "code": null, "e": 2703, "s": 1736, "text": "np.linespace(0,3,4) #create 4 equally spaced points 0-3 range inclusivelynp.linespace(0,3,4, endpoint=False) # remove endpoint and other equally spaced values.np.random.randint(1,100,6) #create array of 6 random values in 0-100 range.np.random.randint(1,100,6).reshape(3,2) #reshape the array according to row and column vectors.np.random.rand(4) #create an array of uniform distribution (0,1)np.eye(3) #create a 3*3 identity matrixnp.zeros(3) #create array([0,0,0])np.zeros((5,5)) #create a 5*5 2-d array of zerosnp.random.randn(2,2) #return standard normal distribution vcenter around zreo.np.empty((2,3)) # uninitializednp.arange(0, 2, 0.3) # from 0 to a number less than 2 with 0.3 intervalsnp.ones((2,3,4), dtype=np.int16) # all element are 1np.array([[1,2],[3,4]], dtype=complex) # complex arraynp.array([(1.5,2,3),(4,5,6)]) # two-dimensional arraynp.array([2,3,4]) # one-dimensional array" }, { "code": null, "e": 2746, "s": 2703, "text": "Important attributes of the ndarray object" }, { "code": null, "e": 2932, "s": 2746, "text": "ndarray.shape : The dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be(n,m) ." }, { "code": null, "e": 2993, "s": 2932, "text": "ndarray.ndim : The number of axes (dimensions) of the array." }, { "code": null, "e": 3325, "s": 2993, "text": "ndarray.dtype : If you want to know the data type of an array, you can query the attributes of dtype. An object describing the type of the elements in the array. One can create or specify dtype using standard Python types.Additionally, numpy provides types of its own. numpy.int32, numpy.int16, and numpy.float64 are some examples." }, { "code": null, "e": 3562, "s": 3325, "text": "ndarray.itemsize : The size in bytes of each element of the array. For example, an array of elements of type float64 has itemsize 8 (=64/8), while one of type complex32 has itemsize 4 (=32/8). It is equivalent to ndarray.dtype.itemsize." }, { "code": null, "e": 3674, "s": 3562, "text": "ndarray.size: The total number of elements of the array. This is equal to the product of the elements of shape." }, { "code": null, "e": 4000, "s": 3674, "text": "Printing an array: When you print an array, numpy displays it in a similar way to nested lists, but with the following layout: the last axis is printed from left to right, the second-to-last is printed from top to bottom, the rest are also printed from top to bottom, with each slice separated from the next by an empty line." }, { "code": null, "e": 4029, "s": 4000, "text": "Basic Operations of ndarray:" }, { "code": null, "e": 4877, "s": 4029, "text": "A = np.array([[1,1],[0,1]])B = np.array([[2,0],[3,4]])A+B #addition of two arraynp.add(A,B) #addition of two arrayA * B # elementwise productA @ B # matrix productA.dot(B) # another matrix productB.T #Transpose of B arrayA.flatten() #form 1-d arrayB < 3 #Boolean of Matrix B. True for elements less than 3A.sum() # sum of all elements of AA.sum(axis=0) # sum of each columnA.sum(axis=1) # sum of each rowA.cumsum(axis=1) # cumulative sum along each rowA.min() # min value of all elementsA.max() # max value of all elementsnp.exp(B) # exponentialnp.sqrt(B) # squre rootA.argmin() #position of min value of elements A.argmax() #position of max value of elementsA[1,1] #member of a array in (1,1) position" }, { "code": null, "e": 4919, "s": 4877, "text": "Indexing, Slicing and Iterating in numpy:" }, { "code": null, "e": 5344, "s": 4919, "text": "a = np.arange(4)**3 # create array aa[2] # member of a array in 2nd positiona[::-1] # reversed aa[0:4,1] # each row in the second column of ba[1,...] # same as a[1,:,:] or a[1]a[a>5] # a with values greater than 5x = a[0:4] # assign x with 4 values of ax[:]=99 # change the values of x to 99 which will change the 4 values of a also." }, { "code": null, "e": 5678, "s": 5344, "text": "If any position of an array is allocated to another array and its being broadcasted to a new value, then the original array also changed. This is because numpy doesn’t want to use more memory for the same array. As shown in the following figure, the value of a is changed with changing the values of x which is a part of the array a." }, { "code": null, "e": 5845, "s": 5678, "text": "When we use a comparison operator in an array it returns a boolean array. Then using the boolean array we could select elements conditionally from the original array." }, { "code": null, "e": 6471, "s": 5845, "text": "pandas is an open-source library built on top of numpy providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language. It allows for fast analysis and data cleaning and preparation. It excels in performance and productivity. It can work with data from a wide variety of sources. pandasis suited for many different kinds of data: tabular data, time-series data, arbitrary matrix data with row and column labels, and Any other form of observational/statistical data sets. To install pandas in your system you can use this command pip install pandas or conda install pandas ." }, { "code": null, "e": 6740, "s": 6471, "text": "import numpy as np #importing numpyimport pandas as pd #importing pandasarr=np.array([1,3,5,7,9]) #create arr arrays2=pd.Series(arr) #create pandas series s2print(s2) #print s2print(type(s2)) #print type of s2" }, { "code": null, "e": 6748, "s": 6740, "text": "Output:" }, { "code": null, "e": 6826, "s": 6748, "text": "0 11 32 53 74 9dtype: int64<class 'pandas.core.series.Series'>" }, { "code": null, "e": 7015, "s": 6826, "text": "To make series in pandaswe need to use pd.Series(data, index)format where data are input data and index are selected index for data. To understand it fully we can follow the below example." }, { "code": null, "e": 7684, "s": 7015, "text": "Pandas series works the same way both in list and numpy array as well as dictionary also. Panel, a three-dimensional data structure, has three axes,Axis 0 (items), Axis 1 (major_axis), and Axis 2 (minor_axis). Axis 0 corresponds to a two-dimensional DataFrame. Corresponds to the row of, and Axis 2 corresponds to the column of the DataFrame. The example below uses numpy to generate a three-dimensional random number and then applies it topandas.Panel(). The output shows that a Panel object of size 2 (items) x 3 (major_axis) x 4 (minor_axis) was created. If you look up p[0]from Panel object p, you can see that DataFrame, the first element of Axis 0, is displayed." }, { "code": null, "e": 8033, "s": 7684, "text": "Pandas DataFrames create a tabular data structure with labeled axes(rows and columns). The default format of a DataFrame would be pd.Dataframe(data, index, column) . You need to mention the data, index and columns value to generate a DataFrame. Data should be at least two-dimensional, index will be the row name and columns values for the columns." }, { "code": null, "e": 8123, "s": 8033, "text": "Below I’ve mentioned some basic commands used in pandas libraries along with their usage:" }, { "code": null, "e": 9075, "s": 8123, "text": "s4=pd.DataFrame(np.random.randn(20,7), columns=['A','B','C','D','E','F','G'])s4[(5<s4.index) & (s4.index<10)] # s4 with values that satisfy both conditions s4.head() # First five rows of s4s4.tail() # Last five rows of s4s4.describe() # statistical information of datas4['B'] # data of the 'B' columns4[['B','E']] # data of the 'B' and 'E' columns4[0:3] # data of the 1~3 rowss4.iloc[0:3] # data of the 1~3 rowss4.loc[[2,3],['A','B']] # value of row 2,3 column 'A' ,'B's4[2 < s4] # s4 with values matching conditionss4.mean() # means of each columns4.mean(1) # mean of each rows4.drop('A') # delete row 'A's4.drop('D',axis=1) # delete 'D' columns4.drop('D',axis=1, inplace=True) # delete 'D' column permanentlys4['H']=np.random.rand(20,1) # add a new column of same length." }, { "code": null, "e": 9344, "s": 9075, "text": "Dictionary can be used in creating both pandas Series and DataFrames. Dictionary can be used as data to create tabular data but values should be more than one for each key and all values should be of same length whereas in pandas Series different value length is okay." }, { "code": null, "e": 9489, "s": 9344, "text": "To reset the index of the frame and add the previous index in a column we need to follow the below command. Reset index will be numerical value." }, { "code": null, "e": 9655, "s": 9489, "text": "df.reset_index(inplace=True)df.set_index('Name') #index will be 'Name' column but not permanent. df.set_index('Name', inplace=True)#permanent new index 'Name' column" }, { "code": null, "e": 9880, "s": 9655, "text": "Most of the DataFrames has several Nan values in different columns. Sometimes we need to remove the Nan items or replace them with something else. We can remove or replace the Nan value in pandas DataFrame in following ways:" }, { "code": null, "e": 10446, "s": 9880, "text": "df.dropna() # remove the rows that have Nan valuedf.dropna(inplace=True) # remove the Nan value rows parmenentlydf.dropna(axis=1) # remove columns that has Nan valuedf.dropna(axis=1, inplace=True) # remove the Nan valued columns parmanently. df.fillna(value='Arman') # fill Nan values with 'Arman'.df.fillna(value='Arman', inplace=True) #fill values parmanently.df.fillna(value=df.mean(), inplace=True) #fill Nan value with each column mean value.df['A'].fillna(value=df['A'].mean()) #fill Nan value of column 'A' with its mean." }, { "code": null, "e": 10755, "s": 10446, "text": "In my next tutorial, I’ll try to summarize about Matplotlib and seaborn, two mostly used visualization libraries. I’ll try to add a repo for this tutorial ASAP. Thanks for your time and any kind of suggestions or criticism is highly appreciable. You can follow my profile to have a look at several tutorials." }, { "code": null, "e": 10766, "s": 10755, "text": "medium.com" }, { "code": null, "e": 11137, "s": 10766, "text": "Numpy: https://numpy.org/Stanford cs231 : http://cs231n.github.io/python-numpy-tutorial/Numpy basic cheetsheet: https://s3.amazonaws.com/assets.datacamp.com/blog_assets/Numpy_Python_Cheat_Sheet.pdfPandas : https://pandas.pydata.org/Pandas cheetsheet: https://pandas.pydata.org/Pandas_Cheat_Sheet.pdf https://assets.datacamp.com/blog_assets/PandasPythonForDataScience.pdf" }, { "code": null, "e": 11163, "s": 11137, "text": "Numpy: https://numpy.org/" }, { "code": null, "e": 11227, "s": 11163, "text": "Stanford cs231 : http://cs231n.github.io/python-numpy-tutorial/" }, { "code": null, "e": 11337, "s": 11227, "text": "Numpy basic cheetsheet: https://s3.amazonaws.com/assets.datacamp.com/blog_assets/Numpy_Python_Cheat_Sheet.pdf" }, { "code": null, "e": 11373, "s": 11337, "text": "Pandas : https://pandas.pydata.org/" } ]
Splunk - Lookups
In the result of a search query, we sometimes get values which may not clearly convey the meaning of the field. For example, we may get a field which lists the value of product id as a numeric result. These numbers will not give us any idea of what kind of product it is. But if we list the product name along with the product id, that gives us a good report where we understand the meaning of the search result. Such linking of values of one field to a field with same name in another dataset using equal values from both the data sets is called a lookup process. The advantage is, we retrieve the related values from two different data sets. In order to successfully create a lookup field in a dataset, we need to follow the below steps − We consider the dataset with host as web_application, and look at the productid field. This field is just a number, but we want product names to be reflected in our query result set. We create a lookup file with the following details. Here, we have kept the name of the first field as productid which is same as the field we are going to use from the dataset. productId,productdescription WC-SH-G04,Tablets DB-SG-G01,PCs DC-SG-G02,MobilePhones SC-MG-G10,Wearables WSC-MG-G10,Usb Light GT-SC-G01,Battery SF-BVS-G01,Hard Drive Next, we add the lookup file to Splunk environment by using the Settings screens as shown below − After selecting the Lookups, we are presented with a screen to create and configure lookup. We select lookup table files as shown below. We browse to select the file productidvals.csv as our lookup file to be uploaded and select search as our destination app. We also keep the same destination file name. On clicking the save button, the file gets saved to the Splunk repository as a lookup file. For a search query to be able to lookup values from the Lookup file we just uploaded above, we need to create a lookup definition. We do this by again going to Settings → Lookups → Lookup Definition → Add New . Next, we check the availability of the lookup definition we added by going to Settings → Lookups → Lookup Definition . Next, we need to select the lookup field for our search query. This is done my going to New search → All Fields . Then check the box for productid which will automatically add the productdescription field from the lookup file also. Now we use the Lookup field in the search query as shown below. The visualization shows the result with productdescription field instead of productid. Print Add Notes Bookmark this page
[ { "code": null, "e": 2774, "s": 2361, "text": "In the result of a search query, we sometimes get values which may not clearly convey the meaning of the field. For example, we may get a field which lists the value of product id as a numeric result. These numbers will not give us any idea of what kind of product it is. But if we list the product name along with the product id, that gives us a good report where we understand the meaning of the search result." }, { "code": null, "e": 3005, "s": 2774, "text": "Such linking of values of one field to a field with same name in another dataset using equal values from both the data sets is called a lookup process. The advantage is, we retrieve the related values from two different data sets." }, { "code": null, "e": 3102, "s": 3005, "text": "In order to successfully create a lookup field in a dataset, we need to follow the below steps −" }, { "code": null, "e": 3462, "s": 3102, "text": "We consider the dataset with host as web_application, and look at the productid field. This field is just a number, but we want product names to be reflected in our query result set. We create a lookup file with the following details. Here, we have kept the name of the first field as productid which is same as the field we are going to use from the dataset." }, { "code": null, "e": 3628, "s": 3462, "text": "productId,productdescription\nWC-SH-G04,Tablets\nDB-SG-G01,PCs\nDC-SG-G02,MobilePhones\nSC-MG-G10,Wearables \nWSC-MG-G10,Usb Light\nGT-SC-G01,Battery\nSF-BVS-G01,Hard Drive" }, { "code": null, "e": 3726, "s": 3628, "text": "Next, we add the lookup file to Splunk environment by using the Settings screens as shown below −" }, { "code": null, "e": 3863, "s": 3726, "text": "After selecting the Lookups, we are presented with a screen to create and configure lookup. We select lookup table files as shown below." }, { "code": null, "e": 4031, "s": 3863, "text": "We browse to select the file productidvals.csv as our lookup file to be uploaded and select search as our destination app. We also keep the same destination file name." }, { "code": null, "e": 4123, "s": 4031, "text": "On clicking the save button, the file gets saved to the Splunk repository as a lookup file." }, { "code": null, "e": 4334, "s": 4123, "text": "For a search query to be able to lookup values from the Lookup file we just uploaded above, we need to create a lookup definition. We do this by again going to Settings → Lookups → Lookup Definition → Add New ." }, { "code": null, "e": 4453, "s": 4334, "text": "Next, we check the availability of the lookup definition we added by going to Settings → Lookups → Lookup Definition ." }, { "code": null, "e": 4686, "s": 4453, "text": "Next, we need to select the lookup field for our search query. This is done my going to New search → All Fields . Then check the box for productid which will automatically add the productdescription field from the lookup file also." }, { "code": null, "e": 4837, "s": 4686, "text": "Now we use the Lookup field in the search query as shown below. The visualization shows the result with productdescription field instead of productid." }, { "code": null, "e": 4844, "s": 4837, "text": " Print" }, { "code": null, "e": 4855, "s": 4844, "text": " Add Notes" } ]
Constructor in Java Abstract Class - GeeksforGeeks
15 Mar, 2022 Constructor is always called by its class name in a class itself. A constructor is used to initialize an object not to build the object. As we all know abstract classes also do have a constructor. So if we do not define any constructor inside the abstract class then JVM (Java Virtual Machine) will give a default constructor to the abstract class. If we want to know how to define user define constructors like constructors with argument or any kind of constructor inside the abstract class then you should follow the given procedure. Note: An abstract class is a class declared with an abstract keyword. Properties of an abstract class: An abstract can have an abstract and a non-abstract method. It must be declared with an abstract keyword. It can have a constructor, static method. It can have a final method that prevents child class of abstract class not to change the body of the method The abstract method contains no-body or in simple words, you can say that you can’t define an abstract method inside an abstract class. We can define an abstract method inside the derived class of its abstract class. The object of the abstract class can’t be instantiated it means you can’t create an abstract class object directly but you can create its object by reference to its child class. Procedure: If you define your own constructor with arguments inside an abstract class but forget to call your own constructor inside its derived class constructor then JVM will call the constructor by default. So if you define your single or multi-argument constructor inside the abstract class then make sure to call the constructor inside the derived class constructor with the super keyword. Implementation: Here in this program, we are going to multiply two numbers by using the following above approach as mentioned. Step 1: We create an abstract class named ‘Content’ and define a user define a constructor with one argument, variable with name ‘a’, and an abstract method named as ‘multiply’ Step 2: We create a class that must be derived from this abstract class ‘Content’ named ‘GFG’. Inside GFG class we are going to define a constructor and inside the method call the parent class constructor by using the super keyword and define the abstract method of its parent class in it. Step 3: Now in the main class of our function that is ‘GeeksforGeeks’ here, where we will create an object of abstract class ‘Content’ by reference to its derived class object. Then we call the method of the abstract class by its object. Step 4: Inside the method, we multiply both the value stored in the different variable names where one of the variables is the variable of an abstract class. We can access the variable of the abstract class by its derived class object. Example: Java // Java Program to Illustrate Concept of Constructors// in Abstract Class // Class 1// Helper Abstract class// Parent classabstract class Content { int a; // Constructor of abstract class public Content(int a) { // This keyword refers to current instance itself this.a = a; } // Abstract method of abstract class abstract int multiply(int val);} // Class 2// Helper class extending above Class1// Child class of Abstract classclass GFG extends Content { // Constructor of Child class GFG GFG() { // Super keyword refers to parent class super(2); } // Defining method the abstract method public int multiply(int val) { // Returning value of same instance return this.a * val; }} // Class 3// Main classpublic class GeeksforGeeks { // Main driver method public static void main(String args[]) { // Creating reference object of abstract class // using it child class Content c = new GFG(); // Calling abstract method of abstract class System.out.println(c.multiply(3)); }} 6 sweetyty rajeev0719singh solankimayank rahuldwvdi Java-Abstract Class and Interface Java-Constructors Picked Technical Scripter 2020 Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Generics in Java Comparator Interface in Java with Examples Strings in Java Difference between Abstract Class and Interface in Java How to remove an element from ArrayList in Java?
[ { "code": null, "e": 23583, "s": 23555, "text": "\n15 Mar, 2022" }, { "code": null, "e": 24119, "s": 23583, "text": "Constructor is always called by its class name in a class itself. A constructor is used to initialize an object not to build the object. As we all know abstract classes also do have a constructor. So if we do not define any constructor inside the abstract class then JVM (Java Virtual Machine) will give a default constructor to the abstract class. If we want to know how to define user define constructors like constructors with argument or any kind of constructor inside the abstract class then you should follow the given procedure." }, { "code": null, "e": 24189, "s": 24119, "text": "Note: An abstract class is a class declared with an abstract keyword." }, { "code": null, "e": 24222, "s": 24189, "text": "Properties of an abstract class:" }, { "code": null, "e": 24282, "s": 24222, "text": "An abstract can have an abstract and a non-abstract method." }, { "code": null, "e": 24328, "s": 24282, "text": "It must be declared with an abstract keyword." }, { "code": null, "e": 24370, "s": 24328, "text": "It can have a constructor, static method." }, { "code": null, "e": 24478, "s": 24370, "text": "It can have a final method that prevents child class of abstract class not to change the body of the method" }, { "code": null, "e": 24695, "s": 24478, "text": "The abstract method contains no-body or in simple words, you can say that you can’t define an abstract method inside an abstract class. We can define an abstract method inside the derived class of its abstract class." }, { "code": null, "e": 24873, "s": 24695, "text": "The object of the abstract class can’t be instantiated it means you can’t create an abstract class object directly but you can create its object by reference to its child class." }, { "code": null, "e": 24884, "s": 24873, "text": "Procedure:" }, { "code": null, "e": 25083, "s": 24884, "text": "If you define your own constructor with arguments inside an abstract class but forget to call your own constructor inside its derived class constructor then JVM will call the constructor by default." }, { "code": null, "e": 25268, "s": 25083, "text": "So if you define your single or multi-argument constructor inside the abstract class then make sure to call the constructor inside the derived class constructor with the super keyword." }, { "code": null, "e": 25395, "s": 25268, "text": "Implementation: Here in this program, we are going to multiply two numbers by using the following above approach as mentioned." }, { "code": null, "e": 25572, "s": 25395, "text": "Step 1: We create an abstract class named ‘Content’ and define a user define a constructor with one argument, variable with name ‘a’, and an abstract method named as ‘multiply’" }, { "code": null, "e": 25862, "s": 25572, "text": "Step 2: We create a class that must be derived from this abstract class ‘Content’ named ‘GFG’. Inside GFG class we are going to define a constructor and inside the method call the parent class constructor by using the super keyword and define the abstract method of its parent class in it." }, { "code": null, "e": 26100, "s": 25862, "text": "Step 3: Now in the main class of our function that is ‘GeeksforGeeks’ here, where we will create an object of abstract class ‘Content’ by reference to its derived class object. Then we call the method of the abstract class by its object." }, { "code": null, "e": 26336, "s": 26100, "text": "Step 4: Inside the method, we multiply both the value stored in the different variable names where one of the variables is the variable of an abstract class. We can access the variable of the abstract class by its derived class object." }, { "code": null, "e": 26345, "s": 26336, "text": "Example:" }, { "code": null, "e": 26350, "s": 26345, "text": "Java" }, { "code": "// Java Program to Illustrate Concept of Constructors// in Abstract Class // Class 1// Helper Abstract class// Parent classabstract class Content { int a; // Constructor of abstract class public Content(int a) { // This keyword refers to current instance itself this.a = a; } // Abstract method of abstract class abstract int multiply(int val);} // Class 2// Helper class extending above Class1// Child class of Abstract classclass GFG extends Content { // Constructor of Child class GFG GFG() { // Super keyword refers to parent class super(2); } // Defining method the abstract method public int multiply(int val) { // Returning value of same instance return this.a * val; }} // Class 3// Main classpublic class GeeksforGeeks { // Main driver method public static void main(String args[]) { // Creating reference object of abstract class // using it child class Content c = new GFG(); // Calling abstract method of abstract class System.out.println(c.multiply(3)); }}", "e": 27465, "s": 26350, "text": null }, { "code": null, "e": 27467, "s": 27465, "text": "6" }, { "code": null, "e": 27476, "s": 27467, "text": "sweetyty" }, { "code": null, "e": 27492, "s": 27476, "text": "rajeev0719singh" }, { "code": null, "e": 27506, "s": 27492, "text": "solankimayank" }, { "code": null, "e": 27517, "s": 27506, "text": "rahuldwvdi" }, { "code": null, "e": 27551, "s": 27517, "text": "Java-Abstract Class and Interface" }, { "code": null, "e": 27569, "s": 27551, "text": "Java-Constructors" }, { "code": null, "e": 27576, "s": 27569, "text": "Picked" }, { "code": null, "e": 27600, "s": 27576, "text": "Technical Scripter 2020" }, { "code": null, "e": 27605, "s": 27600, "text": "Java" }, { "code": null, "e": 27624, "s": 27605, "text": "Technical Scripter" }, { "code": null, "e": 27629, "s": 27624, "text": "Java" }, { "code": null, "e": 27727, "s": 27629, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27736, "s": 27727, "text": "Comments" }, { "code": null, "e": 27749, "s": 27736, "text": "Old Comments" }, { "code": null, "e": 27779, "s": 27749, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27794, "s": 27779, "text": "Stream In Java" }, { "code": null, "e": 27815, "s": 27794, "text": "Constructors in Java" }, { "code": null, "e": 27861, "s": 27815, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27880, "s": 27861, "text": "Exceptions in Java" }, { "code": null, "e": 27897, "s": 27880, "text": "Generics in Java" }, { "code": null, "e": 27940, "s": 27897, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27956, "s": 27940, "text": "Strings in Java" }, { "code": null, "e": 28012, "s": 27956, "text": "Difference between Abstract Class and Interface in Java" } ]
Cohort Analysis with Python. A data clustering skill that every... | by Joe Tran | Towards Data Science
If you are a data analyst working for an e-commerce company, there is a high chance that one of your tasks at work is to discover insights from customer data to improve customer retention. However, the customer data is massive and each customer behaves differently. Customer A who was acquired in March 2020 displays a different behaviour from customer B who was acquired in May 2020. Therefore, it is essential to group customers into different clusters and then investigate the behaviour of each cluster over time. This is called cohort analysis. Cohort Analysis is the data analytic technique in understanding the behaviour of a special group of customers over a period of time. In this article, I will not go into details the theory of cohort analysis. If you do not know what cohort analysis is all about, I would strongly recommend you read this blog first. This article is more to show you how to segment customers into different cohorts and observe the retention rate for each cohort over a period of time. Let’s get into it! You can download the data here. import pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsdf = pd.read_csv('sales_2018-01-01_2019-12-31.csv')df first_time = df.loc[df['customer_type'] == 'First-time',]final = df.loc[df['customer_id'].isin(first_time['customer_id'].values)] Here is it not wise to just simply select df.loc[df['customer_type']]. Let me explain why. In this data, under the customer_type column, First_time refers to new customer, whereas Returning refers to returning customer. So if I first bought on 31 Dec 2019, the data will show me as new customer on 31 Dec 2019 but as returning customer on my 2nd, 3rd, ... time. The cohort analysis looks at new customers and their subsequent purchases. Therefore, if we simply use df.loc[df['customer_type']=='First-time',] we would be ignoring the subsequent purchases of the new customers, which is not a correct way to analyse cohort behaviour. Thus, what I did here was that, first create a list of all the first-time customers and store it as first_time. Then from the original customer dataframe df select only those customers whose IDs fall within the first_time customers group. By doing this, we can make sure that we obtain the data that has only first-time customers and their subsequent purchases. Now, let’s drop the customer_type column because it is not necessary anymore. Also, convert the day column into correct date-time format final = final.drop(columns = ['customer_type'])final['day']= pd.to_datetime(final['day'], dayfirst=True) final = final.sort_values(['customer_id','day'])final.reset_index(inplace = True, drop = True) def purchase_rate(customer_id): purchase_rate = [1] counter = 1 for i in range(1,len(customer_id)): if customer_id[i] != customer_id[i-1]: purchase_rate.append(1) counter = 1 else: counter += 1 purchase_rate.append(counter) return purchase_ratedef join_date(date, purchase_rate): join_date = list(range(len(date))) for i in range(len(purchase_rate)): if purchase_rate[i] == 1: join_date[i] = date[i] else: join_date[i] = join_date[i-1] return join_datedef age_by_month(purchase_rate, month, year, join_month, join_year): age_by_month = list(range(len(year))) for i in range(len(purchase_rate)): if purchase_rate[i] == 1: age_by_month[i] = 0 else: if year[i] == join_year[i]: age_by_month[i] = month[i] - join_month[i] else: age_by_month[i] = month[i] - join_month[i] + 12*(year[i]-join_year[i]) return age_by_month purchase_rate function will determine whether that is a 2nd, 3rd, 4th purchase of each customer. join_date function allows us to identify the date the customer joins. age_by_month function gives us how many months from the current purchase of a customer to the first time purchase. Now the input is ready. Let’s create cohorts. final['month'] =pd.to_datetime(final['day']).dt.monthfinal['Purchase Rate'] = purchase_rate(final['customer_id'])final['Join Date'] = join_date(final['day'], final['Purchase Rate'])final['Join Date'] = pd.to_datetime(final['Join Date'], dayfirst=True)final['cohort'] = pd.to_datetime(final['Join Date']).dt.strftime('%Y-%m')final['year'] = pd.to_datetime(final['day']).dt.yearfinal['Join Date Month'] = pd.to_datetime(final['Join Date']).dt.monthfinal['Join Date Year'] = pd.to_datetime(final['Join Date']).dt.year final['Age by month'] = age_by_month(final['Purchase Rate'], final['month'],final['year'],final['Join Date Month'],final['Join Date Year']) cohorts = final.groupby(['cohort','Age by month']).nunique()cohorts = cohorts.customer_id.to_frame().reset_index() # convert series to framecohorts = pd.pivot_table(cohorts, values = 'customer_id',index = 'cohort', columns= 'Age by month')cohorts.replace(np.nan, '',regex=True) How to interpret this tableTake cohort 2018–01 as an example. In Jan 2018, there were 462 new customers. Out of these 462, 121 customers came back and purchased in Feb 2018, 125 in Mar 2018 and so on and so forth. for i in range(len(cohorts)-1): cohorts[i+1] = cohorts[i+1]/cohorts[0]cohorts[0] = cohorts[0]/cohorts[0] cohorts_t = cohorts.transpose()cohorts_t[cohorts_t.columns].plot(figsize=(10,5))sns.set(style='whitegrid')plt.figure(figsize=(20, 15))plt.title('Cohorts: User Retention')sns.set(font_scale = 0.5) # font sizesns.heatmap(cohorts, mask=cohorts.isnull(),cmap="Blues",annot=True, fmt='.01%')plt.show() That is it. Hope you guys enjoyed and picked up something from this article. If you have any questions, feel free to put them down in the comment section below. Thank you for your read. Have a great day and happy new year 🎉🎉🎉
[ { "code": null, "e": 360, "s": 171, "text": "If you are a data analyst working for an e-commerce company, there is a high chance that one of your tasks at work is to discover insights from customer data to improve customer retention." }, { "code": null, "e": 720, "s": 360, "text": "However, the customer data is massive and each customer behaves differently. Customer A who was acquired in March 2020 displays a different behaviour from customer B who was acquired in May 2020. Therefore, it is essential to group customers into different clusters and then investigate the behaviour of each cluster over time. This is called cohort analysis." }, { "code": null, "e": 853, "s": 720, "text": "Cohort Analysis is the data analytic technique in understanding the behaviour of a special group of customers over a period of time." }, { "code": null, "e": 1035, "s": 853, "text": "In this article, I will not go into details the theory of cohort analysis. If you do not know what cohort analysis is all about, I would strongly recommend you read this blog first." }, { "code": null, "e": 1186, "s": 1035, "text": "This article is more to show you how to segment customers into different cohorts and observe the retention rate for each cohort over a period of time." }, { "code": null, "e": 1205, "s": 1186, "text": "Let’s get into it!" }, { "code": null, "e": 1237, "s": 1205, "text": "You can download the data here." }, { "code": null, "e": 1362, "s": 1237, "text": "import pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsdf = pd.read_csv('sales_2018-01-01_2019-12-31.csv')df" }, { "code": null, "e": 1492, "s": 1362, "text": "first_time = df.loc[df['customer_type'] == 'First-time',]final = df.loc[df['customer_id'].isin(first_time['customer_id'].values)]" }, { "code": null, "e": 2124, "s": 1492, "text": "Here is it not wise to just simply select df.loc[df['customer_type']]. Let me explain why. In this data, under the customer_type column, First_time refers to new customer, whereas Returning refers to returning customer. So if I first bought on 31 Dec 2019, the data will show me as new customer on 31 Dec 2019 but as returning customer on my 2nd, 3rd, ... time. The cohort analysis looks at new customers and their subsequent purchases. Therefore, if we simply use df.loc[df['customer_type']=='First-time',] we would be ignoring the subsequent purchases of the new customers, which is not a correct way to analyse cohort behaviour." }, { "code": null, "e": 2486, "s": 2124, "text": "Thus, what I did here was that, first create a list of all the first-time customers and store it as first_time. Then from the original customer dataframe df select only those customers whose IDs fall within the first_time customers group. By doing this, we can make sure that we obtain the data that has only first-time customers and their subsequent purchases." }, { "code": null, "e": 2623, "s": 2486, "text": "Now, let’s drop the customer_type column because it is not necessary anymore. Also, convert the day column into correct date-time format" }, { "code": null, "e": 2728, "s": 2623, "text": "final = final.drop(columns = ['customer_type'])final['day']= pd.to_datetime(final['day'], dayfirst=True)" }, { "code": null, "e": 2823, "s": 2728, "text": "final = final.sort_values(['customer_id','day'])final.reset_index(inplace = True, drop = True)" }, { "code": null, "e": 3891, "s": 2823, "text": "def purchase_rate(customer_id): purchase_rate = [1] counter = 1 for i in range(1,len(customer_id)): if customer_id[i] != customer_id[i-1]: purchase_rate.append(1) counter = 1 else: counter += 1 purchase_rate.append(counter) return purchase_ratedef join_date(date, purchase_rate): join_date = list(range(len(date))) for i in range(len(purchase_rate)): if purchase_rate[i] == 1: join_date[i] = date[i] else: join_date[i] = join_date[i-1] return join_datedef age_by_month(purchase_rate, month, year, join_month, join_year): age_by_month = list(range(len(year))) for i in range(len(purchase_rate)): if purchase_rate[i] == 1: age_by_month[i] = 0 else: if year[i] == join_year[i]: age_by_month[i] = month[i] - join_month[i] else: age_by_month[i] = month[i] - join_month[i] + 12*(year[i]-join_year[i]) return age_by_month" }, { "code": null, "e": 3988, "s": 3891, "text": "purchase_rate function will determine whether that is a 2nd, 3rd, 4th purchase of each customer." }, { "code": null, "e": 4058, "s": 3988, "text": "join_date function allows us to identify the date the customer joins." }, { "code": null, "e": 4173, "s": 4058, "text": "age_by_month function gives us how many months from the current purchase of a customer to the first time purchase." }, { "code": null, "e": 4219, "s": 4173, "text": "Now the input is ready. Let’s create cohorts." }, { "code": null, "e": 4734, "s": 4219, "text": "final['month'] =pd.to_datetime(final['day']).dt.monthfinal['Purchase Rate'] = purchase_rate(final['customer_id'])final['Join Date'] = join_date(final['day'], final['Purchase Rate'])final['Join Date'] = pd.to_datetime(final['Join Date'], dayfirst=True)final['cohort'] = pd.to_datetime(final['Join Date']).dt.strftime('%Y-%m')final['year'] = pd.to_datetime(final['day']).dt.yearfinal['Join Date Month'] = pd.to_datetime(final['Join Date']).dt.monthfinal['Join Date Year'] = pd.to_datetime(final['Join Date']).dt.year" }, { "code": null, "e": 4874, "s": 4734, "text": "final['Age by month'] = age_by_month(final['Purchase Rate'], final['month'],final['year'],final['Join Date Month'],final['Join Date Year'])" }, { "code": null, "e": 5154, "s": 4874, "text": "cohorts = final.groupby(['cohort','Age by month']).nunique()cohorts = cohorts.customer_id.to_frame().reset_index() # convert series to framecohorts = pd.pivot_table(cohorts, values = 'customer_id',index = 'cohort', columns= 'Age by month')cohorts.replace(np.nan, '',regex=True)" }, { "code": null, "e": 5368, "s": 5154, "text": "How to interpret this tableTake cohort 2018–01 as an example. In Jan 2018, there were 462 new customers. Out of these 462, 121 customers came back and purchased in Feb 2018, 125 in Mar 2018 and so on and so forth." }, { "code": null, "e": 5476, "s": 5368, "text": "for i in range(len(cohorts)-1): cohorts[i+1] = cohorts[i+1]/cohorts[0]cohorts[0] = cohorts[0]/cohorts[0]" }, { "code": null, "e": 5773, "s": 5476, "text": "cohorts_t = cohorts.transpose()cohorts_t[cohorts_t.columns].plot(figsize=(10,5))sns.set(style='whitegrid')plt.figure(figsize=(20, 15))plt.title('Cohorts: User Retention')sns.set(font_scale = 0.5) # font sizesns.heatmap(cohorts, mask=cohorts.isnull(),cmap=\"Blues\",annot=True, fmt='.01%')plt.show()" } ]
Minimum Number of Platforms Problem
A list of arrival and departure time is given. Now the problem is to find the minimum number of platforms are required for the railway as no train waits. By sorting all timings in sorted order, we can find the solution easily, it will be easy to track when the train has arrived but not left the station. The time complexity of this problem is O(n Log n). Input: Lists of arrival time and departure time. Arrival: {900, 940, 950, 1100, 1500, 1800} Departure: {910, 1200, 1120, 1130, 1900, 2000} Output: Minimum Number of Platforms Required: 3 minPlatform(arrival, departure, int n) Input − The list of arrival time and the departure times, and the number of items in the list Output − The number of minimum platforms is needed to solve the problem. Begin sort arrival time list, and departure time list platform := 1 and minPlatform := 1 i := 1 and j := 0 for elements in arrival list ‘i’ and departure list ‘j’ do if arrival[i] < departure[j] then platform := platform + 1 i := i+1 if platform > minPlatform then minPlatform := platform else platform := platform – 1 j := j + 1 done return minPlatform End #include<iostream> #include<algorithm> using namespace std; int minPlatform(int arrival[], int departure[], int n) { sort(arrival, arrival+n); //sort arrival and departure times sort(departure, departure+n); int platform = 1, minPlatform = 1; int i = 1, j = 0; while (i < n && j < n) { if (arrival[i] < departure[j]) { platform++; //platform added i++; if (platform > minPlatform) //if platform value is greater, update minPlatform minPlatform = platform; } else { platform--; //delete platform j++; } } return minPlatform; } int main() { int arrival[] = {900, 940, 950, 1100, 1500, 1800}; int departure[] = {910, 1200, 1120, 1130, 1900, 2000}; int n = 6; cout << "Minimum Number of Platforms Required: " << minPlatform(arrival, departure, n); } Minimum Number of Platforms Required: 3
[ { "code": null, "e": 1216, "s": 1062, "text": "A list of arrival and departure time is given. Now the problem is to find the minimum number of platforms are required for the railway as no train waits." }, { "code": null, "e": 1367, "s": 1216, "text": "By sorting all timings in sorted order, we can find the solution easily, it will be easy to track when the train has arrived but not left the station." }, { "code": null, "e": 1418, "s": 1367, "text": "The time complexity of this problem is O(n Log n)." }, { "code": null, "e": 1605, "s": 1418, "text": "Input:\nLists of arrival time and departure time.\nArrival: {900, 940, 950, 1100, 1500, 1800}\nDeparture: {910, 1200, 1120, 1130, 1900, 2000}\nOutput:\nMinimum Number of Platforms Required: 3" }, { "code": null, "e": 1644, "s": 1605, "text": "minPlatform(arrival, departure, int n)" }, { "code": null, "e": 1738, "s": 1644, "text": "Input − The list of arrival time and the departure times, and the number of items in the list" }, { "code": null, "e": 1811, "s": 1738, "text": "Output − The number of minimum platforms is needed to solve the problem." }, { "code": null, "e": 2257, "s": 1811, "text": "Begin\n sort arrival time list, and departure time list\n platform := 1 and minPlatform := 1\n i := 1 and j := 0\n\n for elements in arrival list ‘i’ and departure list ‘j’ do\n if arrival[i] < departure[j] then\n platform := platform + 1\n i := i+1\n if platform > minPlatform then\n minPlatform := platform\n else\n platform := platform – 1\n j := j + 1\n done\n return minPlatform\nEnd" }, { "code": null, "e": 3131, "s": 2257, "text": "#include<iostream>\n#include<algorithm>\nusing namespace std;\n\nint minPlatform(int arrival[], int departure[], int n) {\n sort(arrival, arrival+n); //sort arrival and departure times\n sort(departure, departure+n);\n\n int platform = 1, minPlatform = 1;\n int i = 1, j = 0;\n\n while (i < n && j < n) {\n if (arrival[i] < departure[j]) {\n platform++; //platform added\n i++;\n if (platform > minPlatform) //if platform value is greater, update minPlatform\n minPlatform = platform;\n } else {\n platform--; //delete platform\n j++;\n }\n }\n return minPlatform;\n}\n\nint main() {\n int arrival[] = {900, 940, 950, 1100, 1500, 1800};\n int departure[] = {910, 1200, 1120, 1130, 1900, 2000};\n int n = 6;\n cout << \"Minimum Number of Platforms Required: \" << minPlatform(arrival, departure, n);\n}" }, { "code": null, "e": 3171, "s": 3131, "text": "Minimum Number of Platforms Required: 3" } ]
Splitting your data to fit any machine learning model | by Magdalena Konkiewicz | Towards Data Science
Introduction After you have performed data cleaning, data visualizations, and learned details about your data it is time to fit the first machine learning model into it. Today I want to share with you a few very simple lines of code that will divide any data set into variables that you can pass to any machine learning model and start training it. It is trivially simple but an understanding of how the split function for training and test data sets work is crucial for any Data Scientist. Let’s dive into it. Preparing data We are going to create a simple medical data set for visualization purposes. Imagine that we are trying to predict if the patient is healthy or not based on his weight, height, and information if he drinks alcohol or not. Therefore we will have three columns with this information and a fourth column that holds the record if the patient is healthy or not. This is our target variable, something we want to predict. We will have only 10 patients for simplicity here. Let’s create this data frame: import pandas as pdimport numpy as npclient_dictionary = {'weight': [112, 123, 176, 145, 198, 211, 145, 181, 90, 101], 'height': [181, 165, 167, 154, 181, 202, 201, 153, 142, 169], 'drinks alcohol': [0, 1, 1, 1, 0, 1, 1, 1, 0, 1], 'healthy': [0, 1, 1, 1, 0, 0, 1, 1, 1, 1],}df = pd.DataFrame(client_dictionary)df.head(10) Our data frame looks like this: Separating features from the target variable We should start with separating features for our model from the target variable. Notice that in our case all columns except ‘healthy’ are features that we want to use for the model. Our target variable is ‘healthy’. We can use the following code to do target separation. x_data = df[['weight', 'height', 'drinks alcohol']]y_data = df['healthy'] Now our x_data looks like this: And y_data looks like this: Using train_test_split Let’s now use train_test_split from the function from scikit-learn to divide features data (x_data) and target data (y_data) even further into train and test. from sklearn.model_selection import train_test_splitx_train, x_test, y_train, y_test = train_test_split(x_data, y_data ,test_size = 0.2, shuffle=False) As a result, we will have our initial data frame partitioned into four different data sets as pictured below: When calling train_test_split function I have used parameter shuffle=False to achieve the results you can see in the picture above. The first 80 % of the data was assigned to training and the remaining 20% was assigned to test. The default parameter for shuffle is True and this is what you would normally use in a real-life example. This means that the rows before the data is split into test and train are shuffled so their order is changed. Controlling test-train split fraction You can control the train_test split fraction by using the test_size parameter. Note that we had it set to 0.2 in our example. It can be any number between 0.0 and 1.0. You do not have to specify the fraction for the train set as by the default it will use all the remaining data that is not taken for the test set. Train your machine learning model The data that you have prepared is now ready to be fed to the machine learning model. Let’s just illustrate it with a very simple linear regression model. from sklearn import linear_modellinear_regression_model = linear_model.LinearRegression()linear_regression_model.fit(x_train, y_train) The model above is trained using x_train and y_train samples. You can now make predictions on the test set using the following code. y_pred = linear_regression_model.predict(x_test) Now if you would like to assess how good your model is you would need to compare your predictions on the test set (y_pred) with the real target values for the test set (y_test). But this is a different story and we will not cover this here. Conclusion You have learned how to separate your data set into features and target variable, and then further split it into test and train parts. And all of this just with few lines of code, elegant and simple. Furthermore, I hope you got to understand how the split works and you will be using it wisely from now on instead of just copy-pasting the code you have found. And if you do copy-paste code from time to time, it is still ok, but what satisfaction you have where you actually get to understand it. Originally published at aboutdatablog.com: Splitting your data to fit any machine learning model, on October 23, 2019. PS: I am writing articles that explain basic Data Science concepts in a simple and comprehensible manner on Medium and aboutdatablog.com. You can subscribe to my email list to get notified every time I write a new article. And if you are not a Medium member yet you can join here. Below there are some other posts you may enjoy:
[ { "code": null, "e": 185, "s": 172, "text": "Introduction" }, { "code": null, "e": 521, "s": 185, "text": "After you have performed data cleaning, data visualizations, and learned details about your data it is time to fit the first machine learning model into it. Today I want to share with you a few very simple lines of code that will divide any data set into variables that you can pass to any machine learning model and start training it." }, { "code": null, "e": 683, "s": 521, "text": "It is trivially simple but an understanding of how the split function for training and test data sets work is crucial for any Data Scientist. Let’s dive into it." }, { "code": null, "e": 698, "s": 683, "text": "Preparing data" }, { "code": null, "e": 1195, "s": 698, "text": "We are going to create a simple medical data set for visualization purposes. Imagine that we are trying to predict if the patient is healthy or not based on his weight, height, and information if he drinks alcohol or not. Therefore we will have three columns with this information and a fourth column that holds the record if the patient is healthy or not. This is our target variable, something we want to predict. We will have only 10 patients for simplicity here. Let’s create this data frame:" }, { "code": null, "e": 1578, "s": 1195, "text": "import pandas as pdimport numpy as npclient_dictionary = {'weight': [112, 123, 176, 145, 198, 211, 145, 181, 90, 101], 'height': [181, 165, 167, 154, 181, 202, 201, 153, 142, 169], 'drinks alcohol': [0, 1, 1, 1, 0, 1, 1, 1, 0, 1], 'healthy': [0, 1, 1, 1, 0, 0, 1, 1, 1, 1],}df = pd.DataFrame(client_dictionary)df.head(10)" }, { "code": null, "e": 1610, "s": 1578, "text": "Our data frame looks like this:" }, { "code": null, "e": 1655, "s": 1610, "text": "Separating features from the target variable" }, { "code": null, "e": 1926, "s": 1655, "text": "We should start with separating features for our model from the target variable. Notice that in our case all columns except ‘healthy’ are features that we want to use for the model. Our target variable is ‘healthy’. We can use the following code to do target separation." }, { "code": null, "e": 2000, "s": 1926, "text": "x_data = df[['weight', 'height', 'drinks alcohol']]y_data = df['healthy']" }, { "code": null, "e": 2032, "s": 2000, "text": "Now our x_data looks like this:" }, { "code": null, "e": 2060, "s": 2032, "text": "And y_data looks like this:" }, { "code": null, "e": 2083, "s": 2060, "text": "Using train_test_split" }, { "code": null, "e": 2242, "s": 2083, "text": "Let’s now use train_test_split from the function from scikit-learn to divide features data (x_data) and target data (y_data) even further into train and test." }, { "code": null, "e": 2394, "s": 2242, "text": "from sklearn.model_selection import train_test_splitx_train, x_test, y_train, y_test = train_test_split(x_data, y_data ,test_size = 0.2, shuffle=False)" }, { "code": null, "e": 2504, "s": 2394, "text": "As a result, we will have our initial data frame partitioned into four different data sets as pictured below:" }, { "code": null, "e": 2948, "s": 2504, "text": "When calling train_test_split function I have used parameter shuffle=False to achieve the results you can see in the picture above. The first 80 % of the data was assigned to training and the remaining 20% was assigned to test. The default parameter for shuffle is True and this is what you would normally use in a real-life example. This means that the rows before the data is split into test and train are shuffled so their order is changed." }, { "code": null, "e": 2986, "s": 2948, "text": "Controlling test-train split fraction" }, { "code": null, "e": 3302, "s": 2986, "text": "You can control the train_test split fraction by using the test_size parameter. Note that we had it set to 0.2 in our example. It can be any number between 0.0 and 1.0. You do not have to specify the fraction for the train set as by the default it will use all the remaining data that is not taken for the test set." }, { "code": null, "e": 3336, "s": 3302, "text": "Train your machine learning model" }, { "code": null, "e": 3491, "s": 3336, "text": "The data that you have prepared is now ready to be fed to the machine learning model. Let’s just illustrate it with a very simple linear regression model." }, { "code": null, "e": 3626, "s": 3491, "text": "from sklearn import linear_modellinear_regression_model = linear_model.LinearRegression()linear_regression_model.fit(x_train, y_train)" }, { "code": null, "e": 3759, "s": 3626, "text": "The model above is trained using x_train and y_train samples. You can now make predictions on the test set using the following code." }, { "code": null, "e": 3808, "s": 3759, "text": "y_pred = linear_regression_model.predict(x_test)" }, { "code": null, "e": 4049, "s": 3808, "text": "Now if you would like to assess how good your model is you would need to compare your predictions on the test set (y_pred) with the real target values for the test set (y_test). But this is a different story and we will not cover this here." }, { "code": null, "e": 4060, "s": 4049, "text": "Conclusion" }, { "code": null, "e": 4260, "s": 4060, "text": "You have learned how to separate your data set into features and target variable, and then further split it into test and train parts. And all of this just with few lines of code, elegant and simple." }, { "code": null, "e": 4420, "s": 4260, "text": "Furthermore, I hope you got to understand how the split works and you will be using it wisely from now on instead of just copy-pasting the code you have found." }, { "code": null, "e": 4557, "s": 4420, "text": "And if you do copy-paste code from time to time, it is still ok, but what satisfaction you have where you actually get to understand it." }, { "code": null, "e": 4676, "s": 4557, "text": "Originally published at aboutdatablog.com: Splitting your data to fit any machine learning model, on October 23, 2019." }, { "code": null, "e": 4957, "s": 4676, "text": "PS: I am writing articles that explain basic Data Science concepts in a simple and comprehensible manner on Medium and aboutdatablog.com. You can subscribe to my email list to get notified every time I write a new article. And if you are not a Medium member yet you can join here." } ]
How I can create Python class from JSON object?
We can use python-jsonschema-objects which is built on top of jsonschema.The python-jsonschema-objects provide an automatic class-based binding to JSON schemas for use in Python. We have a sample json schema as follows schema = '''{ "title": "Example Schema", "type": "object", "properties": { "firstName": { "type": "string" }, "lastName": { "type": "string" }, "age": { "description": "Age in years", "type": "integer", "minimum": 0 }, "dogs": { "type": "array", "items": {"type": "string"}, "maxItems": 4 }, "gender": { "type": "string", "enum": ["male", "female"] }, "deceased": { "enum": ["yes", "no", 1, 0, "true", "false"] } }, "required": ["firstName", "lastName"] } ''' Converting the schema object to class import python_jsonschema_objects as pjs builder = pjs.ObjectBuilder(schema) ns = builder.build_classes() Person = ns.ExampleSchema jack = Person(firstName="Jack", lastName="Sparrow") jack.lastName example_schema lastName=Sparrow age=None firstName=Jack Validation − jack.age = -2 python_jsonschema_objects.validators.ValidationError: -2 was less or equal to than 0
[ { "code": null, "e": 1241, "s": 1062, "text": "We can use python-jsonschema-objects which is built on top of jsonschema.The python-jsonschema-objects provide an automatic class-based binding to JSON schemas for use in Python." }, { "code": null, "e": 1281, "s": 1241, "text": "We have a sample json schema as follows" }, { "code": null, "e": 1993, "s": 1281, "text": "schema = '''{ \"title\": \"Example Schema\", \"type\": \"object\", \"properties\": { \"firstName\": { \"type\": \"string\" }, \"lastName\": { \"type\": \"string\" }, \"age\": { \"description\": \"Age in years\", \"type\": \"integer\", \"minimum\": 0 }, \"dogs\": { \"type\": \"array\", \"items\": {\"type\": \"string\"}, \"maxItems\": 4 }, \"gender\": { \"type\": \"string\", \"enum\": [\"male\", \"female\"] }, \"deceased\": { \"enum\": [\"yes\", \"no\", 1, 0, \"true\", \"false\"] } }, \"required\": [\"firstName\", \"lastName\"] } '''" }, { "code": null, "e": 2031, "s": 1993, "text": "Converting the schema object to class" }, { "code": null, "e": 2306, "s": 2031, "text": " import python_jsonschema_objects as pjs \n builder = pjs.ObjectBuilder(schema) \n ns = builder.build_classes() \n Person = ns.ExampleSchema \n jack = Person(firstName=\"Jack\", lastName=\"Sparrow\") \n jack.lastName \n example_schema lastName=Sparrow age=None firstName=Jack " }, { "code": null, "e": 2319, "s": 2306, "text": "Validation −" }, { "code": null, "e": 2418, "s": 2319, "text": "jack.age = -2 python_jsonschema_objects.validators.ValidationError: -2 was less or equal to than 0" } ]
MySQL FLUSH Statement
The FLUSH statement in MySQL is used to clear the caches. Following is the syntax of MySQL FLUSH statement − FLUSH [NO_WRITE_TO_BINLOG | LOCAL] { BINARY LOGS | ENGINE LOGS | ERROR LOGS | GENERAL LOGS | HOSTS | LOGS | PRIVILEGES | OPTIMIZER_COSTS | RELAY LOGS | SLOW LOGS | STATUS | USER_RESOURCES } Following are various (options) FLUSH statements − mysql> FLUSH BINARY LOGS; Query OK, 0 rows affected (0.81 sec) mysql> FLUSH ENGINE LOGS; Query OK, 0 rows affected (0.34 sec) mysql> FLUSH ERROR LOGS; Query OK, 0 rows affected (0.12 sec) mysql> FLUSH GENERAL LOGS; Query OK, 0 rows affected (0.07 sec) mysql> FLUSH HOSTS; Query OK, 0 rows affected (0.07 sec) mysql> FLUSH LOGS; Query OK, 0 rows affected (1.27 sec) mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.13 sec) mysql> FLUSH OPTIMIZER_COSTS; Query OK, 0 rows affected (0.29 sec) mysql> FLUSH RELAY LOGS; Query OK, 0 rows affected (0.09 sec) mysql> FLUSH STATUS; Query OK, 0 rows affected (0.12 sec) mysql> FLUSH USER_RESOURCES; Query OK, 0 rows affected (0.78 sec) Using the FLUSH tables statement you can flush the data in the table or acquire locks. Following is the syntax of the FLUSH TABLES statement − FLUSH TABLES { tbl_name [, tbl_name] ... | WITH READ LOCK | tbl_name [, tbl_name] ... WITH READ LOCK | tbl_name [, tbl_name] ... FOR EXPORT } Suppose we have created a table that contains the sales details along with the contact details of the customers as shown below − mysql> CREATE TABLE SALES_DETAILS ( ID INT, ProductName VARCHAR(255), CustomerName VARCHAR(255), DispatchDate date, DeliveryTime time, Price INT, Location VARCHAR(255), CustomerAge INT, CustomrtPhone BIGINT, DispatchAddress VARCHAR(255), Email VARCHAR(50) ); Now, let’s insert 2 records into the above created table using the INSERT statement as − mysql> insert into SALES_DETAILS values(1, 'Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad', 25, '9000012345', 'Hyderabad – Madhapur', '[email protected]'); Query OK, 1 row affected (0.84 sec) mysql> insert into SALES_DETAILS values(2, 'Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai', 30, '90000123654', 'Chennai- TNagar', '[email protected]'); Query OK, 1 row affected (1.84 sec) If we want another table with just the contact details of the customer create a table as − mysql> CREATE TABLE CustContactDetails ( ID INT, Name VARCHAR(255), Age INT, Phone BIGINT, Address VARCHAR(255), Email VARCHAR(50) ); Following query insets records into the CustContactDetails table using the INSERT INTO SELECT statement. Here, we are trying to insert records from the SALES_DETAILS table to CustContactDetails table − mysql> INSERT INTO CustContactDetails (ID, Name, Age, Phone, Address, Email) SELECT ID, CustomerName, CustomerAge, CustomrtPhone, DispatchAddress, Email FROM SALES_DETAILS WHERE ID = 1 AND CustomerName = 'Raja'; Query OK, 1 row affected (0.16 sec) Records: 1 Duplicates: 0 Warnings: 0 INSERT INTO CustContactDetails (ID, Name, Age, Phone, Address, Email) SELECT ID, CustomerName, CustomerAge, CustomrtPhone, DispatchAddress, Email FROM SALES_DETAILS WHERE ID = 2 AND CustomerName = 'Vanaja'; Query OK, 1 row affected (0.16 sec) You can verify the contents of the CustContactDetails table as shown below − mysql> SELECT * FROM CustContactDetails; +------+--------+------+-------------+----------------------+----------------------+ | ID | Name | Age | Phone | Address | Email | +------+--------+------+-------------+----------------------+----------------------+ | 1 | Raja | 25 | 9000012345 | Hyderabad – Madhapur | [email protected] | | 2 | Vanaja | 30 | 90000123654 | Chennai- TNagar | [email protected] | +------+--------+------+-------------+----------------------+----------------------+ 2 rows in set (0.00 sec) Following set of queries locks the instance flushes the above created tables and unlocks the instance. mysql> LOCK INSTANCE FOR BACKUP; Query OK, 0 rows affected (0.00 sec) mysql> FLUSH TABLES emp, custcontactdetails WITH READ LOCK; Query OK, 0 rows affected (0.05 sec) mysql> UNLOCK TABLES; Query OK, 0 rows affected (0.00 sec) mysql> UNLOCK INSTANCE; Query OK, 0 rows affected (0.00 sec) 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2391, "s": 2333, "text": "The FLUSH statement in MySQL is used to clear the caches." }, { "code": null, "e": 2442, "s": 2391, "text": "Following is the syntax of MySQL FLUSH statement −" }, { "code": null, "e": 2640, "s": 2442, "text": "FLUSH [NO_WRITE_TO_BINLOG | LOCAL] {\n BINARY LOGS | ENGINE LOGS | ERROR LOGS | GENERAL LOGS | HOSTS | LOGS | \n PRIVILEGES | OPTIMIZER_COSTS | RELAY LOGS | SLOW LOGS | STATUS | USER_RESOURCES\n}\n" }, { "code": null, "e": 2691, "s": 2640, "text": "Following are various (options) FLUSH statements −" }, { "code": null, "e": 3381, "s": 2691, "text": "mysql> FLUSH BINARY LOGS;\nQuery OK, 0 rows affected (0.81 sec)\n\nmysql> FLUSH ENGINE LOGS;\nQuery OK, 0 rows affected (0.34 sec)\n\nmysql> FLUSH ERROR LOGS;\nQuery OK, 0 rows affected (0.12 sec)\n\nmysql> FLUSH GENERAL LOGS;\nQuery OK, 0 rows affected (0.07 sec)\n\nmysql> FLUSH HOSTS;\nQuery OK, 0 rows affected (0.07 sec)\n\nmysql> FLUSH LOGS;\nQuery OK, 0 rows affected (1.27 sec)\n\nmysql> FLUSH PRIVILEGES;\nQuery OK, 0 rows affected (0.13 sec)\n\nmysql> FLUSH OPTIMIZER_COSTS;\nQuery OK, 0 rows affected (0.29 sec)\n\nmysql> FLUSH RELAY LOGS;\nQuery OK, 0 rows affected (0.09 sec)\n\nmysql> FLUSH STATUS;\nQuery OK, 0 rows affected (0.12 sec)\n\nmysql> FLUSH USER_RESOURCES;\nQuery OK, 0 rows affected (0.78 sec)" }, { "code": null, "e": 3468, "s": 3381, "text": "Using the FLUSH tables statement you can flush the data in the table or acquire locks." }, { "code": null, "e": 3524, "s": 3468, "text": "Following is the syntax of the FLUSH TABLES statement −" }, { "code": null, "e": 3679, "s": 3524, "text": "FLUSH TABLES {\n tbl_name [, tbl_name] ...\n | WITH READ LOCK\n | tbl_name [, tbl_name] ... WITH READ LOCK\n | tbl_name [, tbl_name] ... FOR EXPORT\n}\n" }, { "code": null, "e": 3808, "s": 3679, "text": "Suppose we have created a table that contains the sales details along with the contact details of the customers as shown below −" }, { "code": null, "e": 4100, "s": 3808, "text": "mysql> CREATE TABLE SALES_DETAILS (\n ID INT,\n ProductName VARCHAR(255),\n CustomerName VARCHAR(255),\n DispatchDate date,\n DeliveryTime time,\n Price INT,\n Location VARCHAR(255),\n CustomerAge INT,\n CustomrtPhone BIGINT,\n DispatchAddress VARCHAR(255),\n Email VARCHAR(50)\n);" }, { "code": null, "e": 4189, "s": 4100, "text": "Now, let’s insert 2 records into the above created table using the INSERT statement as −" }, { "code": null, "e": 4631, "s": 4189, "text": "mysql> insert into SALES_DETAILS values(1, 'Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad', 25, '9000012345', 'Hyderabad – Madhapur', '[email protected]');\nQuery OK, 1 row affected (0.84 sec)\n\nmysql> insert into SALES_DETAILS values(2, 'Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai', 30, '90000123654', 'Chennai- TNagar', '[email protected]');\nQuery OK, 1 row affected (1.84 sec)" }, { "code": null, "e": 4722, "s": 4631, "text": "If we want another table with just the contact details of the customer create a table as −" }, { "code": null, "e": 4874, "s": 4722, "text": "mysql> CREATE TABLE CustContactDetails (\n ID INT,\n Name VARCHAR(255),\n Age INT,\n Phone BIGINT,\n Address VARCHAR(255),\n Email VARCHAR(50)\n);" }, { "code": null, "e": 5076, "s": 4874, "text": "Following query insets records into the CustContactDetails table using the INSERT INTO SELECT statement. Here, we are trying to insert records from the SALES_DETAILS table to CustContactDetails table −" }, { "code": null, "e": 5659, "s": 5076, "text": "mysql> INSERT INTO CustContactDetails (ID, Name, Age, Phone, Address, Email)\n SELECT\n ID, CustomerName, CustomerAge, CustomrtPhone, DispatchAddress, Email\n FROM\n SALES_DETAILS\n WHERE\n ID = 1 AND CustomerName = 'Raja';\nQuery OK, 1 row affected (0.16 sec)\nRecords: 1 Duplicates: 0 Warnings: 0\n\nINSERT INTO CustContactDetails (ID, Name, Age, Phone, Address, Email)\n SELECT\n ID, CustomerName, CustomerAge, CustomrtPhone, DispatchAddress, Email\n FROM\n SALES_DETAILS\n WHERE\n ID = 2 AND CustomerName = 'Vanaja';\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 5736, "s": 5659, "text": "You can verify the contents of the CustContactDetails table as shown below −" }, { "code": null, "e": 6312, "s": 5736, "text": "mysql> SELECT * FROM CustContactDetails;\n+------+--------+------+-------------+----------------------+----------------------+\n| ID | Name | Age | Phone | Address | Email |\n+------+--------+------+-------------+----------------------+----------------------+\n| 1 | Raja | 25 | 9000012345 | Hyderabad – Madhapur | [email protected] |\n| 2 | Vanaja | 30 | 90000123654 | Chennai- TNagar | [email protected] |\n+------+--------+------+-------------+----------------------+----------------------+\n2 rows in set (0.00 sec)" }, { "code": null, "e": 6415, "s": 6312, "text": "Following set of queries locks the instance flushes the above created tables and unlocks the instance." }, { "code": null, "e": 6705, "s": 6415, "text": "mysql> LOCK INSTANCE FOR BACKUP;\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> FLUSH TABLES emp, custcontactdetails WITH READ LOCK;\nQuery OK, 0 rows affected (0.05 sec)\n\nmysql> UNLOCK TABLES;\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> UNLOCK INSTANCE;\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 6738, "s": 6705, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 6766, "s": 6738, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6801, "s": 6766, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6818, "s": 6801, "text": " Frahaan Hussain" }, { "code": null, "e": 6852, "s": 6818, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6887, "s": 6852, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 6921, "s": 6887, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 6949, "s": 6921, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 6982, "s": 6949, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 7002, "s": 6982, "text": " Harshit Srivastava" }, { "code": null, "e": 7035, "s": 7002, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 7053, "s": 7035, "text": " Trevoir Williams" }, { "code": null, "e": 7060, "s": 7053, "text": " Print" }, { "code": null, "e": 7071, "s": 7060, "text": " Add Notes" } ]
A* Search Algorithm - GeeksforGeeks
13 Apr, 2022 Motivation To approximate the shortest path in real-life situations, like- in maps, games where there can be many hindrances.We can consider a 2D Grid having several obstacles and we start from a source cell (colored red below) to reach towards a goal cell (colored green below) What is A* Search Algorithm? A* Search algorithm is one of the best and popular technique used in path-finding and graph traversals. Why A* Search Algorithm? Informally speaking, A* Search algorithms, unlike other traversal techniques, it has “brains”. What it means is that it is really a smart algorithm which separates it from the other conventional algorithms. This fact is cleared in detail in below sections. And it is also worth mentioning that many games and web-based maps use this algorithm to find the shortest path very efficiently (approximation). Explanation Consider a square grid having many obstacles and we are given a starting cell and a target cell. We want to reach the target cell (if possible) from the starting cell as quickly as possible. Here A* Search Algorithm comes to the rescue.What A* Search Algorithm does is that at each step it picks the node according to a value-‘f’ which is a parameter equal to the sum of two other parameters – ‘g’ and ‘h’. At each step it picks the node/cell having the lowest ‘f’, and process that node/cell.We define ‘g’ and ‘h’ as simply as possible belowg = the movement cost to move from the starting point to a given square on the grid, following the path generated to get there. h = the estimated movement cost to move from that given square on the grid to the final destination. This is often referred to as the heuristic, which is nothing but a kind of smart guess. We really don’t know the actual distance until we find the path, because all sorts of things can be in the way (walls, water, etc.). There can be many ways to calculate this ‘h’ which are discussed in the later sections. Algorithm We create two lists – Open List and Closed List (just like Dijkstra Algorithm) // A* Search Algorithm 1. Initialize the open list 2. Initialize the closed list put the starting node on the open list (you can leave its f at zero) 3. while the open list is not empty a) find the node with the least f on the open list, call it "q" b) pop q off the open list c) generate q's 8 successors and set their parents to q d) for each successor i) if successor is the goal, stop search ii) else, compute both g and h for successor successor.g = q.g + distance between successor and q successor.h = distance from goal to successor (This can be done using many ways, we will discuss three heuristics- Manhattan, Diagonal and Euclidean Heuristics) successor.f = successor.g + successor.h iii) if a node with the same position as successor is in the OPEN list which has a lower f than successor, skip this successor iV) if a node with the same position as successor is in the CLOSED list which has a lower f than successor, skip this successor otherwise, add the node to the open list end (for loop) e) push q on the closed list end (while loop) So suppose as in the below figure if we want to reach the target cell from the source cell, then the A* Search algorithm would follow path as shown below. Note that the below figure is made by considering Euclidean Distance as a heuristics. Heuristics We can calculate g but how to calculate h ?We can do things. A) Either calculate the exact value of h (which is certainly time consuming). OR B ) Approximate the value of h using some heuristics (less time consuming).We will discuss both of the methods.A) Exact Heuristics –We can find exact values of h, but that is generally very time consuming.Below are some of the methods to calculate the exact value of h.1) Pre-compute the distance between each pair of cells before running the A* Search Algorithm.2) If there are no blocked cells/obstacles then we can just find the exact value of h without any pre-computation using the distance formula/Euclidean Distance B) Approximation Heuristics – There are generally three approximation heuristics to calculate h – 1) Manhattan Distance – It is nothing but the sum of absolute values of differences in the goal’s x and y coordinates and the current cell’s x and y coordinates respectively, i.e., h = abs (current_cell.x – goal.x) + abs (current_cell.y – goal.y) When to use this heuristic? – When we are allowed to move only in four directions only (right, left, top, bottom) The Manhattan Distance Heuristics is shown by the below figure (assume red spot as source cell and green spot as target cell). 2) Diagonal Distance- It is nothing but the maximum of absolute values of differences in the goal’s x and y coordinates and the current cell’s x and y coordinates respectively, i.e., dx = abs(current_cell.x – goal.x) dy = abs(current_cell.y – goal.y) h = D * (dx + dy) + (D2 - 2 * D) * min(dx, dy) where D is length of each node(usually = 1) and D2 is diagonal distance between each node (usually = sqrt(2) ). When to use this heuristic? – When we are allowed to move in eight directions only (similar to a move of a King in Chess) The Diagonal Distance Heuristics is shown by the below figure (assume red spot as source cell and green spot as target cell). 3) Euclidean Distance- As it is clear from its name, it is nothing but the distance between the current cell and the goal cell using the distance formula h = sqrt ( (current_cell.x – goal.x)2 + (current_cell.y – goal.y)2 ) When to use this heuristic? – When we are allowed to move in any directions. The Euclidean Distance Heuristics is shown by the below figure (assume red spot as source cell and green spot as target cell). Relation (Similarity and Differences) with other algorithms- Dijkstra is a special case of A* Search Algorithm, where h = 0 for all nodes. Implementation We can use any data structure to implement open list and closed list but for best performance, we use a set data structure of C++ STL(implemented as Red-Black Tree) and a boolean hash table for a closed list.The implementations are similar to Dijkstra’s algorithm. If we use a Fibonacci heap to implement the open list instead of a binary heap/self-balancing tree, then the performance will become better (as Fibonacci heap takes O(1) average time to insert into open list and to decrease key) Also to reduce the time taken to calculate g, we will use dynamic programming. C++ C++14 // A C++ Program to implement A* Search Algorithm#include <bits/stdc++.h>using namespace std; #define ROW 9#define COL 10 // Creating a shortcut for int, int pair typetypedef pair<int, int> Pair; // Creating a shortcut for pair<int, pair<int, int>> typetypedef pair<double, pair<int, int> > pPair; // A structure to hold the necessary parametersstruct cell { // Row and Column index of its parent // Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1 int parent_i, parent_j; // f = g + h double f, g, h;}; // A Utility Function to check whether given cell (row, col)// is a valid cell or not.bool isValid(int row, int col){ // Returns true if row number and column number // is in range return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL);} // A Utility Function to check whether the given cell is// blocked or notbool isUnBlocked(int grid[][COL], int row, int col){ // Returns true if the cell is not blocked else false if (grid[row][col] == 1) return (true); else return (false);} // A Utility Function to check whether destination cell has// been reached or notbool isDestination(int row, int col, Pair dest){ if (row == dest.first && col == dest.second) return (true); else return (false);} // A Utility Function to calculate the 'h' heuristics.double calculateHValue(int row, int col, Pair dest){ // Return using the distance formula return ((double)sqrt( (row - dest.first) * (row - dest.first) + (col - dest.second) * (col - dest.second)));} // A Utility Function to trace the path from the source// to destinationvoid tracePath(cell cellDetails[][COL], Pair dest){ printf("\nThe Path is "); int row = dest.first; int col = dest.second; stack<Pair> Path; while (!(cellDetails[row][col].parent_i == row && cellDetails[row][col].parent_j == col)) { Path.push(make_pair(row, col)); int temp_row = cellDetails[row][col].parent_i; int temp_col = cellDetails[row][col].parent_j; row = temp_row; col = temp_col; } Path.push(make_pair(row, col)); while (!Path.empty()) { pair<int, int> p = Path.top(); Path.pop(); printf("-> (%d,%d) ", p.first, p.second); } return;} // A Function to find the shortest path between// a given source cell to a destination cell according// to A* Search Algorithmvoid aStarSearch(int grid[][COL], Pair src, Pair dest){ // If the source is out of range if (isValid(src.first, src.second) == false) { printf("Source is invalid\n"); return; } // If the destination is out of range if (isValid(dest.first, dest.second) == false) { printf("Destination is invalid\n"); return; } // Either the source or the destination is blocked if (isUnBlocked(grid, src.first, src.second) == false || isUnBlocked(grid, dest.first, dest.second) == false) { printf("Source or the destination is blocked\n"); return; } // If the destination cell is the same as source cell if (isDestination(src.first, src.second, dest) == true) { printf("We are already at the destination\n"); return; } // Create a closed list and initialise it to false which // means that no cell has been included yet This closed // list is implemented as a boolean 2D array bool closedList[ROW][COL]; memset(closedList, false, sizeof(closedList)); // Declare a 2D array of structure to hold the details // of that cell cell cellDetails[ROW][COL]; int i, j; for (i = 0; i < ROW; i++) { for (j = 0; j < COL; j++) { cellDetails[i][j].f = FLT_MAX; cellDetails[i][j].g = FLT_MAX; cellDetails[i][j].h = FLT_MAX; cellDetails[i][j].parent_i = -1; cellDetails[i][j].parent_j = -1; } } // Initialising the parameters of the starting node i = src.first, j = src.second; cellDetails[i][j].f = 0.0; cellDetails[i][j].g = 0.0; cellDetails[i][j].h = 0.0; cellDetails[i][j].parent_i = i; cellDetails[i][j].parent_j = j; /* Create an open list having information as- <f, <i, j>> where f = g + h, and i, j are the row and column index of that cell Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1 This open list is implemented as a set of pair of pair.*/ set<pPair> openList; // Put the starting cell on the open list and set its // 'f' as 0 openList.insert(make_pair(0.0, make_pair(i, j))); // We set this boolean value as false as initially // the destination is not reached. bool foundDest = false; while (!openList.empty()) { pPair p = *openList.begin(); // Remove this vertex from the open list openList.erase(openList.begin()); // Add this vertex to the closed list i = p.second.first; j = p.second.second; closedList[i][j] = true; /* Generating all the 8 successor of this cell N.W N N.E \ | / \ | / W----Cell----E / | \ / | \ S.W S S.E Cell-->Popped Cell (i, j) N --> North (i-1, j) S --> South (i+1, j) E --> East (i, j+1) W --> West (i, j-1) N.E--> North-East (i-1, j+1) N.W--> North-West (i-1, j-1) S.E--> South-East (i+1, j+1) S.W--> South-West (i+1, j-1)*/ // To store the 'g', 'h' and 'f' of the 8 successors double gNew, hNew, fNew; //----------- 1st Successor (North) ------------ // Only process this cell if this is a valid one if (isValid(i - 1, j) == true) { // If the destination cell is the same as the // current successor if (isDestination(i - 1, j, dest) == true) { // Set the Parent of the destination cell cellDetails[i - 1][j].parent_i = i; cellDetails[i - 1][j].parent_j = j; printf("The destination cell is found\n"); tracePath(cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i - 1][j] == false && isUnBlocked(grid, i - 1, j) == true) { gNew = cellDetails[i][j].g + 1.0; hNew = calculateHValue(i - 1, j, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is // better, using 'f' cost as the measure. if (cellDetails[i - 1][j].f == FLT_MAX || cellDetails[i - 1][j].f > fNew) { openList.insert(make_pair( fNew, make_pair(i - 1, j))); // Update the details of this cell cellDetails[i - 1][j].f = fNew; cellDetails[i - 1][j].g = gNew; cellDetails[i - 1][j].h = hNew; cellDetails[i - 1][j].parent_i = i; cellDetails[i - 1][j].parent_j = j; } } } //----------- 2nd Successor (South) ------------ // Only process this cell if this is a valid one if (isValid(i + 1, j) == true) { // If the destination cell is the same as the // current successor if (isDestination(i + 1, j, dest) == true) { // Set the Parent of the destination cell cellDetails[i + 1][j].parent_i = i; cellDetails[i + 1][j].parent_j = j; printf("The destination cell is found\n"); tracePath(cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i + 1][j] == false && isUnBlocked(grid, i + 1, j) == true) { gNew = cellDetails[i][j].g + 1.0; hNew = calculateHValue(i + 1, j, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is // better, using 'f' cost as the measure. if (cellDetails[i + 1][j].f == FLT_MAX || cellDetails[i + 1][j].f > fNew) { openList.insert(make_pair( fNew, make_pair(i + 1, j))); // Update the details of this cell cellDetails[i + 1][j].f = fNew; cellDetails[i + 1][j].g = gNew; cellDetails[i + 1][j].h = hNew; cellDetails[i + 1][j].parent_i = i; cellDetails[i + 1][j].parent_j = j; } } } //----------- 3rd Successor (East) ------------ // Only process this cell if this is a valid one if (isValid(i, j + 1) == true) { // If the destination cell is the same as the // current successor if (isDestination(i, j + 1, dest) == true) { // Set the Parent of the destination cell cellDetails[i][j + 1].parent_i = i; cellDetails[i][j + 1].parent_j = j; printf("The destination cell is found\n"); tracePath(cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i][j + 1] == false && isUnBlocked(grid, i, j + 1) == true) { gNew = cellDetails[i][j].g + 1.0; hNew = calculateHValue(i, j + 1, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is // better, using 'f' cost as the measure. if (cellDetails[i][j + 1].f == FLT_MAX || cellDetails[i][j + 1].f > fNew) { openList.insert(make_pair( fNew, make_pair(i, j + 1))); // Update the details of this cell cellDetails[i][j + 1].f = fNew; cellDetails[i][j + 1].g = gNew; cellDetails[i][j + 1].h = hNew; cellDetails[i][j + 1].parent_i = i; cellDetails[i][j + 1].parent_j = j; } } } //----------- 4th Successor (West) ------------ // Only process this cell if this is a valid one if (isValid(i, j - 1) == true) { // If the destination cell is the same as the // current successor if (isDestination(i, j - 1, dest) == true) { // Set the Parent of the destination cell cellDetails[i][j - 1].parent_i = i; cellDetails[i][j - 1].parent_j = j; printf("The destination cell is found\n"); tracePath(cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i][j - 1] == false && isUnBlocked(grid, i, j - 1) == true) { gNew = cellDetails[i][j].g + 1.0; hNew = calculateHValue(i, j - 1, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is // better, using 'f' cost as the measure. if (cellDetails[i][j - 1].f == FLT_MAX || cellDetails[i][j - 1].f > fNew) { openList.insert(make_pair( fNew, make_pair(i, j - 1))); // Update the details of this cell cellDetails[i][j - 1].f = fNew; cellDetails[i][j - 1].g = gNew; cellDetails[i][j - 1].h = hNew; cellDetails[i][j - 1].parent_i = i; cellDetails[i][j - 1].parent_j = j; } } } //----------- 5th Successor (North-East) //------------ // Only process this cell if this is a valid one if (isValid(i - 1, j + 1) == true) { // If the destination cell is the same as the // current successor if (isDestination(i - 1, j + 1, dest) == true) { // Set the Parent of the destination cell cellDetails[i - 1][j + 1].parent_i = i; cellDetails[i - 1][j + 1].parent_j = j; printf("The destination cell is found\n"); tracePath(cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i - 1][j + 1] == false && isUnBlocked(grid, i - 1, j + 1) == true) { gNew = cellDetails[i][j].g + 1.414; hNew = calculateHValue(i - 1, j + 1, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is // better, using 'f' cost as the measure. if (cellDetails[i - 1][j + 1].f == FLT_MAX || cellDetails[i - 1][j + 1].f > fNew) { openList.insert(make_pair( fNew, make_pair(i - 1, j + 1))); // Update the details of this cell cellDetails[i - 1][j + 1].f = fNew; cellDetails[i - 1][j + 1].g = gNew; cellDetails[i - 1][j + 1].h = hNew; cellDetails[i - 1][j + 1].parent_i = i; cellDetails[i - 1][j + 1].parent_j = j; } } } //----------- 6th Successor (North-West) //------------ // Only process this cell if this is a valid one if (isValid(i - 1, j - 1) == true) { // If the destination cell is the same as the // current successor if (isDestination(i - 1, j - 1, dest) == true) { // Set the Parent of the destination cell cellDetails[i - 1][j - 1].parent_i = i; cellDetails[i - 1][j - 1].parent_j = j; printf("The destination cell is found\n"); tracePath(cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i - 1][j - 1] == false && isUnBlocked(grid, i - 1, j - 1) == true) { gNew = cellDetails[i][j].g + 1.414; hNew = calculateHValue(i - 1, j - 1, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is // better, using 'f' cost as the measure. if (cellDetails[i - 1][j - 1].f == FLT_MAX || cellDetails[i - 1][j - 1].f > fNew) { openList.insert(make_pair( fNew, make_pair(i - 1, j - 1))); // Update the details of this cell cellDetails[i - 1][j - 1].f = fNew; cellDetails[i - 1][j - 1].g = gNew; cellDetails[i - 1][j - 1].h = hNew; cellDetails[i - 1][j - 1].parent_i = i; cellDetails[i - 1][j - 1].parent_j = j; } } } //----------- 7th Successor (South-East) //------------ // Only process this cell if this is a valid one if (isValid(i + 1, j + 1) == true) { // If the destination cell is the same as the // current successor if (isDestination(i + 1, j + 1, dest) == true) { // Set the Parent of the destination cell cellDetails[i + 1][j + 1].parent_i = i; cellDetails[i + 1][j + 1].parent_j = j; printf("The destination cell is found\n"); tracePath(cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i + 1][j + 1] == false && isUnBlocked(grid, i + 1, j + 1) == true) { gNew = cellDetails[i][j].g + 1.414; hNew = calculateHValue(i + 1, j + 1, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is // better, using 'f' cost as the measure. if (cellDetails[i + 1][j + 1].f == FLT_MAX || cellDetails[i + 1][j + 1].f > fNew) { openList.insert(make_pair( fNew, make_pair(i + 1, j + 1))); // Update the details of this cell cellDetails[i + 1][j + 1].f = fNew; cellDetails[i + 1][j + 1].g = gNew; cellDetails[i + 1][j + 1].h = hNew; cellDetails[i + 1][j + 1].parent_i = i; cellDetails[i + 1][j + 1].parent_j = j; } } } //----------- 8th Successor (South-West) //------------ // Only process this cell if this is a valid one if (isValid(i + 1, j - 1) == true) { // If the destination cell is the same as the // current successor if (isDestination(i + 1, j - 1, dest) == true) { // Set the Parent of the destination cell cellDetails[i + 1][j - 1].parent_i = i; cellDetails[i + 1][j - 1].parent_j = j; printf("The destination cell is found\n"); tracePath(cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i + 1][j - 1] == false && isUnBlocked(grid, i + 1, j - 1) == true) { gNew = cellDetails[i][j].g + 1.414; hNew = calculateHValue(i + 1, j - 1, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is // better, using 'f' cost as the measure. if (cellDetails[i + 1][j - 1].f == FLT_MAX || cellDetails[i + 1][j - 1].f > fNew) { openList.insert(make_pair( fNew, make_pair(i + 1, j - 1))); // Update the details of this cell cellDetails[i + 1][j - 1].f = fNew; cellDetails[i + 1][j - 1].g = gNew; cellDetails[i + 1][j - 1].h = hNew; cellDetails[i + 1][j - 1].parent_i = i; cellDetails[i + 1][j - 1].parent_j = j; } } } } // When the destination cell is not found and the open // list is empty, then we conclude that we failed to // reach the destination cell. This may happen when the // there is no way to destination cell (due to // blockages) if (foundDest == false) printf("Failed to find the Destination Cell\n"); return;} // Driver program to test above functionint main(){ /* Description of the Grid- 1--> The cell is not blocked 0--> The cell is blocked */ int grid[ROW][COL] = { { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 }, { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, { 0, 0, 1, 0, 1, 0, 0, 0, 0, 1 }, { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 }, { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 }, { 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 }, { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 } }; // Source is the left-most bottom-most corner Pair src = make_pair(8, 0); // Destination is the left-most top-most corner Pair dest = make_pair(0, 0); aStarSearch(grid, src, dest); return (0);} // A C++ Program to implement A* Search Algorithm#include "math.h"#include <array>#include <chrono>#include <cstring>#include <iostream>#include <queue>#include <set>#include <stack>#include <tuple>using namespace std; // Creating a shortcut for int, int pair typetypedef pair<int, int> Pair;// Creating a shortcut for tuple<int, int, int> typetypedef tuple<double, int, int> Tuple; // A structure to hold the necessary parametersstruct cell { // Row and Column index of its parent Pair parent; // f = g + h double f, g, h; cell() : parent(-1, -1) , f(-1) , g(-1) , h(-1) { }}; // A Utility Function to check whether given cell (row, col)// is a valid cell or not.template <size_t ROW, size_t COL>bool isValid(const array<array<int, COL>, ROW>& grid, const Pair& point){ // Returns true if row number and column number is in // range if (ROW > 0 && COL > 0) return (point.first >= 0) && (point.first < ROW) && (point.second >= 0) && (point.second < COL); return false;} // A Utility Function to check whether the given cell is// blocked or nottemplate <size_t ROW, size_t COL>bool isUnBlocked(const array<array<int, COL>, ROW>& grid, const Pair& point){ // Returns true if the cell is not blocked else false return isValid(grid, point) && grid[point.first][point.second] == 1;} // A Utility Function to check whether destination cell has// been reached or notbool isDestination(const Pair& position, const Pair& dest){ return position == dest;} // A Utility Function to calculate the 'h' heuristics.double calculateHValue(const Pair& src, const Pair& dest){ // h is estimated with the two points distance formula return sqrt(pow((src.first - dest.first), 2.0) + pow((src.second - dest.second), 2.0));} // A Utility Function to trace the path from the source to// destinationtemplate <size_t ROW, size_t COL>void tracePath( const array<array<cell, COL>, ROW>& cellDetails, const Pair& dest){ printf("\nThe Path is "); stack<Pair> Path; int row = dest.second; int col = dest.second; Pair next_node = cellDetails[row][col].parent; do { Path.push(next_node); next_node = cellDetails[row][col].parent; row = next_node.first; col = next_node.second; } while (cellDetails[row][col].parent != next_node); Path.emplace(row, col); while (!Path.empty()) { Pair p = Path.top(); Path.pop(); printf("-> (%d,%d) ", p.first, p.second); }} // A Function to find the shortest path between a given// source cell to a destination cell according to A* Search// Algorithmtemplate <size_t ROW, size_t COL>void aStarSearch(const array<array<int, COL>, ROW>& grid, const Pair& src, const Pair& dest){ // If the source is out of range if (!isValid(grid, src)) { printf("Source is invalid\n"); return; } // If the destination is out of range if (!isValid(grid, dest)) { printf("Destination is invalid\n"); return; } // Either the source or the destination is blocked if (!isUnBlocked(grid, src) || !isUnBlocked(grid, dest)) { printf("Source or the destination is blocked\n"); return; } // If the destination cell is the same as source cell if (isDestination(src, dest)) { printf("We are already at the destination\n"); return; } // Create a closed list and initialise it to false which // means that no cell has been included yet This closed // list is implemented as a boolean 2D array bool closedList[ROW][COL]; memset(closedList, false, sizeof(closedList)); // Declare a 2D array of structure to hold the details // of that cell array<array<cell, COL>, ROW> cellDetails; int i, j; // Initialising the parameters of the starting node i = src.first, j = src.second; cellDetails[i][j].f = 0.0; cellDetails[i][j].g = 0.0; cellDetails[i][j].h = 0.0; cellDetails[i][j].parent = { i, j }; /* Create an open list having information as- <f, <i, j>> where f = g + h, and i, j are the row and column index of that cell Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1 This open list is implemented as a set of tuple.*/ std::priority_queue<Tuple, std::vector<Tuple>, std::greater<Tuple> > openList; // Put the starting cell on the open list and set its // 'f' as 0 openList.emplace(0.0, i, j); // We set this boolean value as false as initially // the destination is not reached. while (!openList.empty()) { const Tuple& p = openList.top(); // Add this vertex to the closed list i = get<1>(p); // second element of tuple j = get<2>(p); // third element of tuple // Remove this vertex from the open list openList.pop(); closedList[i][j] = true; /* Generating all the 8 successor of this cell N.W N N.E \ | / \ | / W----Cell----E / | \ / | \ S.W S S.E Cell-->Popped Cell (i, j) N --> North (i-1, j) S --> South (i+1, j) E --> East (i, j+1) W --> West (i, j-1) N.E--> North-East (i-1, j+1) N.W--> North-West (i-1, j-1) S.E--> South-East (i+1, j+1) S.W--> South-West (i+1, j-1) */ for (int add_x = -1; add_x <= 1; add_x++) { for (int add_y = -1; add_y <= 1; add_y++) { Pair neighbour(i + add_x, j + add_y); // Only process this cell if this is a valid // one if (isValid(grid, neighbour)) { // If the destination cell is the same // as the current successor if (isDestination( neighbour, dest)) { // Set the Parent of // the destination cell cellDetails[neighbour.first] [neighbour.second] .parent = { i, j }; printf("The destination cell is " "found\n"); tracePath(cellDetails, dest); return; } // If the successor is already on the // closed list or if it is blocked, then // ignore it. Else do the following else if (!closedList[neighbour.first] [neighbour.second] && isUnBlocked(grid, neighbour)) { double gNew, hNew, fNew; gNew = cellDetails[i][j].g + 1.0; hNew = calculateHValue(neighbour, dest); fNew = gNew + hNew; // If it isn’t on the open list, add // it to the open list. Make the // current square the parent of this // square. Record the f, g, and h // costs of the square cell // OR // If it is on the open list // already, check to see if this // path to that square is better, // using 'f' cost as the measure. if (cellDetails[neighbour.first] [neighbour.second] .f == -1 || cellDetails[neighbour.first] [neighbour.second] .f > fNew) { openList.emplace( fNew, neighbour.first, neighbour.second); // Update the details of this // cell cellDetails[neighbour.first] [neighbour.second] .g = gNew; cellDetails[neighbour.first] [neighbour.second] .h = hNew; cellDetails[neighbour.first] [neighbour.second] .f = fNew; cellDetails[neighbour.first] [neighbour.second] .parent = { i, j }; } } } } } } // When the destination cell is not found and the open // list is empty, then we conclude that we failed to // reach the destination cell. This may happen when the // there is no way to destination cell (due to // blockages) printf("Failed to find the Destination Cell\n");} // Driver program to test above functionint main(){ /* Description of the Grid- 1--> The cell is not blocked 0--> The cell is blocked */ array<array<int, 10>, 9> grid{ { { { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 } }, { { 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 } }, { { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 } }, { { 0, 0, 1, 0, 1, 0, 0, 0, 0, 1 } }, { { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 } }, { { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 } }, { { 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 } }, { { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 } }, { { 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 } } } }; // Source is the left-most bottom-most corner Pair src(8, 0); // Destination is the left-most top-most corner Pair dest(0, 0); aStarSearch(grid, src, dest); return 0;} Limitations Although being the best path finding algorithm around, A* Search Algorithm doesn’t produce the shortest path always, as it relies heavily on heuristics / approximations to calculate – h Applications This is the most interesting part of A* Search Algorithm. They are used in games! But how?Ever played Tower Defense Games ? Tower defense is a type of strategy video game where the goal is to defend a player’s territories or possessions by obstructing enemy attackers, usually achieved by placing defensive structures on or along their path of attack. A* Search Algorithm is often used to find the shortest path from one point to another point. You can use this for each enemy to find a path to the goal.One example of this is the very popular game- Warcraft III What if the search space is not a grid and is a graph ?The same rules applies there also. The example of grid is taken for the simplicity of understanding. So we can find the shortest path between the source node and the target node in a graph using this A* Search Algorithm, just like we did for a 2D Grid. Time Complexity Considering a graph, it may take us to travel all the edge to reach the destination cell from the source cell [For example, consider a graph where source and destination nodes are connected by a series of edges, like – 0(source) –>1 –> 2 –> 3 (target)So the worse case time complexity is O(E), where E is the number of edges in the graph Auxiliary Space In the worse case we can have all the edges inside the open list, so required auxiliary space in worst case is O(V), where V is the total number of vertices. Exercise to the Readers- Ever wondered how to make a game like- Pacman where there are many such obstacles. Can we use A* Search Algorithm to find the correct way ?Think about it as a fun exercise. Articles for interested readers In our program, the obstacles are fixed. What if the obstacles are moving ? Interested readers may see here an excellent discussion on this topic. Summary So when to use BFS over A*, when to use Dijkstra over A* to find the shortest paths ? We can summarise this as below-1) One source and One Destination- → Use A* Search Algorithm (For Unweighted as well as Weighted Graphs)2) One Source, All Destination – → Use BFS (For Unweighted Graphs) → Use Dijkstra (For Weighted Graphs without negative weights) → Use Bellman Ford (For Weighted Graphs with negative weights)3) Between every pair of nodes- → Floyd-Warshall → Johnson’s Algorithm Related Article: Best First Search (Informed Search) References- http://theory.stanford.edu/~amitp/GameProgramming/ https://en.wikipedia.org/wiki/A*_search_algorithm This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above VibhakarMohta federicolupo92 adnanirshad158 rjainbe19 saurabh1990aror gabaa406 surinderdawra388 avtarkumar719 as5853535 niccsacchi simmytarika5 Algorithms Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Introduction to Algorithms How to write a Pseudo Code? Playfair Cipher with Examples Recursive Practice Problems with Solutions Quick Sort vs Merge Sort Cyclomatic Complexity Rail Fence Cipher - Encryption and Decryption Converting Roman Numerals to Decimal lying between 1 to 3999
[ { "code": null, "e": 24329, "s": 24301, "text": "\n13 Apr, 2022" }, { "code": null, "e": 24608, "s": 24329, "text": "Motivation To approximate the shortest path in real-life situations, like- in maps, games where there can be many hindrances.We can consider a 2D Grid having several obstacles and we start from a source cell (colored red below) to reach towards a goal cell (colored green below)" }, { "code": null, "e": 24741, "s": 24608, "text": "What is A* Search Algorithm? A* Search algorithm is one of the best and popular technique used in path-finding and graph traversals." }, { "code": null, "e": 25170, "s": 24741, "text": "Why A* Search Algorithm? Informally speaking, A* Search algorithms, unlike other traversal techniques, it has “brains”. What it means is that it is really a smart algorithm which separates it from the other conventional algorithms. This fact is cleared in detail in below sections. And it is also worth mentioning that many games and web-based maps use this algorithm to find the shortest path very efficiently (approximation). " }, { "code": null, "e": 26262, "s": 25170, "text": "Explanation Consider a square grid having many obstacles and we are given a starting cell and a target cell. We want to reach the target cell (if possible) from the starting cell as quickly as possible. Here A* Search Algorithm comes to the rescue.What A* Search Algorithm does is that at each step it picks the node according to a value-‘f’ which is a parameter equal to the sum of two other parameters – ‘g’ and ‘h’. At each step it picks the node/cell having the lowest ‘f’, and process that node/cell.We define ‘g’ and ‘h’ as simply as possible belowg = the movement cost to move from the starting point to a given square on the grid, following the path generated to get there. h = the estimated movement cost to move from that given square on the grid to the final destination. This is often referred to as the heuristic, which is nothing but a kind of smart guess. We really don’t know the actual distance until we find the path, because all sorts of things can be in the way (walls, water, etc.). There can be many ways to calculate this ‘h’ which are discussed in the later sections." }, { "code": null, "e": 26353, "s": 26262, "text": "Algorithm We create two lists – Open List and Closed List (just like Dijkstra Algorithm) " }, { "code": null, "e": 27697, "s": 26353, "text": "// A* Search Algorithm\n1. Initialize the open list\n2. Initialize the closed list\n put the starting node on the open \n list (you can leave its f at zero)\n\n3. while the open list is not empty\n a) find the node with the least f on \n the open list, call it \"q\"\n\n b) pop q off the open list\n \n c) generate q's 8 successors and set their \n parents to q\n \n d) for each successor\n i) if successor is the goal, stop search\n \n ii) else, compute both g and h for successor\n successor.g = q.g + distance between \n successor and q\n successor.h = distance from goal to \n successor (This can be done using many \n ways, we will discuss three heuristics- \n Manhattan, Diagonal and Euclidean \n Heuristics)\n \n successor.f = successor.g + successor.h\n\n iii) if a node with the same position as \n successor is in the OPEN list which has a \n lower f than successor, skip this successor\n\n iV) if a node with the same position as \n successor is in the CLOSED list which has\n a lower f than successor, skip this successor\n otherwise, add the node to the open list\n end (for loop)\n \n e) push q on the closed list\n end (while loop)" }, { "code": null, "e": 27938, "s": 27697, "text": "So suppose as in the below figure if we want to reach the target cell from the source cell, then the A* Search algorithm would follow path as shown below. Note that the below figure is made by considering Euclidean Distance as a heuristics." }, { "code": null, "e": 28627, "s": 27938, "text": "Heuristics We can calculate g but how to calculate h ?We can do things. A) Either calculate the exact value of h (which is certainly time consuming). OR B ) Approximate the value of h using some heuristics (less time consuming).We will discuss both of the methods.A) Exact Heuristics –We can find exact values of h, but that is generally very time consuming.Below are some of the methods to calculate the exact value of h.1) Pre-compute the distance between each pair of cells before running the A* Search Algorithm.2) If there are no blocked cells/obstacles then we can just find the exact value of h without any pre-computation using the distance formula/Euclidean Distance" }, { "code": null, "e": 28725, "s": 28627, "text": "B) Approximation Heuristics – There are generally three approximation heuristics to calculate h –" }, { "code": null, "e": 28751, "s": 28725, "text": "1) Manhattan Distance – " }, { "code": null, "e": 28908, "s": 28751, "text": "It is nothing but the sum of absolute values of differences in the goal’s x and y coordinates and the current cell’s x and y coordinates respectively, i.e.," }, { "code": null, "e": 28981, "s": 28908, "text": " h = abs (current_cell.x – goal.x) + \n abs (current_cell.y – goal.y)" }, { "code": null, "e": 29095, "s": 28981, "text": "When to use this heuristic? – When we are allowed to move only in four directions only (right, left, top, bottom)" }, { "code": null, "e": 29223, "s": 29095, "text": "The Manhattan Distance Heuristics is shown by the below figure (assume red spot as source cell and green spot as target cell). " }, { "code": null, "e": 29246, "s": 29223, "text": "2) Diagonal Distance- " }, { "code": null, "e": 29407, "s": 29246, "text": "It is nothing but the maximum of absolute values of differences in the goal’s x and y coordinates and the current cell’s x and y coordinates respectively, i.e.," }, { "code": null, "e": 29638, "s": 29407, "text": "dx = abs(current_cell.x – goal.x)\ndy = abs(current_cell.y – goal.y)\n \nh = D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)\n\nwhere D is length of each node(usually = 1) and D2 is diagonal distance between each node (usually = sqrt(2) ). " }, { "code": null, "e": 29760, "s": 29638, "text": "When to use this heuristic? – When we are allowed to move in eight directions only (similar to a move of a King in Chess)" }, { "code": null, "e": 29887, "s": 29760, "text": "The Diagonal Distance Heuristics is shown by the below figure (assume red spot as source cell and green spot as target cell). " }, { "code": null, "e": 29910, "s": 29887, "text": "3) Euclidean Distance-" }, { "code": null, "e": 30041, "s": 29910, "text": "As it is clear from its name, it is nothing but the distance between the current cell and the goal cell using the distance formula" }, { "code": null, "e": 30124, "s": 30041, "text": " h = sqrt ( (current_cell.x – goal.x)2 + \n (current_cell.y – goal.y)2 )" }, { "code": null, "e": 30201, "s": 30124, "text": "When to use this heuristic? – When we are allowed to move in any directions." }, { "code": null, "e": 30328, "s": 30201, "text": "The Euclidean Distance Heuristics is shown by the below figure (assume red spot as source cell and green spot as target cell)." }, { "code": null, "e": 30467, "s": 30328, "text": "Relation (Similarity and Differences) with other algorithms- Dijkstra is a special case of A* Search Algorithm, where h = 0 for all nodes." }, { "code": null, "e": 30976, "s": 30467, "text": "Implementation We can use any data structure to implement open list and closed list but for best performance, we use a set data structure of C++ STL(implemented as Red-Black Tree) and a boolean hash table for a closed list.The implementations are similar to Dijkstra’s algorithm. If we use a Fibonacci heap to implement the open list instead of a binary heap/self-balancing tree, then the performance will become better (as Fibonacci heap takes O(1) average time to insert into open list and to decrease key)" }, { "code": null, "e": 31057, "s": 30976, "text": "Also to reduce the time taken to calculate g, we will use dynamic programming. " }, { "code": null, "e": 31061, "s": 31057, "text": "C++" }, { "code": null, "e": 31067, "s": 31061, "text": "C++14" }, { "code": "// A C++ Program to implement A* Search Algorithm#include <bits/stdc++.h>using namespace std; #define ROW 9#define COL 10 // Creating a shortcut for int, int pair typetypedef pair<int, int> Pair; // Creating a shortcut for pair<int, pair<int, int>> typetypedef pair<double, pair<int, int> > pPair; // A structure to hold the necessary parametersstruct cell { // Row and Column index of its parent // Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1 int parent_i, parent_j; // f = g + h double f, g, h;}; // A Utility Function to check whether given cell (row, col)// is a valid cell or not.bool isValid(int row, int col){ // Returns true if row number and column number // is in range return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL);} // A Utility Function to check whether the given cell is// blocked or notbool isUnBlocked(int grid[][COL], int row, int col){ // Returns true if the cell is not blocked else false if (grid[row][col] == 1) return (true); else return (false);} // A Utility Function to check whether destination cell has// been reached or notbool isDestination(int row, int col, Pair dest){ if (row == dest.first && col == dest.second) return (true); else return (false);} // A Utility Function to calculate the 'h' heuristics.double calculateHValue(int row, int col, Pair dest){ // Return using the distance formula return ((double)sqrt( (row - dest.first) * (row - dest.first) + (col - dest.second) * (col - dest.second)));} // A Utility Function to trace the path from the source// to destinationvoid tracePath(cell cellDetails[][COL], Pair dest){ printf(\"\\nThe Path is \"); int row = dest.first; int col = dest.second; stack<Pair> Path; while (!(cellDetails[row][col].parent_i == row && cellDetails[row][col].parent_j == col)) { Path.push(make_pair(row, col)); int temp_row = cellDetails[row][col].parent_i; int temp_col = cellDetails[row][col].parent_j; row = temp_row; col = temp_col; } Path.push(make_pair(row, col)); while (!Path.empty()) { pair<int, int> p = Path.top(); Path.pop(); printf(\"-> (%d,%d) \", p.first, p.second); } return;} // A Function to find the shortest path between// a given source cell to a destination cell according// to A* Search Algorithmvoid aStarSearch(int grid[][COL], Pair src, Pair dest){ // If the source is out of range if (isValid(src.first, src.second) == false) { printf(\"Source is invalid\\n\"); return; } // If the destination is out of range if (isValid(dest.first, dest.second) == false) { printf(\"Destination is invalid\\n\"); return; } // Either the source or the destination is blocked if (isUnBlocked(grid, src.first, src.second) == false || isUnBlocked(grid, dest.first, dest.second) == false) { printf(\"Source or the destination is blocked\\n\"); return; } // If the destination cell is the same as source cell if (isDestination(src.first, src.second, dest) == true) { printf(\"We are already at the destination\\n\"); return; } // Create a closed list and initialise it to false which // means that no cell has been included yet This closed // list is implemented as a boolean 2D array bool closedList[ROW][COL]; memset(closedList, false, sizeof(closedList)); // Declare a 2D array of structure to hold the details // of that cell cell cellDetails[ROW][COL]; int i, j; for (i = 0; i < ROW; i++) { for (j = 0; j < COL; j++) { cellDetails[i][j].f = FLT_MAX; cellDetails[i][j].g = FLT_MAX; cellDetails[i][j].h = FLT_MAX; cellDetails[i][j].parent_i = -1; cellDetails[i][j].parent_j = -1; } } // Initialising the parameters of the starting node i = src.first, j = src.second; cellDetails[i][j].f = 0.0; cellDetails[i][j].g = 0.0; cellDetails[i][j].h = 0.0; cellDetails[i][j].parent_i = i; cellDetails[i][j].parent_j = j; /* Create an open list having information as- <f, <i, j>> where f = g + h, and i, j are the row and column index of that cell Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1 This open list is implemented as a set of pair of pair.*/ set<pPair> openList; // Put the starting cell on the open list and set its // 'f' as 0 openList.insert(make_pair(0.0, make_pair(i, j))); // We set this boolean value as false as initially // the destination is not reached. bool foundDest = false; while (!openList.empty()) { pPair p = *openList.begin(); // Remove this vertex from the open list openList.erase(openList.begin()); // Add this vertex to the closed list i = p.second.first; j = p.second.second; closedList[i][j] = true; /* Generating all the 8 successor of this cell N.W N N.E \\ | / \\ | / W----Cell----E / | \\ / | \\ S.W S S.E Cell-->Popped Cell (i, j) N --> North (i-1, j) S --> South (i+1, j) E --> East (i, j+1) W --> West (i, j-1) N.E--> North-East (i-1, j+1) N.W--> North-West (i-1, j-1) S.E--> South-East (i+1, j+1) S.W--> South-West (i+1, j-1)*/ // To store the 'g', 'h' and 'f' of the 8 successors double gNew, hNew, fNew; //----------- 1st Successor (North) ------------ // Only process this cell if this is a valid one if (isValid(i - 1, j) == true) { // If the destination cell is the same as the // current successor if (isDestination(i - 1, j, dest) == true) { // Set the Parent of the destination cell cellDetails[i - 1][j].parent_i = i; cellDetails[i - 1][j].parent_j = j; printf(\"The destination cell is found\\n\"); tracePath(cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i - 1][j] == false && isUnBlocked(grid, i - 1, j) == true) { gNew = cellDetails[i][j].g + 1.0; hNew = calculateHValue(i - 1, j, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is // better, using 'f' cost as the measure. if (cellDetails[i - 1][j].f == FLT_MAX || cellDetails[i - 1][j].f > fNew) { openList.insert(make_pair( fNew, make_pair(i - 1, j))); // Update the details of this cell cellDetails[i - 1][j].f = fNew; cellDetails[i - 1][j].g = gNew; cellDetails[i - 1][j].h = hNew; cellDetails[i - 1][j].parent_i = i; cellDetails[i - 1][j].parent_j = j; } } } //----------- 2nd Successor (South) ------------ // Only process this cell if this is a valid one if (isValid(i + 1, j) == true) { // If the destination cell is the same as the // current successor if (isDestination(i + 1, j, dest) == true) { // Set the Parent of the destination cell cellDetails[i + 1][j].parent_i = i; cellDetails[i + 1][j].parent_j = j; printf(\"The destination cell is found\\n\"); tracePath(cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i + 1][j] == false && isUnBlocked(grid, i + 1, j) == true) { gNew = cellDetails[i][j].g + 1.0; hNew = calculateHValue(i + 1, j, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is // better, using 'f' cost as the measure. if (cellDetails[i + 1][j].f == FLT_MAX || cellDetails[i + 1][j].f > fNew) { openList.insert(make_pair( fNew, make_pair(i + 1, j))); // Update the details of this cell cellDetails[i + 1][j].f = fNew; cellDetails[i + 1][j].g = gNew; cellDetails[i + 1][j].h = hNew; cellDetails[i + 1][j].parent_i = i; cellDetails[i + 1][j].parent_j = j; } } } //----------- 3rd Successor (East) ------------ // Only process this cell if this is a valid one if (isValid(i, j + 1) == true) { // If the destination cell is the same as the // current successor if (isDestination(i, j + 1, dest) == true) { // Set the Parent of the destination cell cellDetails[i][j + 1].parent_i = i; cellDetails[i][j + 1].parent_j = j; printf(\"The destination cell is found\\n\"); tracePath(cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i][j + 1] == false && isUnBlocked(grid, i, j + 1) == true) { gNew = cellDetails[i][j].g + 1.0; hNew = calculateHValue(i, j + 1, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is // better, using 'f' cost as the measure. if (cellDetails[i][j + 1].f == FLT_MAX || cellDetails[i][j + 1].f > fNew) { openList.insert(make_pair( fNew, make_pair(i, j + 1))); // Update the details of this cell cellDetails[i][j + 1].f = fNew; cellDetails[i][j + 1].g = gNew; cellDetails[i][j + 1].h = hNew; cellDetails[i][j + 1].parent_i = i; cellDetails[i][j + 1].parent_j = j; } } } //----------- 4th Successor (West) ------------ // Only process this cell if this is a valid one if (isValid(i, j - 1) == true) { // If the destination cell is the same as the // current successor if (isDestination(i, j - 1, dest) == true) { // Set the Parent of the destination cell cellDetails[i][j - 1].parent_i = i; cellDetails[i][j - 1].parent_j = j; printf(\"The destination cell is found\\n\"); tracePath(cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i][j - 1] == false && isUnBlocked(grid, i, j - 1) == true) { gNew = cellDetails[i][j].g + 1.0; hNew = calculateHValue(i, j - 1, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is // better, using 'f' cost as the measure. if (cellDetails[i][j - 1].f == FLT_MAX || cellDetails[i][j - 1].f > fNew) { openList.insert(make_pair( fNew, make_pair(i, j - 1))); // Update the details of this cell cellDetails[i][j - 1].f = fNew; cellDetails[i][j - 1].g = gNew; cellDetails[i][j - 1].h = hNew; cellDetails[i][j - 1].parent_i = i; cellDetails[i][j - 1].parent_j = j; } } } //----------- 5th Successor (North-East) //------------ // Only process this cell if this is a valid one if (isValid(i - 1, j + 1) == true) { // If the destination cell is the same as the // current successor if (isDestination(i - 1, j + 1, dest) == true) { // Set the Parent of the destination cell cellDetails[i - 1][j + 1].parent_i = i; cellDetails[i - 1][j + 1].parent_j = j; printf(\"The destination cell is found\\n\"); tracePath(cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i - 1][j + 1] == false && isUnBlocked(grid, i - 1, j + 1) == true) { gNew = cellDetails[i][j].g + 1.414; hNew = calculateHValue(i - 1, j + 1, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is // better, using 'f' cost as the measure. if (cellDetails[i - 1][j + 1].f == FLT_MAX || cellDetails[i - 1][j + 1].f > fNew) { openList.insert(make_pair( fNew, make_pair(i - 1, j + 1))); // Update the details of this cell cellDetails[i - 1][j + 1].f = fNew; cellDetails[i - 1][j + 1].g = gNew; cellDetails[i - 1][j + 1].h = hNew; cellDetails[i - 1][j + 1].parent_i = i; cellDetails[i - 1][j + 1].parent_j = j; } } } //----------- 6th Successor (North-West) //------------ // Only process this cell if this is a valid one if (isValid(i - 1, j - 1) == true) { // If the destination cell is the same as the // current successor if (isDestination(i - 1, j - 1, dest) == true) { // Set the Parent of the destination cell cellDetails[i - 1][j - 1].parent_i = i; cellDetails[i - 1][j - 1].parent_j = j; printf(\"The destination cell is found\\n\"); tracePath(cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i - 1][j - 1] == false && isUnBlocked(grid, i - 1, j - 1) == true) { gNew = cellDetails[i][j].g + 1.414; hNew = calculateHValue(i - 1, j - 1, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is // better, using 'f' cost as the measure. if (cellDetails[i - 1][j - 1].f == FLT_MAX || cellDetails[i - 1][j - 1].f > fNew) { openList.insert(make_pair( fNew, make_pair(i - 1, j - 1))); // Update the details of this cell cellDetails[i - 1][j - 1].f = fNew; cellDetails[i - 1][j - 1].g = gNew; cellDetails[i - 1][j - 1].h = hNew; cellDetails[i - 1][j - 1].parent_i = i; cellDetails[i - 1][j - 1].parent_j = j; } } } //----------- 7th Successor (South-East) //------------ // Only process this cell if this is a valid one if (isValid(i + 1, j + 1) == true) { // If the destination cell is the same as the // current successor if (isDestination(i + 1, j + 1, dest) == true) { // Set the Parent of the destination cell cellDetails[i + 1][j + 1].parent_i = i; cellDetails[i + 1][j + 1].parent_j = j; printf(\"The destination cell is found\\n\"); tracePath(cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i + 1][j + 1] == false && isUnBlocked(grid, i + 1, j + 1) == true) { gNew = cellDetails[i][j].g + 1.414; hNew = calculateHValue(i + 1, j + 1, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is // better, using 'f' cost as the measure. if (cellDetails[i + 1][j + 1].f == FLT_MAX || cellDetails[i + 1][j + 1].f > fNew) { openList.insert(make_pair( fNew, make_pair(i + 1, j + 1))); // Update the details of this cell cellDetails[i + 1][j + 1].f = fNew; cellDetails[i + 1][j + 1].g = gNew; cellDetails[i + 1][j + 1].h = hNew; cellDetails[i + 1][j + 1].parent_i = i; cellDetails[i + 1][j + 1].parent_j = j; } } } //----------- 8th Successor (South-West) //------------ // Only process this cell if this is a valid one if (isValid(i + 1, j - 1) == true) { // If the destination cell is the same as the // current successor if (isDestination(i + 1, j - 1, dest) == true) { // Set the Parent of the destination cell cellDetails[i + 1][j - 1].parent_i = i; cellDetails[i + 1][j - 1].parent_j = j; printf(\"The destination cell is found\\n\"); tracePath(cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i + 1][j - 1] == false && isUnBlocked(grid, i + 1, j - 1) == true) { gNew = cellDetails[i][j].g + 1.414; hNew = calculateHValue(i + 1, j - 1, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is // better, using 'f' cost as the measure. if (cellDetails[i + 1][j - 1].f == FLT_MAX || cellDetails[i + 1][j - 1].f > fNew) { openList.insert(make_pair( fNew, make_pair(i + 1, j - 1))); // Update the details of this cell cellDetails[i + 1][j - 1].f = fNew; cellDetails[i + 1][j - 1].g = gNew; cellDetails[i + 1][j - 1].h = hNew; cellDetails[i + 1][j - 1].parent_i = i; cellDetails[i + 1][j - 1].parent_j = j; } } } } // When the destination cell is not found and the open // list is empty, then we conclude that we failed to // reach the destination cell. This may happen when the // there is no way to destination cell (due to // blockages) if (foundDest == false) printf(\"Failed to find the Destination Cell\\n\"); return;} // Driver program to test above functionint main(){ /* Description of the Grid- 1--> The cell is not blocked 0--> The cell is blocked */ int grid[ROW][COL] = { { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 }, { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, { 0, 0, 1, 0, 1, 0, 0, 0, 0, 1 }, { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 }, { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 }, { 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 }, { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 } }; // Source is the left-most bottom-most corner Pair src = make_pair(8, 0); // Destination is the left-most top-most corner Pair dest = make_pair(0, 0); aStarSearch(grid, src, dest); return (0);}", "e": 54582, "s": 31067, "text": null }, { "code": "// A C++ Program to implement A* Search Algorithm#include \"math.h\"#include <array>#include <chrono>#include <cstring>#include <iostream>#include <queue>#include <set>#include <stack>#include <tuple>using namespace std; // Creating a shortcut for int, int pair typetypedef pair<int, int> Pair;// Creating a shortcut for tuple<int, int, int> typetypedef tuple<double, int, int> Tuple; // A structure to hold the necessary parametersstruct cell { // Row and Column index of its parent Pair parent; // f = g + h double f, g, h; cell() : parent(-1, -1) , f(-1) , g(-1) , h(-1) { }}; // A Utility Function to check whether given cell (row, col)// is a valid cell or not.template <size_t ROW, size_t COL>bool isValid(const array<array<int, COL>, ROW>& grid, const Pair& point){ // Returns true if row number and column number is in // range if (ROW > 0 && COL > 0) return (point.first >= 0) && (point.first < ROW) && (point.second >= 0) && (point.second < COL); return false;} // A Utility Function to check whether the given cell is// blocked or nottemplate <size_t ROW, size_t COL>bool isUnBlocked(const array<array<int, COL>, ROW>& grid, const Pair& point){ // Returns true if the cell is not blocked else false return isValid(grid, point) && grid[point.first][point.second] == 1;} // A Utility Function to check whether destination cell has// been reached or notbool isDestination(const Pair& position, const Pair& dest){ return position == dest;} // A Utility Function to calculate the 'h' heuristics.double calculateHValue(const Pair& src, const Pair& dest){ // h is estimated with the two points distance formula return sqrt(pow((src.first - dest.first), 2.0) + pow((src.second - dest.second), 2.0));} // A Utility Function to trace the path from the source to// destinationtemplate <size_t ROW, size_t COL>void tracePath( const array<array<cell, COL>, ROW>& cellDetails, const Pair& dest){ printf(\"\\nThe Path is \"); stack<Pair> Path; int row = dest.second; int col = dest.second; Pair next_node = cellDetails[row][col].parent; do { Path.push(next_node); next_node = cellDetails[row][col].parent; row = next_node.first; col = next_node.second; } while (cellDetails[row][col].parent != next_node); Path.emplace(row, col); while (!Path.empty()) { Pair p = Path.top(); Path.pop(); printf(\"-> (%d,%d) \", p.first, p.second); }} // A Function to find the shortest path between a given// source cell to a destination cell according to A* Search// Algorithmtemplate <size_t ROW, size_t COL>void aStarSearch(const array<array<int, COL>, ROW>& grid, const Pair& src, const Pair& dest){ // If the source is out of range if (!isValid(grid, src)) { printf(\"Source is invalid\\n\"); return; } // If the destination is out of range if (!isValid(grid, dest)) { printf(\"Destination is invalid\\n\"); return; } // Either the source or the destination is blocked if (!isUnBlocked(grid, src) || !isUnBlocked(grid, dest)) { printf(\"Source or the destination is blocked\\n\"); return; } // If the destination cell is the same as source cell if (isDestination(src, dest)) { printf(\"We are already at the destination\\n\"); return; } // Create a closed list and initialise it to false which // means that no cell has been included yet This closed // list is implemented as a boolean 2D array bool closedList[ROW][COL]; memset(closedList, false, sizeof(closedList)); // Declare a 2D array of structure to hold the details // of that cell array<array<cell, COL>, ROW> cellDetails; int i, j; // Initialising the parameters of the starting node i = src.first, j = src.second; cellDetails[i][j].f = 0.0; cellDetails[i][j].g = 0.0; cellDetails[i][j].h = 0.0; cellDetails[i][j].parent = { i, j }; /* Create an open list having information as- <f, <i, j>> where f = g + h, and i, j are the row and column index of that cell Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1 This open list is implemented as a set of tuple.*/ std::priority_queue<Tuple, std::vector<Tuple>, std::greater<Tuple> > openList; // Put the starting cell on the open list and set its // 'f' as 0 openList.emplace(0.0, i, j); // We set this boolean value as false as initially // the destination is not reached. while (!openList.empty()) { const Tuple& p = openList.top(); // Add this vertex to the closed list i = get<1>(p); // second element of tuple j = get<2>(p); // third element of tuple // Remove this vertex from the open list openList.pop(); closedList[i][j] = true; /* Generating all the 8 successor of this cell N.W N N.E \\ | / \\ | / W----Cell----E / | \\ / | \\ S.W S S.E Cell-->Popped Cell (i, j) N --> North (i-1, j) S --> South (i+1, j) E --> East (i, j+1) W --> West (i, j-1) N.E--> North-East (i-1, j+1) N.W--> North-West (i-1, j-1) S.E--> South-East (i+1, j+1) S.W--> South-West (i+1, j-1) */ for (int add_x = -1; add_x <= 1; add_x++) { for (int add_y = -1; add_y <= 1; add_y++) { Pair neighbour(i + add_x, j + add_y); // Only process this cell if this is a valid // one if (isValid(grid, neighbour)) { // If the destination cell is the same // as the current successor if (isDestination( neighbour, dest)) { // Set the Parent of // the destination cell cellDetails[neighbour.first] [neighbour.second] .parent = { i, j }; printf(\"The destination cell is \" \"found\\n\"); tracePath(cellDetails, dest); return; } // If the successor is already on the // closed list or if it is blocked, then // ignore it. Else do the following else if (!closedList[neighbour.first] [neighbour.second] && isUnBlocked(grid, neighbour)) { double gNew, hNew, fNew; gNew = cellDetails[i][j].g + 1.0; hNew = calculateHValue(neighbour, dest); fNew = gNew + hNew; // If it isn’t on the open list, add // it to the open list. Make the // current square the parent of this // square. Record the f, g, and h // costs of the square cell // OR // If it is on the open list // already, check to see if this // path to that square is better, // using 'f' cost as the measure. if (cellDetails[neighbour.first] [neighbour.second] .f == -1 || cellDetails[neighbour.first] [neighbour.second] .f > fNew) { openList.emplace( fNew, neighbour.first, neighbour.second); // Update the details of this // cell cellDetails[neighbour.first] [neighbour.second] .g = gNew; cellDetails[neighbour.first] [neighbour.second] .h = hNew; cellDetails[neighbour.first] [neighbour.second] .f = fNew; cellDetails[neighbour.first] [neighbour.second] .parent = { i, j }; } } } } } } // When the destination cell is not found and the open // list is empty, then we conclude that we failed to // reach the destination cell. This may happen when the // there is no way to destination cell (due to // blockages) printf(\"Failed to find the Destination Cell\\n\");} // Driver program to test above functionint main(){ /* Description of the Grid- 1--> The cell is not blocked 0--> The cell is blocked */ array<array<int, 10>, 9> grid{ { { { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 } }, { { 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 } }, { { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 } }, { { 0, 0, 1, 0, 1, 0, 0, 0, 0, 1 } }, { { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 } }, { { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 } }, { { 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 } }, { { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 } }, { { 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 } } } }; // Source is the left-most bottom-most corner Pair src(8, 0); // Destination is the left-most top-most corner Pair dest(0, 0); aStarSearch(grid, src, dest); return 0;}", "e": 65020, "s": 54582, "text": null }, { "code": null, "e": 65218, "s": 65020, "text": "Limitations Although being the best path finding algorithm around, A* Search Algorithm doesn’t produce the shortest path always, as it relies heavily on heuristics / approximations to calculate – h" }, { "code": null, "e": 65795, "s": 65218, "text": "Applications This is the most interesting part of A* Search Algorithm. They are used in games! But how?Ever played Tower Defense Games ? Tower defense is a type of strategy video game where the goal is to defend a player’s territories or possessions by obstructing enemy attackers, usually achieved by placing defensive structures on or along their path of attack. A* Search Algorithm is often used to find the shortest path from one point to another point. You can use this for each enemy to find a path to the goal.One example of this is the very popular game- Warcraft III " }, { "code": null, "e": 66103, "s": 65795, "text": "What if the search space is not a grid and is a graph ?The same rules applies there also. The example of grid is taken for the simplicity of understanding. So we can find the shortest path between the source node and the target node in a graph using this A* Search Algorithm, just like we did for a 2D Grid." }, { "code": null, "e": 66457, "s": 66103, "text": "Time Complexity Considering a graph, it may take us to travel all the edge to reach the destination cell from the source cell [For example, consider a graph where source and destination nodes are connected by a series of edges, like – 0(source) –>1 –> 2 –> 3 (target)So the worse case time complexity is O(E), where E is the number of edges in the graph" }, { "code": null, "e": 66631, "s": 66457, "text": "Auxiliary Space In the worse case we can have all the edges inside the open list, so required auxiliary space in worst case is O(V), where V is the total number of vertices." }, { "code": null, "e": 66829, "s": 66631, "text": "Exercise to the Readers- Ever wondered how to make a game like- Pacman where there are many such obstacles. Can we use A* Search Algorithm to find the correct way ?Think about it as a fun exercise." }, { "code": null, "e": 67008, "s": 66829, "text": "Articles for interested readers In our program, the obstacles are fixed. What if the obstacles are moving ? Interested readers may see here an excellent discussion on this topic." }, { "code": null, "e": 67499, "s": 67008, "text": "Summary So when to use BFS over A*, when to use Dijkstra over A* to find the shortest paths ? We can summarise this as below-1) One source and One Destination- → Use A* Search Algorithm (For Unweighted as well as Weighted Graphs)2) One Source, All Destination – → Use BFS (For Unweighted Graphs) → Use Dijkstra (For Weighted Graphs without negative weights) → Use Bellman Ford (For Weighted Graphs with negative weights)3) Between every pair of nodes- → Floyd-Warshall → Johnson’s Algorithm" }, { "code": null, "e": 67552, "s": 67499, "text": "Related Article: Best First Search (Informed Search)" }, { "code": null, "e": 67667, "s": 67552, "text": "References- http://theory.stanford.edu/~amitp/GameProgramming/ https://en.wikipedia.org/wiki/A*_search_algorithm " }, { "code": null, "e": 68061, "s": 67667, "text": "This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 68075, "s": 68061, "text": "VibhakarMohta" }, { "code": null, "e": 68090, "s": 68075, "text": "federicolupo92" }, { "code": null, "e": 68105, "s": 68090, "text": "adnanirshad158" }, { "code": null, "e": 68115, "s": 68105, "text": "rjainbe19" }, { "code": null, "e": 68131, "s": 68115, "text": "saurabh1990aror" }, { "code": null, "e": 68140, "s": 68131, "text": "gabaa406" }, { "code": null, "e": 68157, "s": 68140, "text": "surinderdawra388" }, { "code": null, "e": 68171, "s": 68157, "text": "avtarkumar719" }, { "code": null, "e": 68181, "s": 68171, "text": "as5853535" }, { "code": null, "e": 68192, "s": 68181, "text": "niccsacchi" }, { "code": null, "e": 68205, "s": 68192, "text": "simmytarika5" }, { "code": null, "e": 68216, "s": 68205, "text": "Algorithms" }, { "code": null, "e": 68227, "s": 68216, "text": "Algorithms" }, { "code": null, "e": 68325, "s": 68227, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 68334, "s": 68325, "text": "Comments" }, { "code": null, "e": 68347, "s": 68334, "text": "Old Comments" }, { "code": null, "e": 68396, "s": 68347, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 68421, "s": 68396, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 68448, "s": 68421, "text": "Introduction to Algorithms" }, { "code": null, "e": 68476, "s": 68448, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 68506, "s": 68476, "text": "Playfair Cipher with Examples" }, { "code": null, "e": 68549, "s": 68506, "text": "Recursive Practice Problems with Solutions" }, { "code": null, "e": 68574, "s": 68549, "text": "Quick Sort vs Merge Sort" }, { "code": null, "e": 68596, "s": 68574, "text": "Cyclomatic Complexity" }, { "code": null, "e": 68642, "s": 68596, "text": "Rail Fence Cipher - Encryption and Decryption" } ]
Faster Pandas with parallel processing: cuDF vs. Modin | by Déborah Mesquita | Towards Data Science
With Pandas, by default we can only use a single CPU core at a time. This is fine for small datasets, but when working with larger files this can create a bottleneck. It's possible to speed-up things by using Parallel processing, but if you never wrote a multithreaded program don't worry: you don't need to learn how to do it. Some new libraries that can do it for us. Today we're going to compare two of them: cuDF and Modin. They both use pandas-like APIs so we can start using them just by changing the import statement. cuDF is a GPU DataFrame library that provides a pandas-like API allowing us to accelerate our workflows without going into details of CUDA programming. The lib is part of RAPIDS, a suite of open source libraries that uses GPU-acceleration and integrates with popular data science libraries and workflows to speed up Machine Learning. The API is really similar to pandas, so in most cases, we just need to change one line of code to start using it: import cudf as pds = pd.Series([1,2,3,None,4])df = pd.DataFrame([('a', list(range(20))), ('b', list(reversed(range(20)))), ('c', list(range(20)))])df.head(2)df.sort_values(by='b')df['a']df.loc[2:5, ['a', 'b']]s = pd.Series([1,2,3,None,4])s.fillna(999)df = pd.read_csv('example_output/foo.csv')df.to_csv('example_output/foo.csv', index=False) cuDF is a single-GPU library. For Multi-GPU they use Dask and the dask-cudf package, which is able to scale cuDF across multiple GPUs on a single machine, or multiple GPUs across many machines in a cluster [cuDF Docs]. Modin also provides a pandas-like API that uses Ray or Dask to implement a high-performance distributed execution framework. With Modin you can use all of the CPU cores on your machine. It provides speed-ups of up to 4x on a laptop with 4 physical cores [Modin Docs]. We'll be using the Maingear VYBE PRO Data Science PC and I'm running the scripts using Jupyter. Here are the technical specs: 125gb RAM i9–7980XE, 36 cores 2x TITAN RTX 24GB The dataset used for the benchmarks was the brazilian 2018 higher education census. Let's go ahead and read a 3gb CSV file using Pandas, cuDF and Modin. We'll run it 30 times and get the mean values. Modin is the winner with less than 4s on average. It automatically distributes the computation across all of the system’s available CPU cores and we have 36 cores so maybe this is the reason why 🤔? In this benchmark we will fill the NaN values of the DataFrame. Modin is the winner for this benchmark too. And cuDF is the lib that takes more time to run on average. Let's group the rows to see how each library behaves. Here cuDF is the winner and Modin has the worst performance. To answer this question I think we have to consider the methods we most use in our workflows. In today's benchmark reading the file was much faster using Modin, but how many times do we need to use the read_csv() method in our ETL? By contrast, in theory, we would use the groupby() method more frequently, and in this case, the cuDF library had the best performance. Modin is pretty easy to install (we just need to use pip) and cuDF is harder (you'll need to update the NVIDIA drivers, install CUDA and then install cuDF using conda). Or you can skip all these steps and get a Data Science PC because it comes with all RAPIDS libraries and software fully installed. Also, both Modin and cuDF are still in the early stages and they don't have the complete coverage of the entire Pandas API yet. If you want to dive deep into cuDF, the 10 Minutes to cuDF and Dask-cuDF is a good place to start. For more info about Modin, this blog post explains more about parallelizing Pandas with Ray. If you want to dive even deeper there is the technical report on Scaling Interactive Data Science Transparently with Modin, which does a great job of explaining the technical architecture of Modin.
[ { "code": null, "e": 338, "s": 171, "text": "With Pandas, by default we can only use a single CPU core at a time. This is fine for small datasets, but when working with larger files this can create a bottleneck." }, { "code": null, "e": 696, "s": 338, "text": "It's possible to speed-up things by using Parallel processing, but if you never wrote a multithreaded program don't worry: you don't need to learn how to do it. Some new libraries that can do it for us. Today we're going to compare two of them: cuDF and Modin. They both use pandas-like APIs so we can start using them just by changing the import statement." }, { "code": null, "e": 1030, "s": 696, "text": "cuDF is a GPU DataFrame library that provides a pandas-like API allowing us to accelerate our workflows without going into details of CUDA programming. The lib is part of RAPIDS, a suite of open source libraries that uses GPU-acceleration and integrates with popular data science libraries and workflows to speed up Machine Learning." }, { "code": null, "e": 1144, "s": 1030, "text": "The API is really similar to pandas, so in most cases, we just need to change one line of code to start using it:" }, { "code": null, "e": 1526, "s": 1144, "text": "import cudf as pds = pd.Series([1,2,3,None,4])df = pd.DataFrame([('a', list(range(20))), ('b', list(reversed(range(20)))), ('c', list(range(20)))])df.head(2)df.sort_values(by='b')df['a']df.loc[2:5, ['a', 'b']]s = pd.Series([1,2,3,None,4])s.fillna(999)df = pd.read_csv('example_output/foo.csv')df.to_csv('example_output/foo.csv', index=False)" }, { "code": null, "e": 1745, "s": 1526, "text": "cuDF is a single-GPU library. For Multi-GPU they use Dask and the dask-cudf package, which is able to scale cuDF across multiple GPUs on a single machine, or multiple GPUs across many machines in a cluster [cuDF Docs]." }, { "code": null, "e": 2013, "s": 1745, "text": "Modin also provides a pandas-like API that uses Ray or Dask to implement a high-performance distributed execution framework. With Modin you can use all of the CPU cores on your machine. It provides speed-ups of up to 4x on a laptop with 4 physical cores [Modin Docs]." }, { "code": null, "e": 2139, "s": 2013, "text": "We'll be using the Maingear VYBE PRO Data Science PC and I'm running the scripts using Jupyter. Here are the technical specs:" }, { "code": null, "e": 2149, "s": 2139, "text": "125gb RAM" }, { "code": null, "e": 2169, "s": 2149, "text": "i9–7980XE, 36 cores" }, { "code": null, "e": 2187, "s": 2169, "text": "2x TITAN RTX 24GB" }, { "code": null, "e": 2271, "s": 2187, "text": "The dataset used for the benchmarks was the brazilian 2018 higher education census." }, { "code": null, "e": 2387, "s": 2271, "text": "Let's go ahead and read a 3gb CSV file using Pandas, cuDF and Modin. We'll run it 30 times and get the mean values." }, { "code": null, "e": 2585, "s": 2387, "text": "Modin is the winner with less than 4s on average. It automatically distributes the computation across all of the system’s available CPU cores and we have 36 cores so maybe this is the reason why 🤔?" }, { "code": null, "e": 2649, "s": 2585, "text": "In this benchmark we will fill the NaN values of the DataFrame." }, { "code": null, "e": 2753, "s": 2649, "text": "Modin is the winner for this benchmark too. And cuDF is the lib that takes more time to run on average." }, { "code": null, "e": 2807, "s": 2753, "text": "Let's group the rows to see how each library behaves." }, { "code": null, "e": 2868, "s": 2807, "text": "Here cuDF is the winner and Modin has the worst performance." }, { "code": null, "e": 3236, "s": 2868, "text": "To answer this question I think we have to consider the methods we most use in our workflows. In today's benchmark reading the file was much faster using Modin, but how many times do we need to use the read_csv() method in our ETL? By contrast, in theory, we would use the groupby() method more frequently, and in this case, the cuDF library had the best performance." }, { "code": null, "e": 3536, "s": 3236, "text": "Modin is pretty easy to install (we just need to use pip) and cuDF is harder (you'll need to update the NVIDIA drivers, install CUDA and then install cuDF using conda). Or you can skip all these steps and get a Data Science PC because it comes with all RAPIDS libraries and software fully installed." }, { "code": null, "e": 3664, "s": 3536, "text": "Also, both Modin and cuDF are still in the early stages and they don't have the complete coverage of the entire Pandas API yet." }, { "code": null, "e": 3763, "s": 3664, "text": "If you want to dive deep into cuDF, the 10 Minutes to cuDF and Dask-cuDF is a good place to start." } ]
Web Applications in Python. Getting Started with Django | by Sadrach Pierre, Ph.D. | Towards Data Science
Django is a python-based and open-sourced web framework that enables easy creation of database-driven websites. Some examples of sites that use Django include Instagram, Mozilla, and Bitbucket. In this post, we will walk through the steps of building a simple web application with Django. Documentation for Django can be found here. Let’s get started! The first thing we will need to do is make sure we have Django installed. To install Django, open up a terminal and execute the following pip command: pip install django We can then display the version of Django: python -m django --version The version I am using, at the time of this post, is 2.2.6. Now, let’s create a new directory on our desktop called ‘first_site’: mkdir first_sitecd first_site Let’s create our Django project in our ‘first_site’ folder: django-admin startproject first_site We can take a look at the structure of the files created and we see: We have a ‘manage.py’ file and a Django project directory, ‘first_site’. The ‘manage.py’ file is the command-line utility, which allows us to perform administrative tasks. The ‘__init__.py’ file is an empty file which tells python that our app is a python package. The ‘setting.py’ file allows us to change settings and configuration. The ‘url.py’ allows us to specify the mapping from urls to where we send the user. The ‘wsgi.py’ is used to allow communication between our server and web application. Now, let’s open the default website that comes with every new project. In our terminal we run: python manage.py runserver We should see the following: We see that our site is running. We can access our site at “http://127.0.0.1:8000/”, which corresponds to our local computer. We should see the following: This is the default website that Django created for us. The thinking behind the Django framework is that upon creating a website project, which is itself an application, we can create additional applications within our web app. You can think of each application as being its own section on our site, such as blog section, store section, etc. What’s nice about this framework is that upon creating an application you can reuse the code in subsequent web application. We will proceed by creating a blog app for our website. First, press ‘control’ + ‘C’ to kill the server running our web app: Next, to create our blog application we do the following: python manage.py startapp blog We can look at our project structure upon creation of our new app: Now, let’s go into our blog directory and open the ‘views.py’ file. We should see the following: from django.shortcuts import render# Create your views here. Let’s also import HttpResponse. Let’s also create a new function called ‘home’, which will allow us to handle traffic from the home page of our blog: from django.shortcuts import renderfrom django.http import HttpResponsedef home(request): return HttpResponse('<h1>Blog Home</h1>')# Create your views here. Next, we need to map our url pattern to this ‘view’ function. We go to our blog app directory and create a new file call ‘urls.py’ In this file we copy and paste the following: from django.urls import pathfrom . import viewsurlpatterns = [path('', views.home, name='blog-home'),] Now we have a url path for our blog home page mapped to our home function in the views file. For this to fully work, we need to modify our ‘urls.py’ module in main project directory, ‘first_site’. This module tells our website which urls will send us to our blog app. Let’s open the ‘urls.py’ file in our ‘first_site’ directory: from django.contrib import adminfrom django.urls import pathurlpatterns = [path('admin/', admin.site.urls),] We see we have one route that gets mapped to our admin site urls. We now need to specify the routes that get mapped to our blog urls. We need to import the include function from django.urls and add an additional path for our blog url: from django.contrib import adminfrom django.urls import path, includeurlpatterns = [path('admin/', admin.site.urls),path('blog/', include('blog.urls'))] Now let’s try to run the server. I often come across the following error upon attempting to run the server: To remedy this issue, execute: ps -ef | grep python and use the following to kill the appropriate process: kill -9 procees_id Now try running the server: python manage.py runserver If we type, http://127.0.0.1:8000/blog/ we should see the following: We can further edit the contents of blog home. Let’s add a quote from one of my favorite novels, Infinite Jest, by David Foster Wallace: from django.shortcuts import renderfrom django.http import HttpResponsedef home(request): return HttpResponse('<h1>Blog Home</h1><p1>Everybody is identical in their secret unspoken belief that way deep down they are different from everyone else.</p1>') We will also add an about page for our blog. In our ‘views.py’ module let’s define a function called ‘about’: from django.shortcuts import renderfrom django.http import HttpResponsedef home(request): return HttpResponse('<h1>Blog Home</h1><p1>Everybody is identical in their secret unspoken belief that way deep down they are different from everyone else.</p1>')def about(request): return HttpResponse('<h1>About Home</h1>') Now let’s add a new path for our about section in our ‘urls.py’ module in our blog app: from django.urls import pathfrom . import viewsurlpatterns = [path('', views.home, name='blog-home'),path('about/', views.about, name='blog-about')] Now if we go to http://127.0.0.1:8000/blog/about we should see: I’ll stop here but feel free to play around with the contents of the blog home and about sections on our web application. Further, a great resource for learning more about Django is Corey Schafer’s YouTube tutorials which can be found here. To summarize, in this post we went over how to build web applications and define url routes using Django. First, we discussed the specific files generated upon creating a new web application with Django. Then we created a blog application within our project and defined view functions, which allow us to specify what the user sees. We also showed how to add an additional url route and view within our blog application. I hope you found this post useful/interesting. Thank you for reading!
[ { "code": null, "e": 366, "s": 172, "text": "Django is a python-based and open-sourced web framework that enables easy creation of database-driven websites. Some examples of sites that use Django include Instagram, Mozilla, and Bitbucket." }, { "code": null, "e": 505, "s": 366, "text": "In this post, we will walk through the steps of building a simple web application with Django. Documentation for Django can be found here." }, { "code": null, "e": 524, "s": 505, "text": "Let’s get started!" }, { "code": null, "e": 675, "s": 524, "text": "The first thing we will need to do is make sure we have Django installed. To install Django, open up a terminal and execute the following pip command:" }, { "code": null, "e": 694, "s": 675, "text": "pip install django" }, { "code": null, "e": 737, "s": 694, "text": "We can then display the version of Django:" }, { "code": null, "e": 764, "s": 737, "text": "python -m django --version" }, { "code": null, "e": 894, "s": 764, "text": "The version I am using, at the time of this post, is 2.2.6. Now, let’s create a new directory on our desktop called ‘first_site’:" }, { "code": null, "e": 924, "s": 894, "text": "mkdir first_sitecd first_site" }, { "code": null, "e": 984, "s": 924, "text": "Let’s create our Django project in our ‘first_site’ folder:" }, { "code": null, "e": 1021, "s": 984, "text": "django-admin startproject first_site" }, { "code": null, "e": 1090, "s": 1021, "text": "We can take a look at the structure of the files created and we see:" }, { "code": null, "e": 1262, "s": 1090, "text": "We have a ‘manage.py’ file and a Django project directory, ‘first_site’. The ‘manage.py’ file is the command-line utility, which allows us to perform administrative tasks." }, { "code": null, "e": 1593, "s": 1262, "text": "The ‘__init__.py’ file is an empty file which tells python that our app is a python package. The ‘setting.py’ file allows us to change settings and configuration. The ‘url.py’ allows us to specify the mapping from urls to where we send the user. The ‘wsgi.py’ is used to allow communication between our server and web application." }, { "code": null, "e": 1688, "s": 1593, "text": "Now, let’s open the default website that comes with every new project. In our terminal we run:" }, { "code": null, "e": 1715, "s": 1688, "text": "python manage.py runserver" }, { "code": null, "e": 1744, "s": 1715, "text": "We should see the following:" }, { "code": null, "e": 1899, "s": 1744, "text": "We see that our site is running. We can access our site at “http://127.0.0.1:8000/”, which corresponds to our local computer. We should see the following:" }, { "code": null, "e": 2365, "s": 1899, "text": "This is the default website that Django created for us. The thinking behind the Django framework is that upon creating a website project, which is itself an application, we can create additional applications within our web app. You can think of each application as being its own section on our site, such as blog section, store section, etc. What’s nice about this framework is that upon creating an application you can reuse the code in subsequent web application." }, { "code": null, "e": 2490, "s": 2365, "text": "We will proceed by creating a blog app for our website. First, press ‘control’ + ‘C’ to kill the server running our web app:" }, { "code": null, "e": 2548, "s": 2490, "text": "Next, to create our blog application we do the following:" }, { "code": null, "e": 2579, "s": 2548, "text": "python manage.py startapp blog" }, { "code": null, "e": 2646, "s": 2579, "text": "We can look at our project structure upon creation of our new app:" }, { "code": null, "e": 2743, "s": 2646, "text": "Now, let’s go into our blog directory and open the ‘views.py’ file. We should see the following:" }, { "code": null, "e": 2804, "s": 2743, "text": "from django.shortcuts import render# Create your views here." }, { "code": null, "e": 2954, "s": 2804, "text": "Let’s also import HttpResponse. Let’s also create a new function called ‘home’, which will allow us to handle traffic from the home page of our blog:" }, { "code": null, "e": 3114, "s": 2954, "text": "from django.shortcuts import renderfrom django.http import HttpResponsedef home(request): return HttpResponse('<h1>Blog Home</h1>')# Create your views here." }, { "code": null, "e": 3291, "s": 3114, "text": "Next, we need to map our url pattern to this ‘view’ function. We go to our blog app directory and create a new file call ‘urls.py’ In this file we copy and paste the following:" }, { "code": null, "e": 3394, "s": 3291, "text": "from django.urls import pathfrom . import viewsurlpatterns = [path('', views.home, name='blog-home'),]" }, { "code": null, "e": 3487, "s": 3394, "text": "Now we have a url path for our blog home page mapped to our home function in the views file." }, { "code": null, "e": 3662, "s": 3487, "text": "For this to fully work, we need to modify our ‘urls.py’ module in main project directory, ‘first_site’. This module tells our website which urls will send us to our blog app." }, { "code": null, "e": 3723, "s": 3662, "text": "Let’s open the ‘urls.py’ file in our ‘first_site’ directory:" }, { "code": null, "e": 3832, "s": 3723, "text": "from django.contrib import adminfrom django.urls import pathurlpatterns = [path('admin/', admin.site.urls),]" }, { "code": null, "e": 4067, "s": 3832, "text": "We see we have one route that gets mapped to our admin site urls. We now need to specify the routes that get mapped to our blog urls. We need to import the include function from django.urls and add an additional path for our blog url:" }, { "code": null, "e": 4220, "s": 4067, "text": "from django.contrib import adminfrom django.urls import path, includeurlpatterns = [path('admin/', admin.site.urls),path('blog/', include('blog.urls'))]" }, { "code": null, "e": 4328, "s": 4220, "text": "Now let’s try to run the server. I often come across the following error upon attempting to run the server:" }, { "code": null, "e": 4359, "s": 4328, "text": "To remedy this issue, execute:" }, { "code": null, "e": 4380, "s": 4359, "text": "ps -ef | grep python" }, { "code": null, "e": 4435, "s": 4380, "text": "and use the following to kill the appropriate process:" }, { "code": null, "e": 4454, "s": 4435, "text": "kill -9 procees_id" }, { "code": null, "e": 4482, "s": 4454, "text": "Now try running the server:" }, { "code": null, "e": 4509, "s": 4482, "text": "python manage.py runserver" }, { "code": null, "e": 4578, "s": 4509, "text": "If we type, http://127.0.0.1:8000/blog/ we should see the following:" }, { "code": null, "e": 4715, "s": 4578, "text": "We can further edit the contents of blog home. Let’s add a quote from one of my favorite novels, Infinite Jest, by David Foster Wallace:" }, { "code": null, "e": 4971, "s": 4715, "text": "from django.shortcuts import renderfrom django.http import HttpResponsedef home(request): return HttpResponse('<h1>Blog Home</h1><p1>Everybody is identical in their secret unspoken belief that way deep down they are different from everyone else.</p1>')" }, { "code": null, "e": 5081, "s": 4971, "text": "We will also add an about page for our blog. In our ‘views.py’ module let’s define a function called ‘about’:" }, { "code": null, "e": 5402, "s": 5081, "text": "from django.shortcuts import renderfrom django.http import HttpResponsedef home(request): return HttpResponse('<h1>Blog Home</h1><p1>Everybody is identical in their secret unspoken belief that way deep down they are different from everyone else.</p1>')def about(request): return HttpResponse('<h1>About Home</h1>')" }, { "code": null, "e": 5490, "s": 5402, "text": "Now let’s add a new path for our about section in our ‘urls.py’ module in our blog app:" }, { "code": null, "e": 5639, "s": 5490, "text": "from django.urls import pathfrom . import viewsurlpatterns = [path('', views.home, name='blog-home'),path('about/', views.about, name='blog-about')]" }, { "code": null, "e": 5703, "s": 5639, "text": "Now if we go to http://127.0.0.1:8000/blog/about we should see:" }, { "code": null, "e": 5944, "s": 5703, "text": "I’ll stop here but feel free to play around with the contents of the blog home and about sections on our web application. Further, a great resource for learning more about Django is Corey Schafer’s YouTube tutorials which can be found here." } ]
Minimum steps required to reduce all array elements to 1 based on given steps - GeeksforGeeks
22 Nov, 2021 Given an array arr[] of size N. The task is to find the minimum steps required to reduce all array elements to 1. In each step, perform the following given operation: Choose any starting index, say i, and jump to the (arr[i] + i)th index, reducing ith as well as (arr[i] + i)th index by 1, follow this process until it reaches the end of the array If an element is already reduced to 1, it can’t be reduced more, it remains the same. Examples: Input: arr[] = {4, 2, 3, 2, 2, 2, 1, 2}, N = 8Output: 5Explanation: Series of operations can be performed in the following way: {4, 2, 3, 2, 2, 2, 1, 2}, decrement values by 1, arr[] = {4, 2, 2, 2, 2, 1, 1, 1} {4, 2, 2, 2, 2, 1, 1, 1}, decrement values by 1, arr[] = {3, 2, 2, 2, 1, 1, 1, 1} {3, 2, 2, 2, 1, 1, 1, 1}, decrement values by 1, arr[] = {2, 2, 2, 1, 1, 1, 1, 1} {2, 2, 2, 1, 1, 1, 1, 1}, decrement values by 1, arr[] = {1, 2, 1, 1, 1, 1, 1, 1} {1, 2, 1, 1, 1, 1, 1, 1}, decrement values by 1, arr[] = {1, 1, 1, 1, 1, 1, 1, 1} So, total steps required = 5 Input: arr[] = {1, 3, 1, 2, 2}, N = 5Output: 2 Approach: The given problem can be solved by dividing the problem in 4 parts :- (0 to i-1) | i | (i + 1) | (i + 2 to n – 1). Follow the below steps to solve the problem: Take a vector say v, which will denote how many times an element is decreased due to visiting the previous elements. Each element in v i.e v[i] denotes the count of decrement in arr[i] due to visiting the elements from 0 to (i-1). Iterate over the array arr[], and take a variable say k to store the numbers of passes that have to add in answer due to element arr[i] after making 0 to (i-1) elements equal to 1. Inside the loop, run another loop(i.e the second loop) to compute how much current arr[i] elements effect(decrease after visiting the ith element) the (i+2) to N elements. Take a vector say v, which will denote how many times an element is decreased due to visiting the previous elements. Each element in v i.e v[i] denotes the count of decrement in arr[i] due to visiting the elements from 0 to (i-1). Iterate over the array arr[], and take a variable say k to store the numbers of passes that have to add in answer due to element arr[i] after making 0 to (i-1) elements equal to 1. Inside the loop, run another loop(i.e the second loop) to compute how much current arr[i] elements effect(decrease after visiting the ith element) the (i+2) to N elements. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to find minimum steps // required to reduce all array // elements to 1 int minSteps(int arr[], int N) { // Variable to store the answer int steps = 0; // Vector with all elements initialized // with 0 vector<long long> v(N + 1, 0); // Traverse the array for (int i = 0; i < N; ++i) { // Variable to store the numbers of // passes that have to add in answer // due to element arr[i] after making // 0 to (i-1) elements equal to 1 int k = max(0ll, arr[i] - 1 - v[i]); // Increment steps by K steps += k; // Update element in v v[i] += k; // Loop to compute how much current element // effect the (i+2) to N elements for (int j = i + 2; j <= min(i + arr[i], N); j++) { v[j]++; } v[i + 1] += v[i] - arr[i] + 1; } // Return steps which is the answer return steps; } // Driver Code int main() { int arr[] = { 4, 2, 3, 2, 2, 2, 1, 2 }; int N = sizeof(arr) / sizeof(arr[0]); cout << minSteps(arr, N); return 0; } // Java code for the above approach import java.io.*; class GFG { // Function to find minimum steps // required to reduce all array // elements to 1 static int minSteps(int arr[], int N) { // Variable to store the answer int steps = 0; // Vector with all elements initialized // with 0 int v[] = new int[N + 1]; // Traverse the array for (int i = 0; i < N; ++i) { // Variable to store the numbers of // passes that have to add in answer // due to element arr[i] after making // 0 to (i-1) elements equal to 1 int k = Math.max(0, arr[i] - 1 - v[i]); // Increment steps by K steps += k; // Update element in v v[i] += k; // Loop to compute how much current element // effect the (i+2) to N elements for (int j = i + 2; j <= Math.min(i + arr[i], N); j++) { v[j]++; } v[i + 1] += v[i] - arr[i] + 1; } // Return steps which is the answer return steps; } // Driver Code public static void main(String[] args) { int arr[] = { 4, 2, 3, 2, 2, 2, 1, 2 }; int N = arr.length; System.out.println(minSteps(arr, N)); } } // This code is contributed by Potta Lokesh # Python program for the above approach # Function to find minimum steps # required to reduce all array # elements to 1 def minSteps(arr, N): # Variable to store the answer steps = 0 # Vector with all elements initialized # with 0 v = [0] * (N + 1) # Traverse the array for i in range(N): # Variable to store the numbers of # passes that have to add in answer # due to element arr[i] after making # 0 to (i-1) elements equal to 1 k = max(0, arr[i] - 1 - v[i]) # Increment steps by K steps += k # Update element in v v[i] += k # Loop to compute how much current element # effect the (i+2) to N elements for j in range(i + 2, min(i + arr[i], N) + 1): v[j] += 1 v[i + 1] += v[i] - arr[i] + 1 # Return steps which is the answer return steps # Driver Code arr = [4, 2, 3, 2, 2, 2, 1, 2] N = len(arr) print(minSteps(arr, N)) # This code is contributed by gfgking. // C# code for the above approach using System; class GFG { // Function to find minimum steps // required to reduce all array // elements to 1 static int minSteps(int[] arr, int N) { // Variable to store the answer int steps = 0; // Vector with all elements initialized // with 0 int[] v = new int[N + 1]; // Traverse the array for (int i = 0; i < N; ++i) { // Variable to store the numbers of // passes that have to add in answer // due to element arr[i] after making // 0 to (i-1) elements equal to 1 int k = Math.Max(0, arr[i] - 1 - v[i]); // Increment steps by K steps += k; // Update element in v v[i] += k; // Loop to compute how much current element // effect the (i+2) to N elements for (int j = i + 2; j <= Math.Min(i + arr[i], N); j++) { v[j]++; } v[i + 1] += v[i] - arr[i] + 1; } // Return steps which is the answer return steps; } // Driver Code public static void Main() { int[] arr = { 4, 2, 3, 2, 2, 2, 1, 2 }; int N = arr.Length; Console.Write(minSteps(arr, N)); } } // This code is contributed by gfgking <script> // JavaScript program for the above approach // Function to find minimum steps // required to reduce all array // elements to 1 const minSteps = (arr, N) => { // Variable to store the answer let steps = 0; // Vector with all elements initialized // with 0 let v = new Array(N + 1).fill(0); // Traverse the array for (let i = 0; i < N; ++i) { // Variable to store the numbers of // passes that have to add in answer // due to element arr[i] after making // 0 to (i-1) elements equal to 1 let k = Math.max(0, arr[i] - 1 - v[i]); // Increment steps by K steps += k; // Update element in v v[i] += k; // Loop to compute how much current element // effect the (i+2) to N elements for (let j = i + 2; j <= Math.min(i + arr[i], N); j++) { v[j]++; } v[i + 1] += v[i] - arr[i] + 1; } // Return steps which is the answer return steps; } // Driver Code let arr = [4, 2, 3, 2, 2, 2, 1, 2]; let N = arr.length document.write(minSteps(arr, N)); // This code is contributed by rakeshsahni </script> 5 Time Complexity: O(N2)Auxiliary Space: O(N) rakeshsahni lokeshpotta20 gfgking Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24479, "s": 24448, "text": " \n22 Nov, 2021\n" }, { "code": null, "e": 24646, "s": 24479, "text": "Given an array arr[] of size N. The task is to find the minimum steps required to reduce all array elements to 1. In each step, perform the following given operation:" }, { "code": null, "e": 24827, "s": 24646, "text": "Choose any starting index, say i, and jump to the (arr[i] + i)th index, reducing ith as well as (arr[i] + i)th index by 1, follow this process until it reaches the end of the array" }, { "code": null, "e": 24913, "s": 24827, "text": "If an element is already reduced to 1, it can’t be reduced more, it remains the same." }, { "code": null, "e": 24923, "s": 24913, "text": "Examples:" }, { "code": null, "e": 25051, "s": 24923, "text": "Input: arr[] = {4, 2, 3, 2, 2, 2, 1, 2}, N = 8Output: 5Explanation: Series of operations can be performed in the following way:" }, { "code": null, "e": 25133, "s": 25051, "text": "{4, 2, 3, 2, 2, 2, 1, 2}, decrement values by 1, arr[] = {4, 2, 2, 2, 2, 1, 1, 1}" }, { "code": null, "e": 25215, "s": 25133, "text": "{4, 2, 2, 2, 2, 1, 1, 1}, decrement values by 1, arr[] = {3, 2, 2, 2, 1, 1, 1, 1}" }, { "code": null, "e": 25297, "s": 25215, "text": "{3, 2, 2, 2, 1, 1, 1, 1}, decrement values by 1, arr[] = {2, 2, 2, 1, 1, 1, 1, 1}" }, { "code": null, "e": 25379, "s": 25297, "text": "{2, 2, 2, 1, 1, 1, 1, 1}, decrement values by 1, arr[] = {1, 2, 1, 1, 1, 1, 1, 1}" }, { "code": null, "e": 25461, "s": 25379, "text": "{1, 2, 1, 1, 1, 1, 1, 1}, decrement values by 1, arr[] = {1, 1, 1, 1, 1, 1, 1, 1}" }, { "code": null, "e": 25490, "s": 25461, "text": "So, total steps required = 5" }, { "code": null, "e": 25537, "s": 25490, "text": "Input: arr[] = {1, 3, 1, 2, 2}, N = 5Output: 2" }, { "code": null, "e": 25709, "s": 25537, "text": "Approach: The given problem can be solved by dividing the problem in 4 parts :- (0 to i-1) | i | (i + 1) | (i + 2 to n – 1). Follow the below steps to solve the problem:" }, { "code": null, "e": 26295, "s": 25709, "text": "\nTake a vector say v, which will denote how many times an element is decreased due to visiting the previous elements.\nEach element in v i.e v[i] denotes the count of decrement in arr[i] due to visiting the elements from 0 to (i-1).\nIterate over the array arr[], and take a variable say k to store the numbers of passes that have to add in answer due to element arr[i] after making 0 to (i-1) elements equal to 1.\nInside the loop, run another loop(i.e the second loop) to compute how much current arr[i] elements effect(decrease after visiting the ith element) the (i+2) to N elements.\n" }, { "code": null, "e": 26412, "s": 26295, "text": "Take a vector say v, which will denote how many times an element is decreased due to visiting the previous elements." }, { "code": null, "e": 26526, "s": 26412, "text": "Each element in v i.e v[i] denotes the count of decrement in arr[i] due to visiting the elements from 0 to (i-1)." }, { "code": null, "e": 26707, "s": 26526, "text": "Iterate over the array arr[], and take a variable say k to store the numbers of passes that have to add in answer due to element arr[i] after making 0 to (i-1) elements equal to 1." }, { "code": null, "e": 26879, "s": 26707, "text": "Inside the loop, run another loop(i.e the second loop) to compute how much current arr[i] elements effect(decrease after visiting the ith element) the (i+2) to N elements." }, { "code": null, "e": 26930, "s": 26879, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26934, "s": 26930, "text": "C++" }, { "code": null, "e": 26939, "s": 26934, "text": "Java" }, { "code": null, "e": 26947, "s": 26939, "text": "Python3" }, { "code": null, "e": 26950, "s": 26947, "text": "C#" }, { "code": null, "e": 26961, "s": 26950, "text": "Javascript" }, { "code": "\n\n\n\n\n\n\n// C++ program for the above approach\n#include <bits/stdc++.h>\nusing namespace std;\n \n// Function to find minimum steps\n// required to reduce all array\n// elements to 1\nint minSteps(int arr[], int N)\n{\n // Variable to store the answer\n int steps = 0;\n \n // Vector with all elements initialized\n // with 0\n vector<long long> v(N + 1, 0);\n \n // Traverse the array\n for (int i = 0; i < N; ++i) {\n // Variable to store the numbers of\n // passes that have to add in answer\n // due to element arr[i] after making\n // 0 to (i-1) elements equal to 1\n int k = max(0ll, arr[i] - 1 - v[i]);\n \n // Increment steps by K\n steps += k;\n // Update element in v\n v[i] += k;\n \n // Loop to compute how much current element\n // effect the (i+2) to N elements\n for (int j = i + 2; j <= min(i + arr[i], N); j++) {\n v[j]++;\n }\n v[i + 1] += v[i] - arr[i] + 1;\n }\n // Return steps which is the answer\n return steps;\n}\n \n// Driver Code\nint main()\n{\n int arr[] = { 4, 2, 3, 2, 2, 2, 1, 2 };\n int N = sizeof(arr) / sizeof(arr[0]);\n \n cout << minSteps(arr, N);\n \n return 0;\n}\n\n\n\n\n\n", "e": 28181, "s": 26971, "text": null }, { "code": "\n\n\n\n\n\n\n// Java code for the above approach\nimport java.io.*;\n \nclass GFG\n{\n \n // Function to find minimum steps\n // required to reduce all array\n // elements to 1\n static int minSteps(int arr[], int N)\n {\n \n // Variable to store the answer\n int steps = 0;\n \n // Vector with all elements initialized\n // with 0\n int v[] = new int[N + 1];\n \n // Traverse the array\n for (int i = 0; i < N; ++i)\n {\n \n // Variable to store the numbers of\n // passes that have to add in answer\n // due to element arr[i] after making\n // 0 to (i-1) elements equal to 1\n int k = Math.max(0, arr[i] - 1 - v[i]);\n \n // Increment steps by K\n steps += k;\n // Update element in v\n v[i] += k;\n \n // Loop to compute how much current element\n // effect the (i+2) to N elements\n for (int j = i + 2;\n j <= Math.min(i + arr[i], N); j++) {\n v[j]++;\n }\n v[i + 1] += v[i] - arr[i] + 1;\n }\n // Return steps which is the answer\n return steps;\n }\n \n // Driver Code\n public static void main(String[] args)\n {\n int arr[] = { 4, 2, 3, 2, 2, 2, 1, 2 };\n int N = arr.length;\n \n System.out.println(minSteps(arr, N));\n }\n}\n \n// This code is contributed by Potta Lokesh\n\n\n\n\n\n", "e": 29648, "s": 28191, "text": null }, { "code": "\n\n\n\n\n\n\n# Python program for the above approach\n \n# Function to find minimum steps\n# required to reduce all array\n# elements to 1\ndef minSteps(arr, N):\n \n # Variable to store the answer\n steps = 0\n \n # Vector with all elements initialized\n # with 0\n v = [0] * (N + 1)\n \n # Traverse the array\n for i in range(N):\n \n # Variable to store the numbers of\n # passes that have to add in answer\n # due to element arr[i] after making\n # 0 to (i-1) elements equal to 1\n k = max(0, arr[i] - 1 - v[i])\n \n # Increment steps by K\n steps += k\n # Update element in v\n v[i] += k\n \n # Loop to compute how much current element\n # effect the (i+2) to N elements\n for j in range(i + 2, min(i + arr[i], N) + 1):\n v[j] += 1\n v[i + 1] += v[i] - arr[i] + 1\n \n # Return steps which is the answer\n return steps\n \n# Driver Code\narr = [4, 2, 3, 2, 2, 2, 1, 2]\nN = len(arr)\n \nprint(minSteps(arr, N))\n \n # This code is contributed by gfgking.\n\n\n\n\n\n", "e": 30712, "s": 29658, "text": null }, { "code": "\n\n\n\n\n\n\n// C# code for the above approach\nusing System;\nclass GFG\n{\n \n // Function to find minimum steps\n // required to reduce all array\n // elements to 1\n static int minSteps(int[] arr, int N)\n {\n \n // Variable to store the answer\n int steps = 0;\n \n // Vector with all elements initialized\n // with 0\n int[] v = new int[N + 1];\n \n // Traverse the array\n for (int i = 0; i < N; ++i)\n {\n \n // Variable to store the numbers of\n // passes that have to add in answer\n // due to element arr[i] after making\n // 0 to (i-1) elements equal to 1\n int k = Math.Max(0, arr[i] - 1 - v[i]);\n \n // Increment steps by K\n steps += k;\n \n // Update element in v\n v[i] += k;\n \n // Loop to compute how much current element\n // effect the (i+2) to N elements\n for (int j = i + 2;\n j <= Math.Min(i + arr[i], N); j++) {\n v[j]++;\n }\n v[i + 1] += v[i] - arr[i] + 1;\n }\n \n // Return steps which is the answer\n return steps;\n }\n \n // Driver Code\n public static void Main()\n {\n int[] arr = { 4, 2, 3, 2, 2, 2, 1, 2 };\n int N = arr.Length;\n \n Console.Write(minSteps(arr, N));\n }\n}\n \n// This code is contributed by gfgking\n\n\n\n\n\n", "e": 32168, "s": 30722, "text": null }, { "code": "\n\n\n\n\n\n\n<script>\n // JavaScript program for the above approach\n \n // Function to find minimum steps\n // required to reduce all array\n // elements to 1\n const minSteps = (arr, N) => {\n // Variable to store the answer\n let steps = 0;\n \n // Vector with all elements initialized\n // with 0\n let v = new Array(N + 1).fill(0);\n \n // Traverse the array\n for (let i = 0; i < N; ++i) {\n // Variable to store the numbers of\n // passes that have to add in answer\n // due to element arr[i] after making\n // 0 to (i-1) elements equal to 1\n let k = Math.max(0, arr[i] - 1 - v[i]);\n \n // Increment steps by K\n steps += k;\n // Update element in v\n v[i] += k;\n \n // Loop to compute how much current element\n // effect the (i+2) to N elements\n for (let j = i + 2; j <= Math.min(i + arr[i], N); j++) {\n v[j]++;\n }\n v[i + 1] += v[i] - arr[i] + 1;\n }\n // Return steps which is the answer\n return steps;\n }\n \n // Driver Code\n let arr = [4, 2, 3, 2, 2, 2, 1, 2];\n let N = arr.length\n \n document.write(minSteps(arr, N));\n \n // This code is contributed by rakeshsahni\n \n</script>\n\n\n\n\n\n", "e": 33510, "s": 32178, "text": null }, { "code": null, "e": 33515, "s": 33513, "text": "5" }, { "code": null, "e": 33561, "s": 33517, "text": "Time Complexity: O(N2)Auxiliary Space: O(N)" }, { "code": null, "e": 33575, "s": 33563, "text": "rakeshsahni" }, { "code": null, "e": 33589, "s": 33575, "text": "lokeshpotta20" }, { "code": null, "e": 33597, "s": 33589, "text": "gfgking" }, { "code": null, "e": 33606, "s": 33597, "text": "\nArrays\n" }, { "code": null, "e": 33621, "s": 33606, "text": "\nMathematical\n" }, { "code": null, "e": 33826, "s": 33621, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 33847, "s": 33826, "text": "Next Greater Element" }, { "code": null, "e": 33872, "s": 33847, "text": "Window Sliding Technique" }, { "code": null, "e": 33899, "s": 33872, "text": "Count pairs with given sum" }, { "code": null, "e": 33948, "s": 33899, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 33986, "s": 33948, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 34016, "s": 33986, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 34031, "s": 34016, "text": "C++ Data Types" }, { "code": null, "e": 34092, "s": 34031, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34135, "s": 34092, "text": "Set in C++ Standard Template Library (STL)" } ]
Check If the Rune is a Space Character or not in Golang - GeeksforGeeks
27 Sep, 2019 Rune is a superset of ASCII or it is an alias of int32. It holds all the characters available in the world’s writing system, including accents and other diacritical marks, control codes like tab and carriage return, and assigns each one a standard number. This standard number is known as a Unicode code point or rune in the Go language.You are allowed to check the given rune is a space character or not defined by the Unicode’s White Space property, with the help of IsSymbol() function. This function returns true if the given rune is a space character, or return false if the given rune is not a space character. This function is defined under Unicode package, so for accessing this method you need to import the Unicode package in your program. Syntax: func IsSpace(r rune) bool The return type of this function is boolean. Let us discuss this concept with the help of given examples: Example 1: // Go program to illustrate how to check// the given rune is a space character// or notpackage main import ( "fmt" "unicode") // Main functionfunc main() { // Creating rune rune_1 := 'g' rune_2 := 'e' rune_3 := '\t' rune_4 := '\n' rune_5 := 'S' // Checking the given rune is // a space character or not // Using IsSpace () function res_1 := unicode.IsSpace(rune_1) res_2 := unicode.IsSpace(rune_2) res_3 := unicode.IsSpace(rune_3) res_4 := unicode.IsSpace(rune_4) res_5 := unicode.IsSpace(rune_5) // Displaying results fmt.Println(res_1) fmt.Println(res_2) fmt.Println(res_3) fmt.Println(res_4) fmt.Println(res_5) } Output: false false true true false Example 2: // Go program to illustrate how to check// the given rune is a space character// or notpackage main import ( "fmt" "unicode") // Main functionfunc main() { // Creating a slice of rune val := []rune{'g', '\f', '\v', '&', ' '} // Checking the given rune is // a space character or not // Using IsSpace () function for i := 0; i < len(val); i++ { if unicode.IsSpace(val[i]) == true { fmt.Println("It is a space character") } else { fmt.Println("It is not a space character") } }} Output: It is not a space character It is a space character It is a space character It is not a space character It is a space character Golang Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Check if the String ends with specified suffix in Golang Rune in Golang Anonymous function in Go Language How to Parse JSON in Golang? Class and Object in Golang Loops in Go Language Methods in Golang Structures in Golang Golang program that uses structs as map keys fmt.print() Function in Golang With Examples
[ { "code": null, "e": 24380, "s": 24352, "text": "\n27 Sep, 2019" }, { "code": null, "e": 25130, "s": 24380, "text": "Rune is a superset of ASCII or it is an alias of int32. It holds all the characters available in the world’s writing system, including accents and other diacritical marks, control codes like tab and carriage return, and assigns each one a standard number. This standard number is known as a Unicode code point or rune in the Go language.You are allowed to check the given rune is a space character or not defined by the Unicode’s White Space property, with the help of IsSymbol() function. This function returns true if the given rune is a space character, or return false if the given rune is not a space character. This function is defined under Unicode package, so for accessing this method you need to import the Unicode package in your program." }, { "code": null, "e": 25138, "s": 25130, "text": "Syntax:" }, { "code": null, "e": 25164, "s": 25138, "text": "func IsSpace(r rune) bool" }, { "code": null, "e": 25270, "s": 25164, "text": "The return type of this function is boolean. Let us discuss this concept with the help of given examples:" }, { "code": null, "e": 25281, "s": 25270, "text": "Example 1:" }, { "code": "// Go program to illustrate how to check// the given rune is a space character// or notpackage main import ( \"fmt\" \"unicode\") // Main functionfunc main() { // Creating rune rune_1 := 'g' rune_2 := 'e' rune_3 := '\\t' rune_4 := '\\n' rune_5 := 'S' // Checking the given rune is // a space character or not // Using IsSpace () function res_1 := unicode.IsSpace(rune_1) res_2 := unicode.IsSpace(rune_2) res_3 := unicode.IsSpace(rune_3) res_4 := unicode.IsSpace(rune_4) res_5 := unicode.IsSpace(rune_5) // Displaying results fmt.Println(res_1) fmt.Println(res_2) fmt.Println(res_3) fmt.Println(res_4) fmt.Println(res_5) }", "e": 25972, "s": 25281, "text": null }, { "code": null, "e": 25980, "s": 25972, "text": "Output:" }, { "code": null, "e": 26009, "s": 25980, "text": "false\nfalse\ntrue\ntrue\nfalse\n" }, { "code": null, "e": 26020, "s": 26009, "text": "Example 2:" }, { "code": "// Go program to illustrate how to check// the given rune is a space character// or notpackage main import ( \"fmt\" \"unicode\") // Main functionfunc main() { // Creating a slice of rune val := []rune{'g', '\\f', '\\v', '&', ' '} // Checking the given rune is // a space character or not // Using IsSpace () function for i := 0; i < len(val); i++ { if unicode.IsSpace(val[i]) == true { fmt.Println(\"It is a space character\") } else { fmt.Println(\"It is not a space character\") } }}", "e": 26601, "s": 26020, "text": null }, { "code": null, "e": 26609, "s": 26601, "text": "Output:" }, { "code": null, "e": 26738, "s": 26609, "text": "It is not a space character\nIt is a space character\nIt is a space character\nIt is not a space character\nIt is a space character\n" }, { "code": null, "e": 26745, "s": 26738, "text": "Golang" }, { "code": null, "e": 26757, "s": 26745, "text": "Go Language" }, { "code": null, "e": 26855, "s": 26757, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26864, "s": 26855, "text": "Comments" }, { "code": null, "e": 26877, "s": 26864, "text": "Old Comments" }, { "code": null, "e": 26934, "s": 26877, "text": "Check if the String ends with specified suffix in Golang" }, { "code": null, "e": 26949, "s": 26934, "text": "Rune in Golang" }, { "code": null, "e": 26983, "s": 26949, "text": "Anonymous function in Go Language" }, { "code": null, "e": 27012, "s": 26983, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 27039, "s": 27012, "text": "Class and Object in Golang" }, { "code": null, "e": 27060, "s": 27039, "text": "Loops in Go Language" }, { "code": null, "e": 27078, "s": 27060, "text": "Methods in Golang" }, { "code": null, "e": 27099, "s": 27078, "text": "Structures in Golang" }, { "code": null, "e": 27144, "s": 27099, "text": "Golang program that uses structs as map keys" } ]
Basic calculator program using Python program
In this tutorial, we are going to build a basic calculator in Python. I think all of you have an idea about the basic calculators. We will give six options to the user from which they select one option, and we will perform the respective operation. Following are the arithmetic operations we are going to perform. Addition Subtraction Multiplication Division Floor Division Modulo Try to implement it's on your own. Follow the below steps to write code for a simple calculator. 1. Initialise the two numbers. 2. Ask the user to enter an option by giving six options. 3. After getting the option from the user write if conditions for every operation based on the option. 4. Perform the respective operation. 5. Print the result. Let's write the code. ## initializing the numbers a, b = 15, 2 ## displaying catalog for the user choice print("1 - Addition\n2 - Substraction\n3 - Multiplication\n4 - Division\n5 - Floor Division\n6 - Modulo") ## getting option from the user option = int(input("Enter one option from the above list:- ")) ## writing condition to perform respective operation if option == 1: print(f"Addition: {a + b}") elif option == 2: print(f"Substraction: {a - b}") elif option == 3: print(f"Multiplication: {a * b}") elif option == 4: print(f"Division: {a / b}") elif option == 5: print(f"Floor Division: {a // b}") elif option == 6: print(f"Modulo: {a % b}") If you run the above program, you will get the following output. 1 - Addition 2 - Substraction 3 - Multiplication 4 - Division 5 - Floor Division 6 - Modulo Enter one option from the above list:- 3 Multiplication: 30 Let's execute the program once again ## initializing the numbers a, b = 15, 2 ## displaying catalog for the user choice print("1 - Addition\n2 - Substraction\n3 - Multiplication\n4 - Division\n5 - Floor Division\n6 - Modulo") ## getting option from the user option = int(input("Enter one option from the above list:- ")) ## writing condition to perform respective operation if option == 1: print(f"Addition: {a + b}") elif option == 2: print(f"Substraction: {a - b}") elif option == 3: print(f"Multiplication: {a * b}") elif option == 4: print(f"Division: {a / b}") elif option == 5: print(f"Floor Division: {a // b}") elif option == 6: print(f"Modulo: {a % b}") If you run the above program, you will get the following output. 1 - Addition 2 - Substraction 3 - Multiplication 4 - Division 5 - Floor Division 6 - Modulo Enter one option from the above list:- 6 Modulo: 1 If you have any doubts regarding the tutorial, mention them in the comment section.
[ { "code": null, "e": 1376, "s": 1062, "text": "In this tutorial, we are going to build a basic calculator in Python. I think all of you have an idea about the basic calculators. We will give six options to the user from which they select one option, and we will perform the respective operation. Following are the arithmetic operations we\nare going to perform." }, { "code": null, "e": 1385, "s": 1376, "text": "Addition" }, { "code": null, "e": 1397, "s": 1385, "text": "Subtraction" }, { "code": null, "e": 1412, "s": 1397, "text": "Multiplication" }, { "code": null, "e": 1421, "s": 1412, "text": "Division" }, { "code": null, "e": 1436, "s": 1421, "text": "Floor Division" }, { "code": null, "e": 1443, "s": 1436, "text": "Modulo" }, { "code": null, "e": 1540, "s": 1443, "text": "Try to implement it's on your own. Follow the below steps to write code for a simple calculator." }, { "code": null, "e": 1790, "s": 1540, "text": "1. Initialise the two numbers.\n2. Ask the user to enter an option by giving six options.\n3. After getting the option from the user write if conditions for every operation based on the option.\n4. Perform the respective operation.\n5. Print the result." }, { "code": null, "e": 1812, "s": 1790, "text": "Let's write the code." }, { "code": null, "e": 2456, "s": 1812, "text": "## initializing the numbers\na, b = 15, 2\n## displaying catalog for the user choice\nprint(\"1 - Addition\\n2 - Substraction\\n3 - Multiplication\\n4 - Division\\n5 - Floor Division\\n6 - Modulo\")\n## getting option from the user\noption = int(input(\"Enter one option from the above list:- \"))\n## writing condition to perform respective operation\nif option == 1:\n print(f\"Addition: {a + b}\")\nelif option == 2:\n print(f\"Substraction: {a - b}\")\nelif option == 3:\n print(f\"Multiplication: {a * b}\")\nelif option == 4:\n print(f\"Division: {a / b}\")\nelif option == 5:\n print(f\"Floor Division: {a // b}\")\nelif option == 6:\n print(f\"Modulo: {a % b}\")" }, { "code": null, "e": 2521, "s": 2456, "text": "If you run the above program, you will get the following output." }, { "code": null, "e": 2673, "s": 2521, "text": "1 - Addition\n2 - Substraction\n3 - Multiplication\n4 - Division\n5 - Floor Division\n6 - Modulo\nEnter one option from the above list:- 3\nMultiplication: 30" }, { "code": null, "e": 2710, "s": 2673, "text": "Let's execute the program once again" }, { "code": null, "e": 3354, "s": 2710, "text": "## initializing the numbers\na, b = 15, 2\n## displaying catalog for the user choice\nprint(\"1 - Addition\\n2 - Substraction\\n3 - Multiplication\\n4 - Division\\n5 - Floor Division\\n6 - Modulo\")\n## getting option from the user\noption = int(input(\"Enter one option from the above list:- \"))\n## writing condition to perform respective operation\nif option == 1:\n print(f\"Addition: {a + b}\")\nelif option == 2:\n print(f\"Substraction: {a - b}\")\nelif option == 3:\n print(f\"Multiplication: {a * b}\")\nelif option == 4:\n print(f\"Division: {a / b}\")\nelif option == 5:\n print(f\"Floor Division: {a // b}\")\nelif option == 6:\n print(f\"Modulo: {a % b}\")" }, { "code": null, "e": 3419, "s": 3354, "text": "If you run the above program, you will get the following output." }, { "code": null, "e": 3562, "s": 3419, "text": "1 - Addition\n2 - Substraction\n3 - Multiplication\n4 - Division\n5 - Floor Division\n6 - Modulo\nEnter one option from the above list:- 6\nModulo: 1" }, { "code": null, "e": 3646, "s": 3562, "text": "If you have any doubts regarding the tutorial, mention them in the comment section." } ]
Web2py - Quick Guide
web2py is defined as a free, open-source web framework for agile development which involves database-driven web applications; it is written in Python and programmable in Python. It is a full-stack framework; it consists of all the necessary components, a developer needs to build a fully functional web application. web2py framework follows the Model-View-Controller pattern of running web applications unlike traditional patterns. Model is a part of the application that includes logic for the data. The objects in model are used for retrieving and storing the data from the database. Model is a part of the application that includes logic for the data. The objects in model are used for retrieving and storing the data from the database. View is a part of the application, which helps in rendering the display of data to end users. The display of data is fetched from Model. View is a part of the application, which helps in rendering the display of data to end users. The display of data is fetched from Model. Controller is a part of the application, which handles user interaction. Controllers can read data from a view, control user input, and send input data to the specific model. Controller is a part of the application, which handles user interaction. Controllers can read data from a view, control user input, and send input data to the specific model. web2py has an in-built feature to manage cookies and sessions. After committing a transaction (in terms of SQL), the session is also stored simultaneously. web2py has an in-built feature to manage cookies and sessions. After committing a transaction (in terms of SQL), the session is also stored simultaneously. web2py has the capacity of running the tasks in scheduled intervals after the completion of certain actions. This can be achieved with CRON. web2py has the capacity of running the tasks in scheduled intervals after the completion of certain actions. This can be achieved with CRON. Take a look at the workflow diagram given below. The workflow diagram is described below. The Models, Views and Controller components make up the user web2py application. The Models, Views and Controller components make up the user web2py application. Multiple applications can be hosted in the same instance of web2py. Multiple applications can be hosted in the same instance of web2py. The browser sends the HTTP request to the server and the server interacts with Model, Controller and View to fetch the necessary output. The browser sends the HTTP request to the server and the server interacts with Model, Controller and View to fetch the necessary output. The arrows represent communication with the database engine(s). The database queries can be written in raw SQL or by using the web2py Database Abstraction Layer (which will be discussed in further chapters), so that web2py application code is independent of any database engine. The arrows represent communication with the database engine(s). The database queries can be written in raw SQL or by using the web2py Database Abstraction Layer (which will be discussed in further chapters), so that web2py application code is independent of any database engine. Model establishes the database connection with the database and interacts with the Controller. The Controller on the other hand interacts with the View to render the display of data. Model establishes the database connection with the database and interacts with the Controller. The Controller on the other hand interacts with the View to render the display of data. The Dispatcher maps the requested URL as given in HTTP response to a function call in the controller. The output of the function can be a string or a hash table. The Dispatcher maps the requested URL as given in HTTP response to a function call in the controller. The output of the function can be a string or a hash table. The data is rendered by the View. If the user requests an HTML page (the default), the data is rendered into an HTML page. If the user requests the same page in XML, web2py tries to find a view that can render the dictionary in XML. The data is rendered by the View. If the user requests an HTML page (the default), the data is rendered into an HTML page. If the user requests the same page in XML, web2py tries to find a view that can render the dictionary in XML. The supported protocols of web2py include HTML, XML, JSON, RSS, CSV, and RTF. The supported protocols of web2py include HTML, XML, JSON, RSS, CSV, and RTF. The model-view-controller representation of web2py is as follows − "db.py" is the model: db = DAL('sqlite://storage.sqlite') db.define_table(employee, Field('name'), Field(‘phone’)) The Model includes the logic of application data. It connects to the database as mentioned in the figure above. Consider SQLite is being used and is stored in storage.sqlite file with a table defined as employee. If the table does not exist, web2py helps by creating the respective table. The program "default.py" is the Controller. def employees(): grid = SQLFORM.grid(db.contact, user_signature = False) return locals() In web2py, URL mapping helps in accessing the functions and modules. For the above example, the Controller contains a single function (or "action") called employees. The action taken by the Controller returns a string or a Python dictionary, which is a combination of key and value including a local set of variables. "default/contacts.html" is the View. {{extend 'layout.html'}} <h1>Manage My Employees</h1> {{=grid}} For the given example, View displays the output after the associated controller function is executed. The purpose of this View is to render the variables in the dictionary, which is in the form of HTML. The View file is written in HTML, but it embeds Python code with the help of {{ and }} delimiters. The code embedded into HTML consists of Python code in the dictionary. web2py comes in binary packages for all the major operating systems like Windows, UNIX and Mac OS X. It is easy to install web2py because − It comprises of the Python interpreter, so you do not need to have it pre-installed. There is also a source code version that runs on all the operating systems. It comprises of the Python interpreter, so you do not need to have it pre-installed. There is also a source code version that runs on all the operating systems. The following link comprises of the binary packages of web2py for download as per the user’s need − www.web2py.com The following link comprises of the binary packages of web2py for download as per the user’s need − www.web2py.com The web2py framework requires no pre-installation unlike other frameworks. The user needs to download the zip file and unzip as per the operating system requirement. The web2py framework requires no pre-installation unlike other frameworks. The user needs to download the zip file and unzip as per the operating system requirement. The web2py framework is written in Python, which is a complete dynamic language that does not require any compilation or complicated installation to run. The web2py framework is written in Python, which is a complete dynamic language that does not require any compilation or complicated installation to run. It uses a virtual machine like other programming languages such as Java or .net and it can transparently byte-compile the source code written by the developers. It uses a virtual machine like other programming languages such as Java or .net and it can transparently byte-compile the source code written by the developers. Python can be defined as a combination of object-oriented and interactive language. It is an open source software. Guido van Rossum conceived python in the late 1980s. Python is a language similar to PERL (Practical Extraction and Reporting Language), which has gained popularity because of its clear syntax and readability. The main notable features of Python are as follows − Python is said to be relatively easy to learn and portable. Its statements can be easily interpreted in a number of operating systems, including UNIX-based systems, Mac OS, MS-DOS, OS/2, and various versions of Windows. Python is said to be relatively easy to learn and portable. Its statements can be easily interpreted in a number of operating systems, including UNIX-based systems, Mac OS, MS-DOS, OS/2, and various versions of Windows. Python is portable with all the major operating systems. It uses an easy to understand syntax, making the programs, which are user friendly. Python is portable with all the major operating systems. It uses an easy to understand syntax, making the programs, which are user friendly. It comes with a large standard library that supports many tasks. It comes with a large standard library that supports many tasks. From the above diagram, it is clearly visible that Python is a combination of scripting as well as programming language. They are interpreted within another program like scripting languages. Python has three production-quality implementations, which are called as CPython, Jython, and IronPython. These are also termed as versions of Python. Classic Python a.k.a CPython is a compiler, interpreter and consists of built-in and optional extension modules which is implemented in standard C language. Classic Python a.k.a CPython is a compiler, interpreter and consists of built-in and optional extension modules which is implemented in standard C language. Jython is a Python implementation for Java Virtual Machine (JVM). Jython is a Python implementation for Java Virtual Machine (JVM). IronPython is designed by Microsoft, which includes Common Language Runtime (CLR). It is commonly known as .NET IronPython is designed by Microsoft, which includes Common Language Runtime (CLR). It is commonly known as .NET A basic Python program in any operating system starts with a header. The programs are stored with .py extension and Python command is used for running the programs. For example, python_rstprogram.py will give you the required output. It will also generate errors, if present. Python uses indentation to delimit blocks of code. A block starts with a line ending with colon, and continues for all lines in the similar fashion that have a similar or higher indentation as the next line. # Basic program in Python print "Welcome to Python!\n" The output of the program will be − Welcome to Python! Indentations of the programs are quite important in Python. There are some prejudices and myths about Python's indentation rules for the developers who are beginners to Python. The thumb rule for all the programmers is − Leading whitespace, which includes spaces and tabs at the beginning of a logical line of Python computes the indentation level of line. The indentation level also determines the grouping of the statements. The indentation level also determines the grouping of the statements. It is common to use four spaces i.e. tab for each level of indentation. It is common to use four spaces i.e. tab for each level of indentation. It is a good policy not to mix tabs with spaces, which can result in confusion, which is invisible. It is a good policy not to mix tabs with spaces, which can result in confusion, which is invisible. Python also generates a compile time error if there is lack of indentation. IndentationError: expected an indented block The control flow of a Python program is regulated by conditional statements, loops and function calls. The If statement, executes a block of code under specified condition, along with else and elif(a combination of else-if). The If statement, executes a block of code under specified condition, along with else and elif(a combination of else-if). The For statement, iterates over an object, capturing each element to a local variable for use by the attached block. The For statement, iterates over an object, capturing each element to a local variable for use by the attached block. The While statement, executes a block of code under the condition, which is True. The While statement, executes a block of code under the condition, which is True. The With statement, encloses a code block within the context manager. It has been added as a more readable alternative to the try/finally statement. The With statement, encloses a code block within the context manager. It has been added as a more readable alternative to the try/finally statement. # If statement in Python x = int(raw_input("Please enter an integer: ")) #Taking input from the user if x<0: print "1 - Got a negative expression value" print x else: print "1 - Got a positive expression value" print x print "Good bye!" sh-4.3$ python main.py Please enter an integer: 4 1 - Got a positive expression value 4 Good bye! The statements in a typical Python program are organized and grouped in a particular format called, “Functions". A function is a group of statements that perform an action based on the request. Python provides many built-in functions and allows programmers to define their own functions. In Python, functions are values that are handled like other objects in programming languages. The def statement is the most common way to define a function. def is a single-clause compound statement with the following syntax − def function-name (parameters):statement(s) The following example demonstrates a generator function. It can be used as an iterable object, which creates its objects in a similar way. def demo (): for i in range(5): yield (i*i) for j in demo(): print j sh-4.3$ python main.py 0 1 4 9 16 The attributes, methods, and operators starting with double underscore of a class are usually private in behavior. Some of them are reserved keywords, which include a special meaning. Three of them are listed below − __len__ __len__ __getitem__ __getitem__ __setitem__ __setitem__ The other special operators include __getattr__ and __setattr__, which defines the get and set attributes for the class. Python includes a functionality to open and close particular files. This can be achieved with the help of open(), write() and close() functions. The commands which help in file input and output are as follows − open() It helps in opening a file or document write() It helps to write a string in file or document read() It helps in reading the content in existing file close() This method closes the file object. Consider a file named “demo.txt”, which already exists with a text “This is a demo file”. #!/usr/bin/python # Open a file fo = open("demo.txt", "wb") fo.write( "Insering new line \n"); # Close opend file fo.close() The string available after opening the file will be − This is a demo file Inserting a new line web2py is a full-stack web framework that can be used by a developer to completely develop a web application. It includes SQL database integration and multi-threaded web server for designing a program. Once the command is executed as per the operating system, web2py displays a startup window and then displays a GUI widget that asks the user to choose − a one-time administrator password, the IP address of the network interface to be used for the web server, and a port number from which to serve requests. The administrator includes all the authority for addition and editing any new web application. By default, web2py runs its web server on 127.0.0.1:8000 (port 8000 on localhost) but a user can run it on any available IP address and port as per the requirement. The web2py GUI widget will be displayed as shown below. The password is used in the administrative interface for any changes in the new module. After the user has set the administration password, web2py starts up the web browser at the page with the following URL − http://127.0.0.1:8000/ The welcome page of the framework will be displayed as shown below. After starting the web2py application, with the above-mentioned URL, we can use the administrative interface for creating a new module, for example, “helloWorld”. The administrative interface will ask for the password for authentication purpose as the administrator holds all the authority for addition and editing any new web application. The snapshot given above includes the page details, which lists all the installed web2py applications and allows the administrator to manage them. By default, the web2py framework comes with three applications. They are − An admin application, which the user is implementing currently. An admin application, which the user is implementing currently. An examples application, with the online interactive documentation and an instance of the web2py official website. An examples application, with the online interactive documentation and an instance of the web2py official website. A welcome application. It includes the basic template for any other web2py application. It is also known as the scaffolding application. The application also welcomes a user at the startup. A welcome application. It includes the basic template for any other web2py application. It is also known as the scaffolding application. The application also welcomes a user at the startup. Let the name of the new application be “helloWorld”. Once, a new application is created, the user is redirected to a page comprising of view, model and controllers of the respective application. The user can look at the newly created application by mentioning the following URL − http://127.0.0.1:8000/helloWorld By default, a user can view the following screen on hitting the above-mentioned URL. For printing the message of the given web application “helloWorld”, the change is made in the default.py controller. The function named “index” is the default function for returning the value and displaying the necessary output. As mentioned above, the string “Hello World- Welcome to my first web application” is used as the return value, which displays the output in the screen. The output is displayed as follows − The mechanism of validating the input of form is very common and is not considered as such a good programming practice. The input is validated each time, which is a burden for validation. A better pattern in web2py is to submit forms to the same action, which generates them. This mechanism is called as “postback” which is the main feature of web2py. In short, self-submission is achieved in postback. def first(): if request.vars.visitor_name: #if visitor name exists session.visitor_name = request.vars.visitor_name redirect(URL('second'))#postback is implemented return dict() web2py includes applications, which perform the functions of Create, retrieve, update and delete. The CRUD cycle describes the elemental functions of a database, which is persistent. All the application logic is written in the models, which are retrieved by the controllers and displayed to the users with the help of view. For PHP, the application server includes listing of all the databases under phpmyadmin. In a similar way, web2py provides an interface for managing, creating and deleting tables or databases, which is termed as “appadmin.” Before implementing the logic behind the tables, it is necessary to create database and its associated tables. The URL to access appadmin − http://127.0.0.1:8000/applicationname/appadmin On hitting the URL, the user will get the list of tables associated for the given application. This interface is not intended to be public. It is designed to get an easy access to the database. It consists of two files namely − a controller “appadmin.py” and a view “appadmin.html”. It can paginate up to 100 records at a time. The usage of “appadmin” is discussed in subsequent chapters. We have learnt how to start the web2py server using GUI widget in the previous chapter. This widget can be skipped by starting the server from command line prompt. python web2py.py -a 'your password' -i 127.0.0.1 -p 8000 Whenever web2py server starts, it creates a file "parameters_8000.py" where all the passwords are stored in a hashed form. For additional security purpose, the following command line can be used − python web2py.py -a '<recycle>' -i 127.0.0.1 -p 8000 For the above scenario, web2py reuses the hashed passwords stored in "parameters_8000.py". In case, if the file "parameters_8000.py" is deleted accidently or due to some other reasons, the web-based administrative interface is disabled in web2py. The functioning of web2py is based on model-view-controller, which maps the URL in a specific form − http://127.0.0.1:8000/a/d/f.html It routes till the function “f()” mentioned in the controller d.py is under the application named “a”. If the controller is not present in the application then web2py uses a default controller named “default.py”. If the function, as given in the URL is not present, then the default function called init() is used. The working of the URL is shown schematically in the image below. The extension .html is optional for the URL. The extension determines the extension of View that renders the output of the function defined in the controller. The same content is served in multiple formats namely html, xml, json, rss etc. The request is passed, based on the functions, which accept the arguments and gives the appropriate output to the user. It is the controller, which interacts with model and view of the application for giving the output as per the user’s need. The workflow of web2py is discussed below − The web server manages each and every HTTP requests simultaneously in its own thread. The web server manages each and every HTTP requests simultaneously in its own thread. The HTTP request header is parsed and passed to the dispatcher. The HTTP request header is parsed and passed to the dispatcher. The Dispatcher manages the application requests and maps the PATH_INFO in the URL of the function call. Every function call is represented in the URL. The Dispatcher manages the application requests and maps the PATH_INFO in the URL of the function call. Every function call is represented in the URL. All the requests for files included in the static folder are managed directly, and large file are streamed to the client. All the requests for files included in the static folder are managed directly, and large file are streamed to the client. Requests for anything but a static file are mapped into an action. Requests for anything but a static file are mapped into an action. If the request header contains a session cookie for the app, the session object is retrieved; or else, a session id is created. If the request header contains a session cookie for the app, the session object is retrieved; or else, a session id is created. If the action returns a value as string, this is returned to the client. If the action returns a value as string, this is returned to the client. If the action returns an iterable, it is used to loop and stream the data to the client. If the action returns an iterable, it is used to loop and stream the data to the client. In the previous chapter, we saw the functionality of the Controllers. web2py uses models, views and controllers in each of its application. Therefore, it is also necessary to understand the functionality of the Model. Unlike any other MVC application, Models in web2py are treated as conditional. Models in subfolders are executed, based on its controller’s usage. This can be demonstrated with following example − Consider the URL − http://127.0.0.1:8000/a/d/f.html In this case, ‘a’ is the name of the application, ‘d’ is the controller’s name and f() is the function associated with the controller. The list of models, which will be executed are as follows − applications/a/models/*.py applications/a/models/d/*.py applications/a/models/d/f/*.py web2py includes libraries, which are exposed to the all the applications as the objects. These objects are defined inside the core files under the directory named “gluon”. Many of the modules like DAL template have no dependencies and can be implemented outside the framework of web2py. It also maintains the unit tests which is considered as good practice. web2py applications are shown below in a diagrammatic form. The Applications developed in web2py are composed of the following parts − Models − Represents data and database tables. Models − Represents data and database tables. Controllers − Describes the application logic and workflow. Controllers − Describes the application logic and workflow. Views − Helps rendering the display of the data. Views − Helps rendering the display of the data. Languages − describe how to translate strings in the application into various supported languages. Languages − describe how to translate strings in the application into various supported languages. Static files − Do not require processing (e.g. images, CSS style sheets etc). Static files − Do not require processing (e.g. images, CSS style sheets etc). ABOUT and README − Details of the project. ABOUT and README − Details of the project. Errors − Stores error reports generated by the application. Errors − Stores error reports generated by the application. Sessions − Stores information related to each particular user. Sessions − Stores information related to each particular user. Databases − store SQLite databases and additional table information. Databases − store SQLite databases and additional table information. Cache − Store cached application items. Cache − Store cached application items. Modules − Modules are other optional Python modules. Modules − Modules are other optional Python modules. Private − Included files are accessed by the controllers but not directly by the developer. Private − Included files are accessed by the controllers but not directly by the developer. Uploads − Files are accessed by the models but not directly by the developer. Uploads − Files are accessed by the models but not directly by the developer. In web2py, models, controllers and views are executed in an environment where certain objects are imported for the developers. Global Objects − request, response, session, cache. Helpers − web2py includes helper class, which can be used to build HTML programmatically. It corresponds to HTML tags, termed as “HTML helpers”. For example, A, B, FIELDSET, FORM, etc. A session can be defined as a server-side storage of information, which is persisted throughout the user's interaction throughout the web application. Session in web2py is the instance of storage class. For example, a variable can be stored in session as session.myvariable = "hello" This value can be retrieved as a = session.myvariable The value of the variable can be retrieved as long as the code is executed in the same session by the same user. One of the important methods in web2py for session is “forget” − session.forget(response); It instructs web2py not to save the session. An HTTP request arrives to the web server, which handles each request in its own thread, in parallel. The task, which is active, takes place in the foreground while the others are kept in background. Managing the background tasks is also one of the main features of web2py. Time-consuming tasks are preferably kept in the background. Some of the mechanisms are listed as follows, which manage the background tasks − CRON CRON Queues Queues Scheduler Scheduler In web2py, CRON gives the ability to run the task within the specified intervals of the time. Each application includes a CRON file, which defines its functionalities. The built-in scheduler helps in running the tasks in background by setting the priority. It provides a mechanism for creating, scheduling and modifying the tasks. The scheduled events are listed in models with the file name “scheduler.py”. We had an overview of creating models and controllers in web2py. Here, we will focus on the creation of the application named “Contacts”. The application needs to maintain a list of companies, and a list of people who work at those companies. Here, identification of the tables for the data dictionary is the model. The model for the contacts application will be created under the “models” folders. The file is stored in models/db_contacts.py. # in file: models/db_custom.py db.define_table('company', Field('name', notnull = True, unique = True), format = '%(name)s') db.define_table( 'contact', Field('name', notnull = True), Field('company', 'reference company'), Field('picture', 'upload'), Field('email', requires = IS_EMAIL()), Field('phone_number', requires = IS_MATCH('[\d\-\(\) ]+')), Field('address'), format = '%(name)s' ) db.define_table( 'log', Field('body', 'text', notnull = True), Field('posted_on', 'datetime'), Field('contact', 'reference contact') ) Once the above file is created, the tables can be accessed with the help of URL http://127.0.0.1:8000/contacts/appadmin The Controller will include some functions for listing, editing and deleting the contacts. # in file: controllers/default.py def index():return locals() def companies():companies = db(db.company).select(orderby = db.company.name) return locals() def contacts():company = db.company(request.args(0)) or redirect(URL('companies')) contacts = db(db.contact.company == company.id).select(orderby = db.contact.name) return locals() @auth.requires_login() def company_create():form = crud.create(db.company, next = 'companies') return locals() @auth.requires_login() def company_edit():company = db.company(request.args(0)) or redirect(URL('companies')) form = crud.update(db.company, company, next='companies') return locals() @auth.requires_login() def contact_create():db.contact.company.default = request.args(0) form = crud.create(db.contact, next = 'companies') return locals() @auth.requires_login() def contact_edit():contact = db.contact(request.args(0)) or redirect(URL('companies')) form = crud.update(db.contact, contact, next = 'companies') return locals() def user():return dict(form = auth()) The creation of the view along with its output will be discussed in the next chapter. web2py framework uses Models, Controllers and Views in its applications. It includes a slightly modified Python syntax in the Views for more readable code without any restriction as imposed on proper Python usage. The main purpose of a web2py View is to embed the python code in an HTML document. However, it faces some issues, which are as follows − Escaping of embedded python code in an HTML document. Following indentation based on Python, which may affect HTML rules. To escape with the problems, web2py uses delimiters {{..}} in the view section. The delimiters help in escaping the embedded python code. It also helps in following the HTML rules of indentation. The code included within {{..}} delimiters include unintended Python code. Since Python normally uses indentation to delimit blocks of code, the unintended code within the delimiters should be maintained in proper way. To overcome this problem, web2py uses the “pass” keyword. The code block beginning with a line terminates with a colon and ends with a line beginning with pass. Note − pass is a Python keyword, it is not a web2py keyword. The following code shows the implementation of pass keyword − {{ if num > 0: response.write('positive number') else: response.write('negative number') pass }} web2py includes helper class which can be used to build HTML programmatically. It corresponds to the HTML tags, termed as “HTML helpers”. For example − [(A('Home', _href = URL('default', 'home')), False, None, []), ...] Here, A is the helper corresponding to the anchor <a> tag of HTML. It builds the HTML anchor <a> tag programmatically. HTML helpers consists of two types, namely positional and named arguments. Positional arguments are interpreted as objects contained between the HTML open and close tags. Positional arguments are interpreted as objects contained between the HTML open and close tags. Named arguments begins with an underscore are interpreted as HTML tag. Named arguments begins with an underscore are interpreted as HTML tag. Helpers are also useful in serialization of strings, with the _str_ and xml methods. For example − >>> print str(DIV(“hello world”)) <div> hello world </div> Note − HTML helpers provide a server-side representation of the Document Object Model (DOM). XML is termed as an object, which encapsulates text that should not be escaped. The text may or may not contain valid XML. For example, for the below mentioned code, it could contain JavaScript. >>> print XML('<script>alert("unsafe!")</script>') <script> alert(“unsafe!”)</script> There are many built-in helpers used in web2py. Some of the HTML built-in helpers are listed as below. [ (A('Home', _href = URL('default', 'home')), False, None, []), ...] B('<hello>', XML('<i>world</i>'), _class = 'test', _id = 0) BR() CODE('print "hello"', language = 'python').xml() FIELDSET('Height:', INPUT(_name = 'height'), _class = 'test') HEAD(TITLE('<hello>')) IMG(_src = 'http://example.com/image.png',_alt = 'test') These helpers are used to customize the tags as per the requirements. web2py uses following custom helpers − web2py uses TAG as the universal tag generator. It helps in generating customized XML tags. The general syntax is as follows − {{ = TAG.name('a', 'b', _c = 'd')}} It generates the XML code as : <name c = "d">ab</name> TAG is an object and TAG.name or TAG['name'] is a function that returns a temporary helper class. This helper makes a list of the list items or the values of the menu items, generating a tree-like structure representing the menu. The list of menu items is in the form of response.menu. For example − print MENU([['One', False, 'link1'], ['Two', False, 'link2']]) The output will be displayed as follows − <ul class = "web2py-menu web2py-menu-vertical"> <li><a href = "link1">One</a></li> <li><a href = "link2">Two</a></li> </ul> It helps in building representations of compound objects, including lists and dictionaries. For example, {{ = BEAUTIFY({"a": ["hello", XML("world")], "b": (1, 2)})}} It returns an XML object serializable to XML, with a representation of its constructor argument. In this case, the representation would be − {"a": ["hello", XML("world")], "b": (1, 2)} The output will be rendered as − <table> <tr> <td>a</td> <td>:</td> <td>hello<br />world</td> </tr> <tr> <td>b</td> <td>:</td> <td>1<br />2</td> </tr> </table> Server-side rendering allows a user to pre-render the initial state of web2py components. All the derived helpers provide search element and elements to render DOM on server side. The element returns the first child element matching a specified condition. On the other hand, elements return a list of all the matching children. Both use same syntax. This can be demonstrated with the following example − a = DIV(DIV(DIV('a', _id = 'target',_class = 'abc'))) d = a.elements('div#target') d[0][0] = 'changed' print a The output is given as − <div><div><div id = "target" class = "abc">changed</div></div></div> Views are used to display the output to the end users. It can extend as well as include other views as well. This will implement a tree-like structure. Example − “index.html” extends to “layout.html” which can include “menu.html” which in turn includes “header.html”. {{extend 'layout.html'}} <h1>Hello World</h1> {{include 'page.html'}} In the previous chapters, we created models and controllers for the company module. Now, we will focus on the creation of view, which helps in rendering the display of data. By default, the views in web2py include layout.html and index.html, which defines the overall section of displaying data. {{extend 'layout.html'}} <h2>Companies</h2> <table> {{for company in companies:}} <tr> <td>{{ = A(company.name, _href = URL('contacts', args = company.id))}}</td> <td>{{ = A('edit', _href = URL('company_edit', args = company.id))}}</td> </tr> {{pass}} <tr> <td>{{ = A('add company', _href = URL('company_create'))}}</td> </tr> </table> The output will be as follows − The Database Abstraction Layer (DAL) is considered as the major strength of web2py. The DAL exposes a simple Applications Programming Interface (API) to the underlying SQL syntax. In this chapter, we will get to know the non-trivial applications of DAL, such as building queries to search by tags efficiently and building a hierarchical category tree. Some important features of DAL are − web2py includes a Database Abstraction Layer (DAL), an API which maps Python objects into database objects. The database objects can be queries, tables and records. web2py includes a Database Abstraction Layer (DAL), an API which maps Python objects into database objects. The database objects can be queries, tables and records. The DAL dynamically generates the SQL in real time using the specified dialect for the database back end, so that it is not mandatory for a developer to write complete SQL query. The DAL dynamically generates the SQL in real time using the specified dialect for the database back end, so that it is not mandatory for a developer to write complete SQL query. The major advantage of using DAL is that the applications will be portable with different kinds of databases. The major advantage of using DAL is that the applications will be portable with different kinds of databases. Most applications in web2py require a database connection. Therefore, building the database model is the first step in the design of an application. Consider the newly created application named “helloWorld”. The database is implemented under the Models of the application. All the models for the respective application are comprised under file named − models/db_custom.py. The following steps are used for implementing DAL − Establish a database connection. This is created using DAL object which is also called the DAL constructor. db = DAL ('sqlite://storage.sqlite') The notable feature of DAL is that it allows multiple connections with the same database or with different databases, even with different types of database. It is observed that this line is already in the file models/db.py. Therefore, you may not need it, unless you deleted it or need to connect to a different database. By default, web2py connects to a SQLite database stored in file storage.sqlite. This file is located in the application's databases folder. If the file is absent, it is created by web2py when the application is first executed. SQLite is fast, and stores all the data in one single file. This means that your data can be easily transferred from one application to another. In fact, the SQLite database(s) are packaged by web2py together with the applications. It provides full SQL support, including translations, joins, and aggregates. There are two disadvantages of SQLite. One is that it does not enforce column types, and there is no ALTER TABLE except for adding and dropping columns. One is that it does not enforce column types, and there is no ALTER TABLE except for adding and dropping columns. The other disadvantage is that the entire database is locked by any transaction that requires write access. The other disadvantage is that the entire database is locked by any transaction that requires write access. Once the connection with database is established, we can use the define_table method to define new tables. For example − db.define_table('invoice',Field('name')) The above method is also used among Table constructor. The syntax for the table constructor is the same. The first argument is the table name, and it is followed by a list of Field(s). The field constructor takes the following arguments − The field name Name of the field in table. The field type takes values having any of the datatypes such as string (default), text, boolean, integer and so on. Length Defines the maximum length. default = None This is the default value when a new record is inserted. update = None This works the same as default, but the value is used only on update, not on insert. Notnull This specifies whether the field value can be NULL or not. readable = True This specifies whether the field is readable in forms or not. writable = True This specifies whether the field is writable in forms or not. label = "Field Name" This is the label to be used for this field in forms. The define_table method also takes three named arguments − db.define_table('....',migrate=True, fake_migrate=False, format = '%(id)s') migrate = True − This instructs web2py to create the table if it does not exist, or alter it if it does not match the model definition. migrate = True − This instructs web2py to create the table if it does not exist, or alter it if it does not match the model definition. fake_migrate = False − If the model matches the database table content, then set fake_migrate = True which helps web2py to rebuild a data. fake_migrate = False − If the model matches the database table content, then set fake_migrate = True which helps web2py to rebuild a data. format = '%(id)s' − This is a format string that determines how records on the given table should be represented. format = '%(id)s' − This is a format string that determines how records on the given table should be represented. Using DAL, we can establish a connection to database and create new tables and their fields using the table constructor and field constructor. Sometimes, it is necessary to generate SQL statements to conform to the necessary output. web2py includes various functions, which help in generating raw SQL, which are given as follows − It helps in fetching insert statements for the given table. For example, print db.person._insert(name ='ABC') It will retrieve the insert statement for table named “person”. SQL statement output − INSERT INTO person(name) VALUES ('ABC'); It helps in fetching SQL statement, which gives the count of records. For example, consider a table named ‘person’ and we need to find the count of persons with name ‘ABC’. print db(db.person.name ==' ABC ')._count() SQL statement output − SELECT count(*) FROM person WHERE person.name = ' ABC '; It helps in fetching select SQL statements. For example, consider a table named ‘person’ and we need to find the list of persons with name ‘ABC’. print db(db.person.name == ' ABC ')._select() SQL statement output − SELECT person.name FROM person WHERE person.name = ' ABC '; It helps in fetching the delete SQL statements. For example, consider for table named ‘person’ and we need to delete the statements with name ‘ABC’ print db(db.person.name == ' ABC ')._delete() SQL statement output − DELETE FROM person WHERE person.name = ' ABC ';4 It helps in fetching updated SQL statements. For example, consider for table named ‘person’ and we need to update a column name with some other value print db(db.person.name == ' ABC ')._update() SQL statement output − UPDATE person SET WHERE person.name = ’Alex’; SQLite lacks the support of dropping or altering the columns. Deleting a field from the table keeps it active in the database, due to which web2py will not be aware of any changes made. In this case, it is necessary to set the fake_migrate = True which will help to redefine the metadata such that any changes such as alter or delete will be kept under the knowledge of web2py. SQLite does not support Boolean types. For this, web2py internally maps the Booleans to 1 character string, with 'T' and 'F' representing true and False respectively. MySQL does not support ALTER TABLE feature. Thus, migration of database involves multiple commits. This situation can be avoided by setting the parameter fake_migrate = True while defining the database, which will persist all the metadata. Oracle does not support the feature of pagination of records. It also lacks the support for the keywords OFFSET or limit. For this, web2py achieves pagination with the help of a complex three-way nested select of DAL. DAL needs to handle pagination on its own, if Oracle database has been used. web2py comes with powerful functions for form generation. Four distinct ways to build forms in web2py are as follows − FORM − In terms of HTML helpers, it is considered as a low-level implementation. A FORM object is aware of its field contents. FORM − In terms of HTML helpers, it is considered as a low-level implementation. A FORM object is aware of its field contents. SQLFORM − It provides the functionalities of Create, Update and Delete to the existing database. SQLFORM − It provides the functionalities of Create, Update and Delete to the existing database. SQLFORM.factory − It is considered as abstraction layer on the top of SQLFORM, which generates a form similar to SQLFORM. Here, there is no need to create a new database. SQLFORM.factory − It is considered as abstraction layer on the top of SQLFORM, which generates a form similar to SQLFORM. Here, there is no need to create a new database. CRUD Methods − As the name suggests, it provides Create, Retrieve, Update and Delete features with the similar functionalities based on SQLFORM. CRUD Methods − As the name suggests, it provides Create, Retrieve, Update and Delete features with the similar functionalities based on SQLFORM. Consider an application, which accepts an input from the user and has a “submit” button to submit the response. “default.py” controller will include the following associated function def display_form(): return dict() The associated view "default/display_form.html" will render the display of form in HTML as − {{extend 'layout.html'}} <h2>Basic Form</h2> <form enctype = "multipart/form-data" action = "{{= URL()}}" method = "post"> Your name: <input name = "name" /> <input type = "submit" /> </form> <h2>Submitted variables</h2> {{= BEAUTIFY(request.vars)}} The above example is the normal HTML form, which asks for the user input. The same form can be generated with the helpers like FORM object. def display_form(): form = FORM('Value:', INPUT(_value = 'name'), INPUT(_type = 'submit')) return dict(form = form) The above function in “default.py” controller includes FORM object (HTML helper) which helps in creation of form. {{extend 'layout.html'}} <h2>Basic form</h2> {{= form}} <h2>Submitted variables</h2> {{= BEAUTIFY(request.vars)}} He form which is generated by the statement {{= form}} serializes the FORM object. When a user fills the form and clicks on the submit button, the form self-submits, and the variable request.vars.value along with its input value is displayed at the bottom. It helps in creation of a form to the existing database. The steps for its implementation are discussed below. Establishing connection with database using DAL, this is created using DAL object which is also called DAL constructor. After establishing the connection, user can create the respective table. db = DAL('sqlite://storage.sqlite') db.define_table('employee', Field('name', requires = IS_NOT_EMPTY())) Thus, we have created a table named “employee”. The controller builds the form and button with the following statements − form = SQLFORM( db.mytable, record = mytable_index, deletable = True, submit_button = T('Update') ) Therefore, for the employee table created, the modification in the controller would be − def display_form(): form = SQLFORM(db.person) There is no modification in View. In the new controller, it is necessary build a FORM, since the SQLFORM constructor built one from the table db.employee is defined in the model. The new form, when serialized, appears as follows − <form enctype = "multipart/form-data" action = "" method = "post"> <table> <tr id = "employee_name__row"> <td> <label id = "person_name__label" for = "person_name">Your name: </label> </td> <td> <input type = "text" class = "string" name = "name" value = "" id = "employee_name" /> </td> <td></td> </tr> <tr id = "submit_record__row"> <td></td> <td><input value = "Submit" type = "submit" /></td> <td></td> </tr> </table> <input value = "9038845529" type = "hidden" name = "_formkey" /> <input value = "employee" type = "hidden" name = "_formname" /> </form> All tags in the form have names derived from the table and field name. An SQLFORM object also deals with "upload" fields by saving uploaded files in the "uploads" folder. This is done automatically. SQLFORM displays “Boolean” values in the form of checkboxes and text values with the help of “textareas”. SQLFORM also uses the process method.This is necessary if the user wants to keep values with an associated SQLFORM. If form.process(keepvalues = True) then it is accepted. def display_form(): form = SQLFORM(db.employee) if form.process().accepted: response.flash = 'form accepted' elif form.errors: response.flash = 'form has errors' else: response.flash = 'please fill out the form' return dict(form = form) Sometimes, the user needs to generate a form in a way that there is an existing database table without the implementation of the database. The user simply wants to take an advantage of the SQLFORM capability. This is done via form.factory and it is maintained in a session. def form_from_factory(): form = SQLFORM.factory( Field('your_name', requires = IS_NOT_EMPTY()), Field('your_image', 'upload')) if form.process().accepted: response.flash = 'form accepted' session.your_name = form.vars.your_name session.your_image = form.vars.your_image elif form.errors: response.flash = 'form has errors' return dict(form = form) The form will appear like SQLFORM with name and image as its fields, but there is no such existing table in database. The "default/form_from_factory.html" view will represent as − {{extend 'layout.html'}} {{= form}} CRUD is an API used on top of SQLFORM. As the name suggests, it is used for creation, retrieval, updating and deletion of appropriate form. CRUD, in comparison to other APIs in web2py, is not exposed; therefore, it is necessary that it should be imported. from gluon.tools import Crud crud = Crud(db) The CRUD object defined above provides the following API − crud.tables() Returns a list of tables defined in the database. crud.create(db.tablename) Returns a create form for the table tablename. crud.read(db.tablename, id) Returns a read-only form for tablename and record id. crud.delete(db.tablename, id) deletes the record crud.select(db.tablename, query) Returns a list of records selected from the table. crud.search(db.tablename) Returns a tuple (form, records) where form is a search form. crud() Returns one of the above based on the request.args(). Let us create a form. Follow the codes given below. A new model is created under the models folder of the application. The name of the file would be “dynamic_search.py”. def build_query(field, op, value): if op == 'equals': return field == value elif op == 'not equal': return field != value elif op == 'greater than': return field > value elif op == 'less than': return field < value elif op == 'starts with': return field.startswith(value) elif op == 'ends with': return field.endswith(value) elif op == 'contains': return field.contains(value) def dynamic_search(table): tbl = TABLE() selected = [] ops = ['equals', 'not equal', 'greater than', 'less than', 'starts with', 'ends with', 'contains'] query = table.id > 0 for field in table.fields: chkval = request.vars.get('chk'+field,None) txtval = request.vars.get('txt'+field,None) opval = request.vars.get('op'+field,None) row = TR(TD(INPUT(_type = "checkbox",_name = "chk"+field,value = chkval == 'on')), TD(field),TD(SELECT(ops,_name = "op"+field,value = opval)), TD(INPUT(_type = "text",_name = "txt"+field,_value = txtval))) tbl.append(row) if chkval: if txtval: query &= build_query(table[field], opval,txtval) selected.append(table[field]) form = FORM(tbl,INPUT(_type="submit")) results = db(query).select(*selected) return form, results The associated file namely “dynamic_search.py” under controllers section will include the following code − def index(): form,results = dynamic_search(db.things) return dict(form = form,results = results) We can render this with the following view. {{extend 'layout.html'}} {{= form}} {{= results}} Here is what it looks like − web2py includes functionalities of sending e-mail and SMS to the user. It uses libraries to send emails and sms. The in-built class namely gluon.tools.Mail class is used to send email in web2py framework. The mailer can be defined with this class. from gluon.tools import Mail mail = Mail() mail.settings.server = 'smtp.example.com:25' mail.settings.sender = '[email protected]' mail.settings.login = 'username:password' The sender email as mentioned in the above example along with the password will be authenticated each time when an email is sent. If the user needs to experiment or use for some debugging purpose, this can be achieved using the following code. mail.settings.server = 'logging' Now, all the emails will not be sent but it will be logged in the console. Once we have set the configuration settings for an email using mail object, an email can be sent to many users. The complete syntax of mail.send() is as follows − send( to, subject = 'Abc', message = 'None', attachments = [], cc = [], bcc = [], reply_to = [], sender = None, encoding = 'utf-8', raw = True, headers = {} ) The implementation of mail.send() is given below. mail.send( to = ['[email protected]'], subject = 'hello', reply_to = '[email protected]', message = 'Hello ! How are you?' ) Mail returns a Boolean expression based on the response of the mailing server, that the mail is received by the end user. It returns True if it succeeds in sending an email to the user. The attributes to, cc and bcc includes the list of valid email addresses for which the mail is intended to be sent. The implementation for sending SMS messages differs from sending emails in web2py framework as it will require third party service that can relay the messages to the receiver. The third party service is not a free service and will obviously differ based on geographical region (from country to country). web2py uses a module to help sending SMS with the following process − from gluon.contrib.sms_utils import SMSCODES, sms_email email = sms_email('1 (111) 111-1111','T-Mobile USA (abc)') mail.send(to = email, subject = 'test', message = 'test') In the above example, SMSCODES is the dictionary maintained by web2py that maps the names of the major phone companies to the email address postfix. Telephone companies usually treat emails originating from third party services as spam. A better method is that the phone companies themselves relay the SMS. Every phone company includes a unique email address for every mobile number in its storage and the SMS can be sent directly to the email. In the above example, The sms_email function takes a phone number (as a string), which returns the email address of the phone. The sms_email function takes a phone number (as a string), which returns the email address of the phone. The scaffolding app includes several files. One of them is models/db.py, which imports four. The scaffolding app includes several files. One of them is models/db.py, which imports four. Classes from gluon.tools include mail libraries as well and defines the various global objects. Classes from gluon.tools include mail libraries as well and defines the various global objects. The scaffolding application also defines tables required by the auth object, such as db.auth_user. The default scaffolding application is designed to minimize the number of files, not to be modular. In particular, the model file, db.py, contains the configuration, which in a production environment, is best kept in separate files. The scaffolding application also defines tables required by the auth object, such as db.auth_user. The default scaffolding application is designed to minimize the number of files, not to be modular. In particular, the model file, db.py, contains the configuration, which in a production environment, is best kept in separate files. Here, we suggest creating a configuration file − from gluon.storage import Storage settings = Storage() settings.production = False if settings.production: settings.db_uri = 'sqlite://production.sqlite' settings.migrate = False else: settings.db_uri = 'sqlite://development.sqlite' settings.migrate = True settings.title = request. settings.subtitle = 'write something here' settings.author = 'you' settings.author_email = '[email protected]' settings.keywords = '' settings.description = '' settings.layout_theme = 'Default' settings.security_key = 'a098c897-724b-4e05-b2d8-8ee993385ae6' settings.email_server = 'localhost' settings.email_sender = '[email protected]' settings.email_login = '' settings.login_method = 'local' settings.login_config = '' Almost every application needs to be able to authenticate users and set permissions. web2py comes with an extensive and customizable role-based access control mechanism.web2py. It also supports the protocols, such as CAS, OpenID, OAuth 1.0, LDAP, PAM, X509, and many more. web2py includes a mechanism known as Role Based Access Control mechanism (RBAC) which is an approach to restricting system access to authorized users. The web2py class that implements RBAC is called Auth. Look at the schema given below. Auth defines the following tables − auth_user stores users' name, email address, password, and status. auth_group stores groups or roles for users in a many-to-many structure auth_membership Stores the information of links users and groups in a many-to-many structure auth_permission The table links groups and permissions. auth_event logs changes in the other tables and successful access auth_cas It is used for Central Authentication Service There are two ways to customize Auth. To define a custom db.auth_user table from scratch. To define a custom db.auth_user table from scratch. Let web2py define the auth table. Let web2py define the auth table. Let us look at the last method of defining the auth table. In the db.py model, replace the following line − auth.define_tables() Replace it with the following code − auth.settings.extra_fields['auth_user'] = [ Field('phone_number',requires = IS_MATCH('\d{3}\-\d{3}\-\d{4}')), Field('address','text') ] auth.define_tables(username = True) The assumption is that each user consists of phone number, username and address. auth.settings.extra_fields is a dictionary of extra fields. The key is the name of the auth table to which to add the extra fields. The value is a list of extra fields. Here, we have added two extra fields, phone_number and address. username has to be treated in a special way, because it is involved in the authentication process, which is normally based on the email field. By passing the username argument to the following line, it is informed to web2py that we want the username field, and we want to use it for login instead of the email field. It acts like a primary key. auth.define_tables(username = True) The username is treated as a unique value. There may be cases when registration happens outside the normal registration form. It also happens so, that the new user is forced to login, to complete their registration. This can be done using a dummy field, complete_registration that is set to False by default, and is set to True when they update their profile. auth.settings.extra_fields['auth_user'] = [ Field('phone_number',requires = IS_MATCH('\d{3}\-\d{3}\-\d{4}'), comment = "i.e. 123-123-1234"), Field('address','text'), Field('complete_registration',default = False,update = True, writable = False, readable = False) ] auth.define_tables(username = True) This scenario may intend the new users, upon login, to complete their registration. In db.py, in the models folder, we can append the following code − if auth.user and not auth.user.complete_registration: if not (request.controller,request.function) == ('default','user'): redirect(URL('default','user/profile')) This will force the new users to edit their profile as per the requirements. It is the process of granting some access or giving permission of something to the users. In web2py once the new user is created or registered, a new group is created to contain the user. The role of the new user is conventionally termed as “user_[id]” where id is the unique identification of the user. The default value for the creation of the new group is − auth.settings.create_user_groups = "user_%(id)s" The creation of the groups among the users can be disabled by − auth.settings.create_user_groups = None Creation, granting access to particular members and permissions can be achieved programmatically with the help of appadmin also. Some of the implementations are listed as follows − auth.add_group('role', 'description') returns the id of the newly created group. auth.del_group(group_id) Deletes the group with the specified id auth.del_group(auth.id_group('user_7')) Deletes the user group with the given identification. auth.user_group(user_id) Returns the value of id of group uniquely associated for the given user. auth.add_membership(group_id, user_id) Returns the value of user_id for the given group_id auth.del_membership(group_id, user_id) Revokes access of the given member_id i.e. user_id from the given group. auth.has_membership(group_id, user_id, role) Checks whether user_id belongs to the given group. web2py provides an industry standard namely, Client Authentication Service – CAS for both client and server built-in web2py. It is a third party authentication tool. It is an open protocol for distributed authentication. The working of CAS is as follows − If the user visits the website, the protocol checks whether the user is authenticated. If the user visits the website, the protocol checks whether the user is authenticated. If the user is not authenticated to the application, the protocol redirects to the page where the user can register or log in to the application. If the user is not authenticated to the application, the protocol redirects to the page where the user can register or log in to the application. If the registration is completed, user receives an email. The registration is not complete until and unless user verifies the email. If the registration is completed, user receives an email. The registration is not complete until and unless user verifies the email. After successful registration, the user is authenticated with the key, which is used by CAS appliance. After successful registration, the user is authenticated with the key, which is used by CAS appliance. The key is used to get the credentials of user via HTTP request, which is set in the background. The key is used to get the credentials of user via HTTP request, which is set in the background. web2py provides support for various protocols like XML, JSON, RSS, CSV, XMLRPC, JSONRPC, AMFRPC, and SOAP. Each of those protocols is supported in multiple ways, and we make a distinction between − Rendering the output of a function in a given format. Remote Procedure Calls. Consider the following code which maintains the count of the sessions. def count(): session.counter = (session.counter or 0) + 1 return dict(counter = session.counter, now = request.now) The above function increases the number of counts as and when the user visits the page. Suppose the given function is defined in “default.py” controller of web2py application. The page can be requested with the following URL − http://127.0.0.1:8000/app/default/count web2py can render the above page in different protocols and by adding extension to the URL, like − http://127.0.0.1:8000/app/default/count.html http://127.0.0.1:8000/app/default/count.xml http://127.0.0.1:8000/app/default/count.json The dictionary returned by the above action will be rendered in HTML, XML and JSON. web2py framework provides a mechanism which converts a function into a web service. The mechanism described here differs from the mechanism described before because − Inclusion of arguments in function. The function must be defined in a model. It enforces a more strict URL naming convention. It works for a fixed set of protocols and it is easily extensible. To use this feature it is necessary to import and initiate a service object. To implement this mechanism, at first, you must import and instantiate a service object. from gluon.tools import Service service = Service() This is implemented in the "db.py" model file in the scaffolding application. Db.py model is the default model in web2py framework, which interacts with the database and the controller to achieve the desired output to the users. After implementing, the service in model can be accessed from the controllers as and when required. The following example shows various implementations of remote procedure calls using web services and many more. Web Services can be defined as a standardized way of integrating Web-based applications using the protocols like XML, SOAP, WSDL and UDDI. web2py supports most of them, but the integration will be quite tricky. There are many ways to return JSON form web2py, but here we consider the case of a JSON service. For example − def consumer():return dict()@service.json def get_days():return ["Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"] def call():return service() Here, we observe that − the function just returns an empty dictionary to render the view, which will consume the service. the function just returns an empty dictionary to render the view, which will consume the service. get_days defines the service, and the function call exposes all registered services. get_days defines the service, and the function call exposes all registered services. get_days does not need to be in the controller, and can be in a model. get_days does not need to be in the controller, and can be in a model. call is always in the default.py scaffolding controller. call is always in the default.py scaffolding controller. View with the consumer actions are as follows − {{extend 'layout.html'}} <div id = "target"></div> <script> jQuery.getJSON("{{= URL('call',args = ['json','get_days'])}}", function(msg){ jQuery.each(msg, function(){ jQuery("#target"). append(this + "<br />"); } ) } ); </script> The first argument of jQuery.getJSON is the URL of the following service − http://127.0.0.1:8000/app/default/call/json/get_days This always follows the pattern − http://<domain>/<app>/<controller>/call/<type>/<service> The URL is in between {{...}}, because it is resolved at the server-side, while everything else is executed at the client-side. The second argument of jQuery.getJSON is a callback, which will be passed the JSON response. In this case, the callback loops over each item in the response (a list of week days as strings), and appends each string, followed by a <br/> to the <div id = "target">. In this way, web2py manages implementation of web services using jQuery.getJSON. In this chapter, we will discuss examples of integration of jQuery plugins with web2py. These plugins help in making forms and tables more interactive and friendly to the user, thus improving the usability of your application. In particular, we will learn how to improve the multi-select drop-down with an interactive add option button, how to improve the multi-select drop-down with an interactive add option button, how to replace an input field with a slider, and how to replace an input field with a slider, and how to display tabular data using jqGrid and WebGrid. how to display tabular data using jqGrid and WebGrid. Although web2py is a server-side development component, the welcome scaffolding app includes the base jQuery library. This scaffolding web2py application "welcome" includes a file called views/web2py_ajax.html. The contents of the view are as follows − <script type = "text/javascript"><!-- // These variables are used by the web2py_ajax_init function in web2py_ajax.js (which is loaded below). var w2p_ajax_confirm_message = "{{= T('Are you sure you want to delete this object?')}}"; var w2p_ajax_disable_with_message = "{{= T('Working...')}}"; var w2p_ajax_date_format = "{{= T('%Y-%m-%d')}}"; var w2p_ajax_datetime_format = "{{= T('%Y-%m-%d %H:%M:%S')}}"; var ajax_error_500 = '{{=T.M('An error occured, please [[reload %s]] the page') % URL(args = request.args, vars = request.get_vars) }}' //--></script> {{ response.files.insert(0,URL('static','js/jquery.js')) response.files.insert(1,URL('static','css/calendar.css')) response.files.insert(2,URL('static','js/calendar.js')) response.files.insert(3,URL('static','js/web2py.js')) response.include_meta() response.include_files() }} The file consists of implementation of JavaScript and AJAX implementation. web2py will prevent the user from using other AJAX libraries such as Prototype, ExtJS, because it is always observed that it is easier to implement such libraries. The default rendering of <select multiple = "true">..</select> is considered not so intuitive to use, in particular, when it is necessary to select non-contiguous options. This can not be called as an HTML shortcoming, but a poor design of most of the browsers. The presentation of the multiple select can be overwritten using JavaScript. This can be implemented using jQuery plugin called jquery.multiselect.js. For this, a user should download the plugin jquery.muliselect.js from http://abeautifulsite.net/2008/04/jquery-multiselect, and place the corresponding files into static/js/jquery.multiselect.js and static/css/jquery.multiselect.css. The following code should be added in the corresponding view before {{extend ‘layout.html’}} {{ response.files.append('https://ajax.googleapis.com/ajax\ /libs/jqueryui/1.8.9/jquery-ui.js') response.files.append('https://ajax.googleapis.com/ajax\ /libs/jqueryui/1.8.9/themes/ui-darkness/jquery-ui.css') response.files.append(URL('static','js/jquery.multiSelect.js')) response.files.append(URL('static','css/jquery.\multiSelect.css')) }} Place the following after {{extend 'layout.html'}} − <script> jQuery(document).ready(function(){jQuery('[multiple]').multiSelect();}); </script> This will help to style multiselect for the given form def index(): is_fruits = IS_IN_SET(['Apples','Oranges','Bananas','Kiwis','Lemons'], multiple = True) form = SQLFORM.factory(Field('fruits','list:string', requires = is_fruits)) if form.accepts(request,session):response.flash = 'Yummy!' return dict(form = form) This action can be tried with the following view − {{ response.files.append('https://ajax.googleapis.com/ajax\ /libs/jqueryui/1.8.9/jquery-ui.js') response.files.append('https://ajax.googleapis.com/ajax\ /libs/jqueryui/1.8.9/themes/ui-darkness/jquery-ui.css') response.files.append(URL('static','js/jquery.multiSelect.js')) response.files.append(URL('static','css/jquery.\multiSelect.css')) }} {{extend 'layout.html}} <script> jQuery(document).ready(function(){jQuery('[multiple]'). multiSelect();}); </script> {{= form}} The screenshot of the output is as follows − Some of the useful Jquery events are listed in the following table − onchange to be run when the element changes onsubmit to be run when the form is submitted onselect to be run when the element is selected onblur to be run when the element loses focus onfocus to be run when the element gets focus jqGrid is an Ajax-enabled JavaScript control built on jQuery that provides a solution for representing and manipulating tabular data. jqGrid is a client-side solution, and it loads data dynamically through Ajax callbacks, thus providing pagination, search popup, inline editing, and so on. jqGrid is integrated into PluginWiki, but, here, we discuss it as a standalone for web2py programs that do not use the plugin. jqGrid deserves a book of its own but here we will only discuss its basic features and simplest integration. The syntax of jqGrid will be as follows − def JQGRID( table, fieldname = None, fieldvalue = None, col_widths = [], colnames = [], _id = None, fields = [], col_width = 80, width = 700, height = 300, dbname = 'db' ): A component is defined as the functional part of a web page, which works autonomously. It can be composed of modules, controllers and views, which are embedded in a web page. The component in an application, must be localized tag and the performance is considered to be independent of module. In web2py, the main focus is on using components that are loaded in page and which communicate with the component controller via AJAX. web2py includes a function, which is called the LOAD function, which makes implementation of components easy without explicit JavaScript or AJAX programming. Consider a simple web application namely “test” that extends the web2py application with custom model in file “models/db_comments.py”. db.define_table( 'comment_post', Field('body','text', label = 'Your comment'),auth.signature ) The above code will create a table “comment_post” with the proper table definition. The action will be implemented with the help of functions in “controllers/comments.py”. def post(): return dict( form = SQLFORM(db.comment_post).process(), comments = db(db.comment_post).select() ) The corresponding view will be displayed as − {{extend 'layout.html'}} {{for post in comments:}} <div class = "post"> On {{= post.created_on}} {{= post.created_by.first_name}} says <span class = "post_body">{{= post.body}}</span> </div> {{pass}} {{= form}} The page can be accessed using the given URL − http://127.0.0.1:8000/test/comments/post The method mentioned above is a traditional way of accessing a view, which can be changed with the implementation of the LOAD function. This can be achieved by creating a new view with the extension ".load" that does not extend the layout. The new view created would be "views/comments/post.load" − <div class = "post"> On {{= post.created_on}} {{= post.created_by.first_name}} says <blockquote class = "post_body">{{= post.body}}</blockquote> </div> {{pass}} {{= form}} The URL to access the page would be − http://127.0.0.1:8000/test/comments/post.load The LOAD component can be embedded into any other page of web2py application. This can be done by using the following statement. {{= LOAD('comments','post.load',ajax = True)}} For example, the Controllers can be edited as − def index(): return dict() In View, we can add the component − {{extend 'layout.html'}} {{= LOAD('comments','post.load',ajax = True)}} The page can be accessed with the URL − http://127.0.0.1:8000/test/default/index Component plugins are the plugins, which uniquely define Components. Components access the database directly with their model definition. As mentioned in the previous example, comments component into a comments_plugin can be done in the Models section − "models/plugin_comments.py" − db.define_table( 'plugin_comments_comment', Field('body','text', label = 'Your comment'), auth.signature ) The Controller will include the following plugin − def plugin_comments(): return LOAD('plugin_comments','post',ajax = True) The following steps are implemented for installation of web2py in the Ubuntu Desktop. Step 1 − Download web2py cd /home mkdir www-dev cd www-dev wget http://www.web2py.com/examples/static/web2py_src.zip Step 2 − After the download is complete, unzip it. unzip -x web2py_src.zip Step 3 − Optionally install the tk library for Python, if you need to access the GUI. sudo apt-get install python-tk Step 4 − To start web2py, access the web2py directory and run web2py. cd web2py python web2py.py The GUI will appear as follows − After installation, each time you run it, web2py will ask you to choose a password. This password is your administrative password. If the password is left blank, the administrative interface will be disabled. Once the server is started, web2py will redirect to the screen with following mentioned URL − http://127.0.0.1:8000/ This will conclude that web2py is perfectly running in Ubuntu desktop. Step 1 − Installation of all the modules needed to run web2py. sudo apt-get install postgresql sudo apt-get install unzip sudo apt-get install openssh-server sudo apt-get install apache2 sudo apt-get install libapache2-mod-wsgi Step 2 − Installation of web2py in /home/www-data This helps for proper deployment in production environment. sudo apt-get install unzip sudo apt-get install openssh-server cd /home sudo mkdir www-data cd www-data Get the web2py source from the web2py site − sudo wget http://web2py.com/examples/static/web2py_src.zip sudo unzip web2py_src.zip sudo chown -R www-data:www-data web2py Step 3 − Create a self-signed certificate. SSL certificates should be obtained from a trusted Certificate Authority. Maintain an SSL folder with the certificates in it. Step 4 − Edit the apache configuration as per the requirement of production environment. Step 5 − Restart the Apache server and verify if the production environment works for the given IP address. Although there is a binary distribution for Windows environments (packaging executables and standard libraries), web2py is open source, and can be used with a normal Python installation. This method allows working with the latest releases of web2py, and customizing the python modules to be used. Step 1 − Download the source package from web2py official website − http://www.web2py.com/examples/static/web2py_src.zip and unzip it. As web2py does not require installation, the user can unzip it in any folder. Step 2 − To start it, double-click web2py.py. From the console − cd c:\web2py c:\python27\python.exe web2py.py Step 3 − Here command line parameters can be added (−a to set an admin password, −p to specify an alternate port). The startup options are visible through − C:\web2py>c:\python27\python.exe web2py.py --help web2py is written in Python, a portable, interpreted and dynamic language that does not require compilation or complicated installation to run. web2py is written in Python, a portable, interpreted and dynamic language that does not require compilation or complicated installation to run. It uses a virtual machine (such as Java and .Net), and it can transparently byte-compile your source code on the fly when you run your scripts. It uses a virtual machine (such as Java and .Net), and it can transparently byte-compile your source code on the fly when you run your scripts. It is a software called SQLDesigner which helps in making web2py models and generates the corresponding code. Given below are some of the screenshots − SQLDesigner helps in maintaining the relations of the tables in simple manner and generates the corresponding code in the models of given application. Functional testing involves testing of the functions of components or overall system. It can be based on requirement and business process. web2py comes with a module gluon.contrib.webclient, which performs functional testing in remote and local web2py applications. It is basically designed to understand web2py session and postbacks. All it requires is to import the package such that the functional testing would be implemented on the given module. The syntax to import the package is as follows − from gluon.contrib.webclient import WebClient In the previous chapters, there was complete information on the implementation of web2py with various tools. The major concern for developing web2py applications includes security from a user’s perspective. The unique features of web2py are as follows − Users can learn the implementation easily. It requires no installation and dependencies. Users can learn the implementation easily. It requires no installation and dependencies. It has been stable since the day of launch. It has been stable since the day of launch. web2py is lightweight and includes libraries for Data Abstraction Layer and template language. web2py is lightweight and includes libraries for Data Abstraction Layer and template language. It works with the help of Web Server Gateway Interface, which acts as a communication between web servers and applications. It works with the help of Web Server Gateway Interface, which acts as a communication between web servers and applications. Open web application security project (OWASP) is a community, which lists down the security breaches of web application. With respect to OWASP, issues related to web applications and how web2py overcomes them is discussed below. It is also known as XSS. It occurs whenever an application takes a user supplied data and sends it to the user’s browser without encoding or validating the content. The attackers execute scripts to inject worms and viruses using cross side scripting. web2py helps in preventing XSS by preventing all the rendered variables in the View. Sometimes, applications leak information about internal workings, privacy and configurations. Attackers use this to breach sensitive data, which could lead to serious attacks. web2py prevents this by ticketing system. It logs all the errors and the ticket is issued to the user whose error is being registered. These errors are only accessible to the administrator. Account credentials are not often protected. Attackers compromise on passwords, authentication tokens to steal the user’s identities. web2py provides a mechanism for administrative interface. It also forces to use secure sessions when the client is not “localhost”. Sometimes applications fail to encrypt the network traffic. It is necessary to manage traffic to protect sensitive communications. web2py provides SSL enabled certificates to provide encryption of communications. This also helps to maintain sensitive communication. Web applications normally protect the sensitive functionality by preventing display of the links and URLs to some users. Attackers can try to breach some sensitive data by manipulating the URL with some information. In wb2py, a URL maps to the modules and functions rather than the given file. It also includes a mechanism, which specifies which functions are public and which are maintained as private. This helps in resolving the issue. Print Add Notes Bookmark this page
[ { "code": null, "e": 2209, "s": 1893, "text": "web2py is defined as a free, open-source web framework for agile development which involves database-driven web applications; it is written in Python and programmable in Python. It is a full-stack framework; it consists of all the necessary components, a developer needs to build a fully functional web application." }, { "code": null, "e": 2325, "s": 2209, "text": "web2py framework follows the Model-View-Controller pattern of running web applications unlike traditional patterns." }, { "code": null, "e": 2479, "s": 2325, "text": "Model is a part of the application that includes logic for the data. The objects in model are used for retrieving and storing the data from the database." }, { "code": null, "e": 2633, "s": 2479, "text": "Model is a part of the application that includes logic for the data. The objects in model are used for retrieving and storing the data from the database." }, { "code": null, "e": 2770, "s": 2633, "text": "View is a part of the application, which helps in rendering the display of data to end users. The display of data is fetched from Model." }, { "code": null, "e": 2907, "s": 2770, "text": "View is a part of the application, which helps in rendering the display of data to end users. The display of data is fetched from Model." }, { "code": null, "e": 3082, "s": 2907, "text": "Controller is a part of the application, which handles user interaction. Controllers can read data from a view, control user input, and send input data to the specific model." }, { "code": null, "e": 3257, "s": 3082, "text": "Controller is a part of the application, which handles user interaction. Controllers can read data from a view, control user input, and send input data to the specific model." }, { "code": null, "e": 3413, "s": 3257, "text": "web2py has an in-built feature to manage cookies and sessions. After committing a transaction (in terms of SQL), the session is also stored simultaneously." }, { "code": null, "e": 3569, "s": 3413, "text": "web2py has an in-built feature to manage cookies and sessions. After committing a transaction (in terms of SQL), the session is also stored simultaneously." }, { "code": null, "e": 3710, "s": 3569, "text": "web2py has the capacity of running the tasks in scheduled intervals after the completion of certain actions. This can be achieved with CRON." }, { "code": null, "e": 3851, "s": 3710, "text": "web2py has the capacity of running the tasks in scheduled intervals after the completion of certain actions. This can be achieved with CRON." }, { "code": null, "e": 3900, "s": 3851, "text": "Take a look at the workflow diagram given below." }, { "code": null, "e": 3941, "s": 3900, "text": "The workflow diagram is described below." }, { "code": null, "e": 4022, "s": 3941, "text": "The Models, Views and Controller components make up the user web2py application." }, { "code": null, "e": 4103, "s": 4022, "text": "The Models, Views and Controller components make up the user web2py application." }, { "code": null, "e": 4171, "s": 4103, "text": "Multiple applications can be hosted in the same instance of web2py." }, { "code": null, "e": 4239, "s": 4171, "text": "Multiple applications can be hosted in the same instance of web2py." }, { "code": null, "e": 4376, "s": 4239, "text": "The browser sends the HTTP request to the server and the server interacts with Model, Controller and View to fetch the necessary output." }, { "code": null, "e": 4513, "s": 4376, "text": "The browser sends the HTTP request to the server and the server interacts with Model, Controller and View to fetch the necessary output." }, { "code": null, "e": 4792, "s": 4513, "text": "The arrows represent communication with the database engine(s). The database queries can be written in raw SQL or by using the web2py Database Abstraction Layer (which will be discussed in further chapters), so that web2py application code is independent of any database engine." }, { "code": null, "e": 5071, "s": 4792, "text": "The arrows represent communication with the database engine(s). The database queries can be written in raw SQL or by using the web2py Database Abstraction Layer (which will be discussed in further chapters), so that web2py application code is independent of any database engine." }, { "code": null, "e": 5254, "s": 5071, "text": "Model establishes the database connection with the database and interacts with the Controller. The Controller on the other hand interacts with the View to render the display of data." }, { "code": null, "e": 5437, "s": 5254, "text": "Model establishes the database connection with the database and interacts with the Controller. The Controller on the other hand interacts with the View to render the display of data." }, { "code": null, "e": 5599, "s": 5437, "text": "The Dispatcher maps the requested URL as given in HTTP response to a function call in the controller. The output of the function can be a string or a hash table." }, { "code": null, "e": 5761, "s": 5599, "text": "The Dispatcher maps the requested URL as given in HTTP response to a function call in the controller. The output of the function can be a string or a hash table." }, { "code": null, "e": 5994, "s": 5761, "text": "The data is rendered by the View. If the user requests an HTML page (the default), the data is rendered into an HTML page. If the user requests the same page in XML, web2py tries to find a view that can render the dictionary in XML." }, { "code": null, "e": 6227, "s": 5994, "text": "The data is rendered by the View. If the user requests an HTML page (the default), the data is rendered into an HTML page. If the user requests the same page in XML, web2py tries to find a view that can render the dictionary in XML." }, { "code": null, "e": 6305, "s": 6227, "text": "The supported protocols of web2py include HTML, XML, JSON, RSS, CSV, and RTF." }, { "code": null, "e": 6383, "s": 6305, "text": "The supported protocols of web2py include HTML, XML, JSON, RSS, CSV, and RTF." }, { "code": null, "e": 6450, "s": 6383, "text": "The model-view-controller representation of web2py is as follows −" }, { "code": null, "e": 6566, "s": 6450, "text": "\"db.py\" is the model:\ndb = DAL('sqlite://storage.sqlite')\ndb.define_table(employee, Field('name'), Field(‘phone’))\n" }, { "code": null, "e": 6855, "s": 6566, "text": "The Model includes the logic of application data. It connects to the database as mentioned in the figure above. Consider SQLite is being used and is stored in storage.sqlite file with a table defined as employee. If the table does not exist, web2py helps by creating the respective table." }, { "code": null, "e": 6899, "s": 6855, "text": "The program \"default.py\" is the Controller." }, { "code": null, "e": 6994, "s": 6899, "text": "def employees():\n grid = SQLFORM.grid(db.contact, user_signature = False)\n return locals()" }, { "code": null, "e": 7160, "s": 6994, "text": "In web2py, URL mapping helps in accessing the functions and modules. For the above example, the Controller contains a single function (or \"action\") called employees." }, { "code": null, "e": 7312, "s": 7160, "text": "The action taken by the Controller returns a string or a Python dictionary, which is a combination of key and value including a local set of variables." }, { "code": null, "e": 7349, "s": 7312, "text": "\"default/contacts.html\" is the View." }, { "code": null, "e": 7413, "s": 7349, "text": "{{extend 'layout.html'}}\n<h1>Manage My Employees</h1>\n{{=grid}}" }, { "code": null, "e": 7515, "s": 7413, "text": "For the given example, View displays the output after the associated controller function is executed." }, { "code": null, "e": 7715, "s": 7515, "text": "The purpose of this View is to render the variables in the dictionary, which is in the form of HTML. The View file is written in HTML, but it embeds Python code with the help of {{ and }} delimiters." }, { "code": null, "e": 7786, "s": 7715, "text": "The code embedded into HTML consists of Python code in the dictionary." }, { "code": null, "e": 7887, "s": 7786, "text": "web2py comes in binary packages for all the major operating systems like Windows, UNIX and Mac OS X." }, { "code": null, "e": 7926, "s": 7887, "text": "It is easy to install web2py because −" }, { "code": null, "e": 8087, "s": 7926, "text": "It comprises of the Python interpreter, so you do not need to have it pre-installed. There is also a source code version that runs on all the operating systems." }, { "code": null, "e": 8248, "s": 8087, "text": "It comprises of the Python interpreter, so you do not need to have it pre-installed. There is also a source code version that runs on all the operating systems." }, { "code": null, "e": 8363, "s": 8248, "text": "The following link comprises of the binary packages of web2py for download as per the user’s need − www.web2py.com" }, { "code": null, "e": 8478, "s": 8363, "text": "The following link comprises of the binary packages of web2py for download as per the user’s need − www.web2py.com" }, { "code": null, "e": 8644, "s": 8478, "text": "The web2py framework requires no pre-installation unlike other frameworks. The user needs to download the zip file and unzip as per the operating system requirement." }, { "code": null, "e": 8810, "s": 8644, "text": "The web2py framework requires no pre-installation unlike other frameworks. The user needs to download the zip file and unzip as per the operating system requirement." }, { "code": null, "e": 8964, "s": 8810, "text": "The web2py framework is written in Python, which is a complete dynamic language that does not require any compilation or complicated installation to run." }, { "code": null, "e": 9118, "s": 8964, "text": "The web2py framework is written in Python, which is a complete dynamic language that does not require any compilation or complicated installation to run." }, { "code": null, "e": 9279, "s": 9118, "text": "It uses a virtual machine like other programming languages such as Java or .net and it can transparently byte-compile the source code written by the developers." }, { "code": null, "e": 9440, "s": 9279, "text": "It uses a virtual machine like other programming languages such as Java or .net and it can transparently byte-compile the source code written by the developers." }, { "code": null, "e": 9608, "s": 9440, "text": "Python can be defined as a combination of object-oriented and interactive language. It is an open source software. Guido van Rossum conceived python in the late 1980s." }, { "code": null, "e": 9765, "s": 9608, "text": "Python is a language similar to PERL (Practical Extraction and Reporting Language), which has gained popularity because of its clear syntax and readability." }, { "code": null, "e": 9818, "s": 9765, "text": "The main notable features of Python are as follows −" }, { "code": null, "e": 10038, "s": 9818, "text": "Python is said to be relatively easy to learn and portable. Its statements can be easily interpreted in a number of operating systems, including UNIX-based systems, Mac OS, MS-DOS, OS/2, and various versions of Windows." }, { "code": null, "e": 10258, "s": 10038, "text": "Python is said to be relatively easy to learn and portable. Its statements can be easily interpreted in a number of operating systems, including UNIX-based systems, Mac OS, MS-DOS, OS/2, and various versions of Windows." }, { "code": null, "e": 10399, "s": 10258, "text": "Python is portable with all the major operating systems. It uses an easy to understand syntax, making the programs, which are user friendly." }, { "code": null, "e": 10540, "s": 10399, "text": "Python is portable with all the major operating systems. It uses an easy to understand syntax, making the programs, which are user friendly." }, { "code": null, "e": 10605, "s": 10540, "text": "It comes with a large standard library that supports many tasks." }, { "code": null, "e": 10670, "s": 10605, "text": "It comes with a large standard library that supports many tasks." }, { "code": null, "e": 10861, "s": 10670, "text": "From the above diagram, it is clearly visible that Python is a combination of scripting as well as programming language. They are interpreted within another program like scripting languages." }, { "code": null, "e": 11012, "s": 10861, "text": "Python has three production-quality implementations, which are called as CPython, Jython, and IronPython. These are also termed as versions of Python." }, { "code": null, "e": 11169, "s": 11012, "text": "Classic Python a.k.a CPython is a compiler, interpreter and consists of built-in and optional extension modules which is implemented in standard C language." }, { "code": null, "e": 11326, "s": 11169, "text": "Classic Python a.k.a CPython is a compiler, interpreter and consists of built-in and optional extension modules which is implemented in standard C language." }, { "code": null, "e": 11392, "s": 11326, "text": "Jython is a Python implementation for Java Virtual Machine (JVM)." }, { "code": null, "e": 11458, "s": 11392, "text": "Jython is a Python implementation for Java Virtual Machine (JVM)." }, { "code": null, "e": 11570, "s": 11458, "text": "IronPython is designed by Microsoft, which includes Common Language Runtime (CLR). It is commonly known as .NET" }, { "code": null, "e": 11682, "s": 11570, "text": "IronPython is designed by Microsoft, which includes Common Language Runtime (CLR). It is commonly known as .NET" }, { "code": null, "e": 11847, "s": 11682, "text": "A basic Python program in any operating system starts with a header. The programs are stored with .py extension and Python command is used for running the programs." }, { "code": null, "e": 11958, "s": 11847, "text": "For example, python_rstprogram.py will give you the required output. It will also generate errors, if present." }, { "code": null, "e": 12166, "s": 11958, "text": "Python uses indentation to delimit blocks of code. A block starts with a line ending with colon, and continues for all lines in the similar fashion that have a similar or higher indentation as the next line." }, { "code": null, "e": 12221, "s": 12166, "text": "# Basic program in Python\nprint \"Welcome to Python!\\n\"" }, { "code": null, "e": 12257, "s": 12221, "text": "The output of the program will be −" }, { "code": null, "e": 12277, "s": 12257, "text": "Welcome to Python!\n" }, { "code": null, "e": 12454, "s": 12277, "text": "Indentations of the programs are quite important in Python. There are some prejudices and myths about Python's indentation rules for the developers who are beginners to Python." }, { "code": null, "e": 12498, "s": 12454, "text": "The thumb rule for all the programmers is −" }, { "code": null, "e": 12634, "s": 12498, "text": "Leading whitespace, which includes spaces and tabs at the beginning of a logical line of Python computes the indentation level of line." }, { "code": null, "e": 12704, "s": 12634, "text": "The indentation level also determines the grouping of the statements." }, { "code": null, "e": 12774, "s": 12704, "text": "The indentation level also determines the grouping of the statements." }, { "code": null, "e": 12846, "s": 12774, "text": "It is common to use four spaces i.e. tab for each level of indentation." }, { "code": null, "e": 12918, "s": 12846, "text": "It is common to use four spaces i.e. tab for each level of indentation." }, { "code": null, "e": 13018, "s": 12918, "text": "It is a good policy not to mix tabs with spaces, which can result in confusion, which is invisible." }, { "code": null, "e": 13118, "s": 13018, "text": "It is a good policy not to mix tabs with spaces, which can result in confusion, which is invisible." }, { "code": null, "e": 13194, "s": 13118, "text": "Python also generates a compile time error if there is lack of indentation." }, { "code": null, "e": 13240, "s": 13194, "text": "IndentationError: expected an indented block\n" }, { "code": null, "e": 13343, "s": 13240, "text": "The control flow of a Python program is regulated by conditional statements, loops and function calls." }, { "code": null, "e": 13465, "s": 13343, "text": "The If statement, executes a block of code under specified condition, along with else and elif(a combination of else-if)." }, { "code": null, "e": 13587, "s": 13465, "text": "The If statement, executes a block of code under specified condition, along with else and elif(a combination of else-if)." }, { "code": null, "e": 13705, "s": 13587, "text": "The For statement, iterates over an object, capturing each element to a local variable for use by the attached block." }, { "code": null, "e": 13823, "s": 13705, "text": "The For statement, iterates over an object, capturing each element to a local variable for use by the attached block." }, { "code": null, "e": 13905, "s": 13823, "text": "The While statement, executes a block of code under the condition, which is True." }, { "code": null, "e": 13987, "s": 13905, "text": "The While statement, executes a block of code under the condition, which is True." }, { "code": null, "e": 14136, "s": 13987, "text": "The With statement, encloses a code block within the context manager. It has been added as a more readable alternative to the try/finally statement." }, { "code": null, "e": 14285, "s": 14136, "text": "The With statement, encloses a code block within the context manager. It has been added as a more readable alternative to the try/finally statement." }, { "code": null, "e": 14537, "s": 14285, "text": "# If statement in Python\n x = int(raw_input(\"Please enter an integer: \")) #Taking input from the user\nif x<0:\n print \"1 - Got a negative expression value\"\n print x\nelse:\n print \"1 - Got a positive expression value\"\n print x\nprint \"Good bye!\"" }, { "code": null, "e": 14636, "s": 14537, "text": "sh-4.3$ python main.py\nPlease enter an integer: 4\n1 - Got a positive expression value\n4\nGood bye!\n" }, { "code": null, "e": 14924, "s": 14636, "text": "The statements in a typical Python program are organized and grouped in a particular format called, “Functions\". A function is a group of statements that perform an action based on the request. Python provides many built-in functions and allows programmers to define their own functions." }, { "code": null, "e": 15018, "s": 14924, "text": "In Python, functions are values that are handled like other objects in programming languages." }, { "code": null, "e": 15151, "s": 15018, "text": "The def statement is the most common way to define a function. def is a single-clause compound statement with the following syntax −" }, { "code": null, "e": 15196, "s": 15151, "text": "def function-name (parameters):statement(s)\n" }, { "code": null, "e": 15335, "s": 15196, "text": "The following example demonstrates a generator function. It can be used as an iterable object, which creates its objects in a similar way." }, { "code": null, "e": 15418, "s": 15335, "text": "def demo ():\n for i in range(5):\n yield (i*i)\n\t\nfor j in demo():\n print j" }, { "code": null, "e": 15453, "s": 15418, "text": "sh-4.3$ python main.py\n0\n1\n4\n9\n16\n" }, { "code": null, "e": 15637, "s": 15453, "text": "The attributes, methods, and operators starting with double underscore of a class are usually private in behavior. Some of them are reserved keywords, which include a special meaning." }, { "code": null, "e": 15670, "s": 15637, "text": "Three of them are listed below −" }, { "code": null, "e": 15678, "s": 15670, "text": "__len__" }, { "code": null, "e": 15686, "s": 15678, "text": "__len__" }, { "code": null, "e": 15698, "s": 15686, "text": "__getitem__" }, { "code": null, "e": 15710, "s": 15698, "text": "__getitem__" }, { "code": null, "e": 15722, "s": 15710, "text": "__setitem__" }, { "code": null, "e": 15734, "s": 15722, "text": "__setitem__" }, { "code": null, "e": 15855, "s": 15734, "text": "The other special operators include __getattr__ and __setattr__, which defines the get and set attributes for the class." }, { "code": null, "e": 16000, "s": 15855, "text": "Python includes a functionality to open and close particular files. This can be achieved with the help of open(), write() and close() functions." }, { "code": null, "e": 16066, "s": 16000, "text": "The commands which help in file input and output are as follows −" }, { "code": null, "e": 16073, "s": 16066, "text": "open()" }, { "code": null, "e": 16112, "s": 16073, "text": "It helps in opening a file or document" }, { "code": null, "e": 16120, "s": 16112, "text": "write()" }, { "code": null, "e": 16167, "s": 16120, "text": "It helps to write a string in file or document" }, { "code": null, "e": 16174, "s": 16167, "text": "read()" }, { "code": null, "e": 16223, "s": 16174, "text": "It helps in reading the content in existing file" }, { "code": null, "e": 16231, "s": 16223, "text": "close()" }, { "code": null, "e": 16267, "s": 16231, "text": "This method closes the file object." }, { "code": null, "e": 16357, "s": 16267, "text": "Consider a file named “demo.txt”, which already exists with a text “This is a demo file”." }, { "code": null, "e": 16482, "s": 16357, "text": "#!/usr/bin/python\n# Open a file\nfo = open(\"demo.txt\", \"wb\")\nfo.write( \"Insering new line \\n\");\n# Close opend file\nfo.close()" }, { "code": null, "e": 16536, "s": 16482, "text": "The string available after opening the file will be −" }, { "code": null, "e": 16578, "s": 16536, "text": "This is a demo file\nInserting a new line\n" }, { "code": null, "e": 16780, "s": 16578, "text": "web2py is a full-stack web framework that can be used by a developer to completely develop a web application. It includes SQL database integration and multi-threaded web server for designing a program." }, { "code": null, "e": 16933, "s": 16780, "text": "Once the command is executed as per the operating system, web2py displays a startup window and then displays a GUI widget that asks the user to choose −" }, { "code": null, "e": 16968, "s": 16933, "text": "a one-time administrator password," }, { "code": null, "e": 17039, "s": 16968, "text": "the IP address of the network interface to be used for the web server," }, { "code": null, "e": 17087, "s": 17039, "text": "and a port number from which to serve requests." }, { "code": null, "e": 17182, "s": 17087, "text": "The administrator includes all the authority for addition and editing any new web application." }, { "code": null, "e": 17347, "s": 17182, "text": "By default, web2py runs its web server on 127.0.0.1:8000 (port 8000 on localhost) but a user can run it on any available IP address and port as per the requirement." }, { "code": null, "e": 17403, "s": 17347, "text": "The web2py GUI widget will be displayed as shown below." }, { "code": null, "e": 17491, "s": 17403, "text": "The password is used in the administrative interface for any changes in the new module." }, { "code": null, "e": 17636, "s": 17491, "text": "After the user has set the administration password, web2py starts up the web browser at the page with the following URL − http://127.0.0.1:8000/" }, { "code": null, "e": 17704, "s": 17636, "text": "The welcome page of the framework will be displayed as shown below." }, { "code": null, "e": 17867, "s": 17704, "text": "After starting the web2py application, with the above-mentioned URL, we can use the administrative interface for creating a new module, for example, “helloWorld”." }, { "code": null, "e": 18044, "s": 17867, "text": "The administrative interface will ask for the password for authentication purpose as the administrator holds all the authority for addition and editing any new web application." }, { "code": null, "e": 18266, "s": 18044, "text": "The snapshot given above includes the page details, which lists all the installed web2py applications and allows the administrator to manage them. By default, the web2py framework comes with three applications. They are −" }, { "code": null, "e": 18330, "s": 18266, "text": "An admin application, which the user is implementing currently." }, { "code": null, "e": 18394, "s": 18330, "text": "An admin application, which the user is implementing currently." }, { "code": null, "e": 18509, "s": 18394, "text": "An examples application, with the online interactive documentation and an instance of the web2py official website." }, { "code": null, "e": 18624, "s": 18509, "text": "An examples application, with the online interactive documentation and an instance of the web2py official website." }, { "code": null, "e": 18814, "s": 18624, "text": "A welcome application. It includes the basic template for any other web2py application. It is also known as the scaffolding application. The application also welcomes a user at the startup." }, { "code": null, "e": 19004, "s": 18814, "text": "A welcome application. It includes the basic template for any other web2py application. It is also known as the scaffolding application. The application also welcomes a user at the startup." }, { "code": null, "e": 19057, "s": 19004, "text": "Let the name of the new application be “helloWorld”." }, { "code": null, "e": 19199, "s": 19057, "text": "Once, a new application is created, the user is redirected to a page comprising of view, model and controllers of the respective application." }, { "code": null, "e": 19317, "s": 19199, "text": "The user can look at the newly created application by mentioning the following URL − http://127.0.0.1:8000/helloWorld" }, { "code": null, "e": 19402, "s": 19317, "text": "By default, a user can view the following screen on hitting the above-mentioned URL." }, { "code": null, "e": 19519, "s": 19402, "text": "For printing the message of the given web application “helloWorld”, the change is made in the default.py controller." }, { "code": null, "e": 19783, "s": 19519, "text": "The function named “index” is the default function for returning the value and displaying the necessary output. As mentioned above, the string “Hello World- Welcome to my first web application” is used as the return value, which displays the output in the screen." }, { "code": null, "e": 19820, "s": 19783, "text": "The output is displayed as follows −" }, { "code": null, "e": 20008, "s": 19820, "text": "The mechanism of validating the input of form is very common and is not considered as such a good programming practice. The input is validated each time, which is a burden for validation." }, { "code": null, "e": 20223, "s": 20008, "text": "A better pattern in web2py is to submit forms to the same action, which generates them. This mechanism is called as “postback” which is the main feature of web2py. In short, self-submission is achieved in postback." }, { "code": null, "e": 20419, "s": 20223, "text": "def first():\n if request.vars.visitor_name: #if visitor name exists\n session.visitor_name = request.vars.visitor_name\n redirect(URL('second'))#postback is implemented\n return dict()" }, { "code": null, "e": 20602, "s": 20419, "text": "web2py includes applications, which perform the functions of Create, retrieve, update and delete. The CRUD cycle describes the elemental functions of a database, which is persistent." }, { "code": null, "e": 20743, "s": 20602, "text": "All the application logic is written in the models, which are retrieved by the controllers and displayed to the users with the help of view." }, { "code": null, "e": 20966, "s": 20743, "text": "For PHP, the application server includes listing of all the databases under phpmyadmin. In a similar way, web2py provides an interface for managing, creating and deleting tables or databases, which is termed as “appadmin.”" }, { "code": null, "e": 21077, "s": 20966, "text": "Before implementing the logic behind the tables, it is necessary to create database and its associated tables." }, { "code": null, "e": 21106, "s": 21077, "text": "The URL to access appadmin −" }, { "code": null, "e": 21153, "s": 21106, "text": "http://127.0.0.1:8000/applicationname/appadmin" }, { "code": null, "e": 21248, "s": 21153, "text": "On hitting the URL, the user will get the list of tables associated for the given application." }, { "code": null, "e": 21436, "s": 21248, "text": "This interface is not intended to be public. It is designed to get an easy access to the database. It consists of two files namely − a controller “appadmin.py” and a view “appadmin.html”." }, { "code": null, "e": 21542, "s": 21436, "text": "It can paginate up to 100 records at a time. The usage of “appadmin” is discussed in subsequent chapters." }, { "code": null, "e": 21630, "s": 21542, "text": "We have learnt how to start the web2py server using GUI widget in the previous chapter." }, { "code": null, "e": 21706, "s": 21630, "text": "This widget can be skipped by starting the server from command line prompt." }, { "code": null, "e": 21763, "s": 21706, "text": "python web2py.py -a 'your password' -i 127.0.0.1 -p 8000" }, { "code": null, "e": 21886, "s": 21763, "text": "Whenever web2py server starts, it creates a file \"parameters_8000.py\" where all the passwords are stored in a hashed form." }, { "code": null, "e": 21960, "s": 21886, "text": "For additional security purpose, the following command line can be used −" }, { "code": null, "e": 22014, "s": 21960, "text": "python web2py.py -a '<recycle>' -i 127.0.0.1 -p 8000\n" }, { "code": null, "e": 22105, "s": 22014, "text": "For the above scenario, web2py reuses the hashed passwords stored in \"parameters_8000.py\"." }, { "code": null, "e": 22261, "s": 22105, "text": "In case, if the file \"parameters_8000.py\" is deleted accidently or due to some other reasons, the web-based administrative interface is disabled in web2py." }, { "code": null, "e": 22395, "s": 22261, "text": "The functioning of web2py is based on model-view-controller, which maps the URL in a specific form − http://127.0.0.1:8000/a/d/f.html" }, { "code": null, "e": 22608, "s": 22395, "text": "It routes till the function “f()” mentioned in the controller d.py is under the application named “a”. If the controller is not present in the application then web2py uses a default controller named “default.py”." }, { "code": null, "e": 22776, "s": 22608, "text": "If the function, as given in the URL is not present, then the default function called init() is used. The working of the URL is shown schematically in the image below." }, { "code": null, "e": 23015, "s": 22776, "text": "The extension .html is optional for the URL. The extension determines the extension of View that renders the output of the function defined in the controller. The same content is served in multiple formats namely html, xml, json, rss etc." }, { "code": null, "e": 23258, "s": 23015, "text": "The request is passed, based on the functions, which accept the arguments and gives the appropriate output to the user. It is the controller, which interacts with model and view of the application for giving the output as per the user’s need." }, { "code": null, "e": 23302, "s": 23258, "text": "The workflow of web2py is discussed below −" }, { "code": null, "e": 23388, "s": 23302, "text": "The web server manages each and every HTTP requests simultaneously in its own thread." }, { "code": null, "e": 23474, "s": 23388, "text": "The web server manages each and every HTTP requests simultaneously in its own thread." }, { "code": null, "e": 23538, "s": 23474, "text": "The HTTP request header is parsed and passed to the dispatcher." }, { "code": null, "e": 23602, "s": 23538, "text": "The HTTP request header is parsed and passed to the dispatcher." }, { "code": null, "e": 23753, "s": 23602, "text": "The Dispatcher manages the application requests and maps the PATH_INFO in the URL of the function call. Every function call is represented in the URL." }, { "code": null, "e": 23904, "s": 23753, "text": "The Dispatcher manages the application requests and maps the PATH_INFO in the URL of the function call. Every function call is represented in the URL." }, { "code": null, "e": 24026, "s": 23904, "text": "All the requests for files included in the static folder are managed directly, and large file are streamed to the client." }, { "code": null, "e": 24148, "s": 24026, "text": "All the requests for files included in the static folder are managed directly, and large file are streamed to the client." }, { "code": null, "e": 24215, "s": 24148, "text": "Requests for anything but a static file are mapped into an action." }, { "code": null, "e": 24282, "s": 24215, "text": "Requests for anything but a static file are mapped into an action." }, { "code": null, "e": 24410, "s": 24282, "text": "If the request header contains a session cookie for the app, the session object is retrieved; or else, a session id is created." }, { "code": null, "e": 24538, "s": 24410, "text": "If the request header contains a session cookie for the app, the session object is retrieved; or else, a session id is created." }, { "code": null, "e": 24611, "s": 24538, "text": "If the action returns a value as string, this is returned to the client." }, { "code": null, "e": 24684, "s": 24611, "text": "If the action returns a value as string, this is returned to the client." }, { "code": null, "e": 24773, "s": 24684, "text": "If the action returns an iterable, it is used to loop and stream the data to the client." }, { "code": null, "e": 24862, "s": 24773, "text": "If the action returns an iterable, it is used to loop and stream the data to the client." }, { "code": null, "e": 25080, "s": 24862, "text": "In the previous chapter, we saw the functionality of the Controllers. web2py uses models, views and controllers in each of its application. Therefore, it is also necessary to understand the functionality of the Model." }, { "code": null, "e": 25277, "s": 25080, "text": "Unlike any other MVC application, Models in web2py are treated as conditional. Models in subfolders are executed, based on its controller’s usage. This can be demonstrated with following example −" }, { "code": null, "e": 25329, "s": 25277, "text": "Consider the URL − http://127.0.0.1:8000/a/d/f.html" }, { "code": null, "e": 25524, "s": 25329, "text": "In this case, ‘a’ is the name of the application, ‘d’ is the controller’s name and f() is the function associated with the controller. The list of models, which will be executed are as follows −" }, { "code": null, "e": 25612, "s": 25524, "text": "applications/a/models/*.py\napplications/a/models/d/*.py\napplications/a/models/d/f/*.py\n" }, { "code": null, "e": 25784, "s": 25612, "text": "web2py includes libraries, which are exposed to the all the applications as the objects. These objects are defined inside the core files under the directory named “gluon”." }, { "code": null, "e": 25970, "s": 25784, "text": "Many of the modules like DAL template have no dependencies and can be implemented outside the framework of web2py. It also maintains the unit tests which is considered as good practice." }, { "code": null, "e": 26030, "s": 25970, "text": "web2py applications are shown below in a diagrammatic form." }, { "code": null, "e": 26105, "s": 26030, "text": "The Applications developed in web2py are composed of the following parts −" }, { "code": null, "e": 26151, "s": 26105, "text": "Models − Represents data and database tables." }, { "code": null, "e": 26197, "s": 26151, "text": "Models − Represents data and database tables." }, { "code": null, "e": 26257, "s": 26197, "text": "Controllers − Describes the application logic and workflow." }, { "code": null, "e": 26317, "s": 26257, "text": "Controllers − Describes the application logic and workflow." }, { "code": null, "e": 26366, "s": 26317, "text": "Views − Helps rendering the display of the data." }, { "code": null, "e": 26415, "s": 26366, "text": "Views − Helps rendering the display of the data." }, { "code": null, "e": 26514, "s": 26415, "text": "Languages − describe how to translate strings in the application into various supported languages." }, { "code": null, "e": 26613, "s": 26514, "text": "Languages − describe how to translate strings in the application into various supported languages." }, { "code": null, "e": 26691, "s": 26613, "text": "Static files − Do not require processing (e.g. images, CSS style sheets etc)." }, { "code": null, "e": 26769, "s": 26691, "text": "Static files − Do not require processing (e.g. images, CSS style sheets etc)." }, { "code": null, "e": 26812, "s": 26769, "text": "ABOUT and README − Details of the project." }, { "code": null, "e": 26855, "s": 26812, "text": "ABOUT and README − Details of the project." }, { "code": null, "e": 26915, "s": 26855, "text": "Errors − Stores error reports generated by the application." }, { "code": null, "e": 26975, "s": 26915, "text": "Errors − Stores error reports generated by the application." }, { "code": null, "e": 27038, "s": 26975, "text": "Sessions − Stores information related to each particular user." }, { "code": null, "e": 27101, "s": 27038, "text": "Sessions − Stores information related to each particular user." }, { "code": null, "e": 27170, "s": 27101, "text": "Databases − store SQLite databases and additional table information." }, { "code": null, "e": 27239, "s": 27170, "text": "Databases − store SQLite databases and additional table information." }, { "code": null, "e": 27279, "s": 27239, "text": "Cache − Store cached application items." }, { "code": null, "e": 27319, "s": 27279, "text": "Cache − Store cached application items." }, { "code": null, "e": 27372, "s": 27319, "text": "Modules − Modules are other optional Python modules." }, { "code": null, "e": 27425, "s": 27372, "text": "Modules − Modules are other optional Python modules." }, { "code": null, "e": 27517, "s": 27425, "text": "Private − Included files are accessed by the controllers but not directly by the developer." }, { "code": null, "e": 27609, "s": 27517, "text": "Private − Included files are accessed by the controllers but not directly by the developer." }, { "code": null, "e": 27687, "s": 27609, "text": "Uploads − Files are accessed by the models but not directly by the developer." }, { "code": null, "e": 27765, "s": 27687, "text": "Uploads − Files are accessed by the models but not directly by the developer." }, { "code": null, "e": 27892, "s": 27765, "text": "In web2py, models, controllers and views are executed in an environment where certain objects are imported for the developers." }, { "code": null, "e": 27944, "s": 27892, "text": "Global Objects − request, response, session, cache." }, { "code": null, "e": 28089, "s": 27944, "text": "Helpers − web2py includes helper class, which can be used to build HTML programmatically. It corresponds to HTML tags, termed as “HTML helpers”." }, { "code": null, "e": 28129, "s": 28089, "text": "For example, A, B, FIELDSET, FORM, etc." }, { "code": null, "e": 28280, "s": 28129, "text": "A session can be defined as a server-side storage of information, which is persisted throughout the user's interaction throughout the web application." }, { "code": null, "e": 28332, "s": 28280, "text": "Session in web2py is the instance of storage class." }, { "code": null, "e": 28384, "s": 28332, "text": "For example, a variable can be stored in session as" }, { "code": null, "e": 28414, "s": 28384, "text": "session.myvariable = \"hello\"\n" }, { "code": null, "e": 28445, "s": 28414, "text": "This value can be retrieved as" }, { "code": null, "e": 28469, "s": 28445, "text": "a = session.myvariable\n" }, { "code": null, "e": 28582, "s": 28469, "text": "The value of the variable can be retrieved as long as the code is executed in the same session by the same user." }, { "code": null, "e": 28647, "s": 28582, "text": "One of the important methods in web2py for session is “forget” −" }, { "code": null, "e": 28674, "s": 28647, "text": "session.forget(response);\n" }, { "code": null, "e": 28719, "s": 28674, "text": "It instructs web2py not to save the session." }, { "code": null, "e": 28993, "s": 28719, "text": "An HTTP request arrives to the web server, which handles each request in its own thread, in parallel. The task, which is active, takes place in the foreground while the others are kept in background. Managing the background tasks is also one of the main features of web2py." }, { "code": null, "e": 29135, "s": 28993, "text": "Time-consuming tasks are preferably kept in the background. Some of the mechanisms are listed as follows, which manage the background tasks −" }, { "code": null, "e": 29140, "s": 29135, "text": "CRON" }, { "code": null, "e": 29145, "s": 29140, "text": "CRON" }, { "code": null, "e": 29152, "s": 29145, "text": "Queues" }, { "code": null, "e": 29159, "s": 29152, "text": "Queues" }, { "code": null, "e": 29169, "s": 29159, "text": "Scheduler" }, { "code": null, "e": 29179, "s": 29169, "text": "Scheduler" }, { "code": null, "e": 29347, "s": 29179, "text": "In web2py, CRON gives the ability to run the task within the specified intervals of the time. Each application includes a CRON file, which defines its functionalities." }, { "code": null, "e": 29510, "s": 29347, "text": "The built-in scheduler helps in running the tasks in background by setting the priority. It provides a mechanism for creating, scheduling and modifying the tasks." }, { "code": null, "e": 29587, "s": 29510, "text": "The scheduled events are listed in models with the file name “scheduler.py”." }, { "code": null, "e": 29830, "s": 29587, "text": "We had an overview of creating models and controllers in web2py. Here, we will focus on the creation of the application named “Contacts”. The application needs to maintain a list of companies, and a list of people who work at those companies." }, { "code": null, "e": 30031, "s": 29830, "text": "Here, identification of the tables for the data dictionary is the model. The model for the contacts application will be created under the “models” folders. The file is stored in models/db_contacts.py." }, { "code": null, "e": 30593, "s": 30031, "text": "# in file: models/db_custom.py\ndb.define_table('company', Field('name', notnull = True, unique = True), format = '%(name)s')\ndb.define_table(\n 'contact',\n Field('name', notnull = True),\n Field('company', 'reference company'),\n Field('picture', 'upload'),\n Field('email', requires = IS_EMAIL()),\n Field('phone_number', requires = IS_MATCH('[\\d\\-\\(\\) ]+')),\n Field('address'),\n format = '%(name)s'\n)\n\ndb.define_table(\n 'log',\n Field('body', 'text', notnull = True),\n Field('posted_on', 'datetime'),\n Field('contact', 'reference contact')\n)" }, { "code": null, "e": 30713, "s": 30593, "text": "Once the above file is created, the tables can be accessed with the help of URL http://127.0.0.1:8000/contacts/appadmin" }, { "code": null, "e": 30804, "s": 30713, "text": "The Controller will include some functions for listing, editing and deleting the contacts." }, { "code": null, "e": 31821, "s": 30804, "text": "# in file: controllers/default.py\ndef index():return locals()\ndef companies():companies = db(db.company).select(orderby = db.company.name)\nreturn locals()\n\ndef contacts():company = db.company(request.args(0)) or redirect(URL('companies'))\ncontacts = db(db.contact.company == company.id).select(orderby = db.contact.name)\nreturn locals()\n\[email protected]_login()\ndef company_create():form = crud.create(db.company, next = 'companies')\nreturn locals()\n\[email protected]_login()\ndef company_edit():company = db.company(request.args(0)) or redirect(URL('companies'))\nform = crud.update(db.company, company, next='companies')\nreturn locals()\n\[email protected]_login()\ndef contact_create():db.contact.company.default = request.args(0)\nform = crud.create(db.contact, next = 'companies')\nreturn locals()\n\[email protected]_login()\ndef contact_edit():contact = db.contact(request.args(0)) or redirect(URL('companies'))\nform = crud.update(db.contact, contact, next = 'companies')\nreturn locals()\n\ndef user():return dict(form = auth())" }, { "code": null, "e": 31907, "s": 31821, "text": "The creation of the view along with its output will be discussed in the next chapter." }, { "code": null, "e": 32121, "s": 31907, "text": "web2py framework uses Models, Controllers and Views in its applications. It includes a slightly modified Python syntax in the Views for more readable code without any restriction as imposed on proper Python usage." }, { "code": null, "e": 32258, "s": 32121, "text": "The main purpose of a web2py View is to embed the python code in an HTML document. However, it faces some issues, which are as follows −" }, { "code": null, "e": 32312, "s": 32258, "text": "Escaping of embedded python code in an HTML document." }, { "code": null, "e": 32380, "s": 32312, "text": "Following indentation based on Python, which may affect HTML rules." }, { "code": null, "e": 32576, "s": 32380, "text": "To escape with the problems, web2py uses delimiters {{..}} in the view section. The delimiters help in escaping the embedded python code. It also helps in following the HTML rules of indentation." }, { "code": null, "e": 32853, "s": 32576, "text": "The code included within {{..}} delimiters include unintended Python code. Since Python normally uses indentation to delimit blocks of code, the unintended code within the delimiters should be maintained in proper way. To overcome this problem, web2py uses the “pass” keyword." }, { "code": null, "e": 32956, "s": 32853, "text": "The code block beginning with a line terminates with a colon and ends with a line beginning with pass." }, { "code": null, "e": 33017, "s": 32956, "text": "Note − pass is a Python keyword, it is not a web2py keyword." }, { "code": null, "e": 33079, "s": 33017, "text": "The following code shows the implementation of pass keyword −" }, { "code": null, "e": 33200, "s": 33079, "text": "{{\n if num > 0:\n response.write('positive number')\n else:\n response.write('negative number')\n pass\n}}" }, { "code": null, "e": 33338, "s": 33200, "text": "web2py includes helper class which can be used to build HTML programmatically. It corresponds to the HTML tags, termed as “HTML helpers”." }, { "code": null, "e": 33352, "s": 33338, "text": "For example −" }, { "code": null, "e": 33420, "s": 33352, "text": "[(A('Home', _href = URL('default', 'home')), False, None, []), ...]" }, { "code": null, "e": 33539, "s": 33420, "text": "Here, A is the helper corresponding to the anchor <a> tag of HTML. It builds the HTML anchor <a> tag programmatically." }, { "code": null, "e": 33614, "s": 33539, "text": "HTML helpers consists of two types, namely positional and named arguments." }, { "code": null, "e": 33710, "s": 33614, "text": "Positional arguments are interpreted as objects contained between the HTML open and close tags." }, { "code": null, "e": 33806, "s": 33710, "text": "Positional arguments are interpreted as objects contained between the HTML open and close tags." }, { "code": null, "e": 33877, "s": 33806, "text": "Named arguments begins with an underscore are interpreted as HTML tag." }, { "code": null, "e": 33948, "s": 33877, "text": "Named arguments begins with an underscore are interpreted as HTML tag." }, { "code": null, "e": 34047, "s": 33948, "text": "Helpers are also useful in serialization of strings, with the _str_ and xml methods. For example −" }, { "code": null, "e": 34081, "s": 34047, "text": ">>> print str(DIV(“hello world”))" }, { "code": null, "e": 34107, "s": 34081, "text": "<div> hello world </div>\n" }, { "code": null, "e": 34200, "s": 34107, "text": "Note − HTML helpers provide a server-side representation of the Document Object Model (DOM)." }, { "code": null, "e": 34323, "s": 34200, "text": "XML is termed as an object, which encapsulates text that should not be escaped. The text may or may not contain valid XML." }, { "code": null, "e": 34395, "s": 34323, "text": "For example, for the below mentioned code, it could contain JavaScript." }, { "code": null, "e": 34446, "s": 34395, "text": ">>> print XML('<script>alert(\"unsafe!\")</script>')" }, { "code": null, "e": 34481, "s": 34446, "text": "<script> alert(“unsafe!”)</script>" }, { "code": null, "e": 34584, "s": 34481, "text": "There are many built-in helpers used in web2py. Some of the HTML built-in helpers are listed as below." }, { "code": null, "e": 34653, "s": 34584, "text": "[\n(A('Home', _href = URL('default', 'home')), False, None, []),\n...]" }, { "code": null, "e": 34713, "s": 34653, "text": "B('<hello>', XML('<i>world</i>'), _class = 'test', _id = 0)" }, { "code": null, "e": 34718, "s": 34713, "text": "BR()" }, { "code": null, "e": 34767, "s": 34718, "text": "CODE('print \"hello\"', language = 'python').xml()" }, { "code": null, "e": 34829, "s": 34767, "text": "FIELDSET('Height:', INPUT(_name = 'height'), _class = 'test')" }, { "code": null, "e": 34852, "s": 34829, "text": "HEAD(TITLE('<hello>'))" }, { "code": null, "e": 34909, "s": 34852, "text": "IMG(_src = 'http://example.com/image.png',_alt = 'test')" }, { "code": null, "e": 35018, "s": 34909, "text": "These helpers are used to customize the tags as per the requirements. web2py uses following custom helpers −" }, { "code": null, "e": 35145, "s": 35018, "text": "web2py uses TAG as the universal tag generator. It helps in generating customized XML tags. The general syntax is as follows −" }, { "code": null, "e": 35181, "s": 35145, "text": "{{ = TAG.name('a', 'b', _c = 'd')}}" }, { "code": null, "e": 35236, "s": 35181, "text": "It generates the XML code as : <name c = \"d\">ab</name>" }, { "code": null, "e": 35334, "s": 35236, "text": "TAG is an object and TAG.name or TAG['name'] is a function that returns a temporary helper class." }, { "code": null, "e": 35536, "s": 35334, "text": "This helper makes a list of the list items or the values of the menu items, generating a tree-like structure representing the menu. The list of menu items is in the form of response.menu. For example −" }, { "code": null, "e": 35599, "s": 35536, "text": "print MENU([['One', False, 'link1'], ['Two', False, 'link2']])" }, { "code": null, "e": 35641, "s": 35599, "text": "The output will be displayed as follows −" }, { "code": null, "e": 35771, "s": 35641, "text": "<ul class = \"web2py-menu web2py-menu-vertical\">\n <li><a href = \"link1\">One</a></li>\n <li><a href = \"link2\">Two</a></li>\n</ul>" }, { "code": null, "e": 35876, "s": 35771, "text": "It helps in building representations of compound objects, including lists and dictionaries. For example," }, { "code": null, "e": 35937, "s": 35876, "text": "{{ = BEAUTIFY({\"a\": [\"hello\", XML(\"world\")], \"b\": (1, 2)})}}" }, { "code": null, "e": 36078, "s": 35937, "text": "It returns an XML object serializable to XML, with a representation of its constructor argument. In this case, the representation would be −" }, { "code": null, "e": 36122, "s": 36078, "text": "{\"a\": [\"hello\", XML(\"world\")], \"b\": (1, 2)}" }, { "code": null, "e": 36155, "s": 36122, "text": "The output will be rendered as −" }, { "code": null, "e": 36334, "s": 36155, "text": "<table>\n <tr>\n <td>a</td>\n <td>:</td>\n <td>hello<br />world</td>\n </tr>\n \n <tr>\n <td>b</td>\n <td>:</td>\n <td>1<br />2</td>\n </tr>\n</table>" }, { "code": null, "e": 36514, "s": 36334, "text": "Server-side rendering allows a user to pre-render the initial state of web2py components. All the derived helpers provide search element and elements to render DOM on server side." }, { "code": null, "e": 36684, "s": 36514, "text": "The element returns the first child element matching a specified condition. On the other hand, elements return a list of all the matching children. Both use same syntax." }, { "code": null, "e": 36738, "s": 36684, "text": "This can be demonstrated with the following example −" }, { "code": null, "e": 36849, "s": 36738, "text": "a = DIV(DIV(DIV('a', _id = 'target',_class = 'abc')))\nd = a.elements('div#target')\nd[0][0] = 'changed'\nprint a" }, { "code": null, "e": 36874, "s": 36849, "text": "The output is given as −" }, { "code": null, "e": 36944, "s": 36874, "text": "<div><div><div id = \"target\" class = \"abc\">changed</div></div></div>\n" }, { "code": null, "e": 37096, "s": 36944, "text": "Views are used to display the output to the end users. It can extend as well as include other views as well. This will implement a tree-like structure." }, { "code": null, "e": 37212, "s": 37096, "text": "Example − “index.html” extends to “layout.html” which can include “menu.html” which in turn includes “header.html”." }, { "code": null, "e": 37282, "s": 37212, "text": "{{extend 'layout.html'}}\n<h1>Hello World</h1>\n{{include 'page.html'}}" }, { "code": null, "e": 37456, "s": 37282, "text": "In the previous chapters, we created models and controllers for the company module. Now, we will focus on the creation of view, which helps in rendering the display of data." }, { "code": null, "e": 37578, "s": 37456, "text": "By default, the views in web2py include layout.html and index.html, which defines the overall section of displaying data." }, { "code": null, "e": 37957, "s": 37578, "text": "{{extend 'layout.html'}}\n<h2>Companies</h2>\n\n<table>\n {{for company in companies:}}\n <tr>\n <td>{{ = A(company.name, _href = URL('contacts', args = company.id))}}</td>\n <td>{{ = A('edit', _href = URL('company_edit', args = company.id))}}</td>\n </tr>\n \n {{pass}}\n <tr>\n <td>{{ = A('add company', _href = URL('company_create'))}}</td>\n </tr>\n\t\n</table>" }, { "code": null, "e": 37989, "s": 37957, "text": "The output will be as follows −" }, { "code": null, "e": 38169, "s": 37989, "text": "The Database Abstraction Layer (DAL) is considered as the major strength of web2py. The DAL exposes a simple Applications Programming Interface (API) to the underlying SQL syntax." }, { "code": null, "e": 38341, "s": 38169, "text": "In this chapter, we will get to know the non-trivial applications of DAL, such as building queries to search by tags efficiently and building a hierarchical category tree." }, { "code": null, "e": 38378, "s": 38341, "text": "Some important features of DAL are −" }, { "code": null, "e": 38543, "s": 38378, "text": "web2py includes a Database Abstraction Layer (DAL), an API which maps Python objects into database objects. The database objects can be queries, tables and records." }, { "code": null, "e": 38708, "s": 38543, "text": "web2py includes a Database Abstraction Layer (DAL), an API which maps Python objects into database objects. The database objects can be queries, tables and records." }, { "code": null, "e": 38887, "s": 38708, "text": "The DAL dynamically generates the SQL in real time using the specified dialect for the database back end, so that it is not mandatory for a developer to write complete SQL query." }, { "code": null, "e": 39066, "s": 38887, "text": "The DAL dynamically generates the SQL in real time using the specified dialect for the database back end, so that it is not mandatory for a developer to write complete SQL query." }, { "code": null, "e": 39176, "s": 39066, "text": "The major advantage of using DAL is that the applications will be portable with different kinds of databases." }, { "code": null, "e": 39286, "s": 39176, "text": "The major advantage of using DAL is that the applications will be portable with different kinds of databases." }, { "code": null, "e": 39435, "s": 39286, "text": "Most applications in web2py require a database connection. Therefore, building the database model is the first step in the design of an application." }, { "code": null, "e": 39659, "s": 39435, "text": "Consider the newly created application named “helloWorld”. The database is implemented under the Models of the application. All the models for the respective application are comprised under file named − models/db_custom.py." }, { "code": null, "e": 39711, "s": 39659, "text": "The following steps are used for implementing DAL −" }, { "code": null, "e": 39819, "s": 39711, "text": "Establish a database connection. This is created using DAL object which is also called the DAL constructor." }, { "code": null, "e": 39857, "s": 39819, "text": "db = DAL ('sqlite://storage.sqlite')\n" }, { "code": null, "e": 40259, "s": 39857, "text": "The notable feature of DAL is that it allows multiple connections with the same database or with different databases, even with different types of database. It is observed that this line is already in the file models/db.py. Therefore, you may not need it, unless you deleted it or need to connect to a different database. By default, web2py connects to a SQLite database stored in file storage.sqlite." }, { "code": null, "e": 40406, "s": 40259, "text": "This file is located in the application's databases folder. If the file is absent, it is created by web2py when the application is first executed." }, { "code": null, "e": 40715, "s": 40406, "text": "SQLite is fast, and stores all the data in one single file. This means that your data can be easily transferred from one application to another. In fact, the SQLite database(s) are packaged by web2py together with the applications. It provides full SQL support, including translations, joins, and aggregates." }, { "code": null, "e": 40754, "s": 40715, "text": "There are two disadvantages of SQLite." }, { "code": null, "e": 40868, "s": 40754, "text": "One is that it does not enforce column types, and there is no ALTER TABLE except for adding and dropping columns." }, { "code": null, "e": 40982, "s": 40868, "text": "One is that it does not enforce column types, and there is no ALTER TABLE except for adding and dropping columns." }, { "code": null, "e": 41090, "s": 40982, "text": "The other disadvantage is that the entire database is locked by any transaction that requires write access." }, { "code": null, "e": 41198, "s": 41090, "text": "The other disadvantage is that the entire database is locked by any transaction that requires write access." }, { "code": null, "e": 41305, "s": 41198, "text": "Once the connection with database is established, we can use the define_table method to define new tables." }, { "code": null, "e": 41319, "s": 41305, "text": "For example −" }, { "code": null, "e": 41361, "s": 41319, "text": "db.define_table('invoice',Field('name'))\n" }, { "code": null, "e": 41600, "s": 41361, "text": "The above method is also used among Table constructor. The syntax for the table constructor is the same. The first argument is the table name, and it is followed by a list of Field(s). The field constructor takes the following arguments −" }, { "code": null, "e": 41615, "s": 41600, "text": "The field name" }, { "code": null, "e": 41643, "s": 41615, "text": "Name of the field in table." }, { "code": null, "e": 41658, "s": 41643, "text": "The field type" }, { "code": null, "e": 41759, "s": 41658, "text": "takes values having any of the datatypes such as string (default), text, boolean, integer and so on." }, { "code": null, "e": 41766, "s": 41759, "text": "Length" }, { "code": null, "e": 41794, "s": 41766, "text": "Defines the maximum length." }, { "code": null, "e": 41809, "s": 41794, "text": "default = None" }, { "code": null, "e": 41866, "s": 41809, "text": "This is the default value when a new record is inserted." }, { "code": null, "e": 41880, "s": 41866, "text": "update = None" }, { "code": null, "e": 41965, "s": 41880, "text": "This works the same as default, but the value is used only on update, not on insert." }, { "code": null, "e": 41973, "s": 41965, "text": "Notnull" }, { "code": null, "e": 42032, "s": 41973, "text": "This specifies whether the field value can be NULL or not." }, { "code": null, "e": 42048, "s": 42032, "text": "readable = True" }, { "code": null, "e": 42110, "s": 42048, "text": "This specifies whether the field is readable in forms or not." }, { "code": null, "e": 42126, "s": 42110, "text": "writable = True" }, { "code": null, "e": 42188, "s": 42126, "text": "This specifies whether the field is writable in forms or not." }, { "code": null, "e": 42209, "s": 42188, "text": "label = \"Field Name\"" }, { "code": null, "e": 42263, "s": 42209, "text": "This is the label to be used for this field in forms." }, { "code": null, "e": 42322, "s": 42263, "text": "The define_table method also takes three named arguments −" }, { "code": null, "e": 42399, "s": 42322, "text": "db.define_table('....',migrate=True, fake_migrate=False, format = '%(id)s')\n" }, { "code": null, "e": 42535, "s": 42399, "text": "migrate = True − This instructs web2py to create the table if it does not exist, or alter it if it does not match the model definition." }, { "code": null, "e": 42671, "s": 42535, "text": "migrate = True − This instructs web2py to create the table if it does not exist, or alter it if it does not match the model definition." }, { "code": null, "e": 42810, "s": 42671, "text": "fake_migrate = False − If the model matches the database table content, then set fake_migrate = True which helps web2py to rebuild a data." }, { "code": null, "e": 42949, "s": 42810, "text": "fake_migrate = False − If the model matches the database table content, then set fake_migrate = True which helps web2py to rebuild a data." }, { "code": null, "e": 43063, "s": 42949, "text": "format = '%(id)s' − This is a format string that determines how records on the given table should be represented." }, { "code": null, "e": 43177, "s": 43063, "text": "format = '%(id)s' − This is a format string that determines how records on the given table should be represented." }, { "code": null, "e": 43320, "s": 43177, "text": "Using DAL, we can establish a connection to database and create new tables and their fields using the table constructor and field constructor." }, { "code": null, "e": 43508, "s": 43320, "text": "Sometimes, it is necessary to generate SQL statements to conform to the necessary output. web2py includes various functions, which help in generating raw SQL, which are given as follows −" }, { "code": null, "e": 43581, "s": 43508, "text": "It helps in fetching insert statements for the given table. For example," }, { "code": null, "e": 43618, "s": 43581, "text": "print db.person._insert(name ='ABC')" }, { "code": null, "e": 43682, "s": 43618, "text": "It will retrieve the insert statement for table named “person”." }, { "code": null, "e": 43705, "s": 43682, "text": "SQL statement output −" }, { "code": null, "e": 43747, "s": 43705, "text": "INSERT INTO person(name) VALUES ('ABC');\n" }, { "code": null, "e": 43920, "s": 43747, "text": "It helps in fetching SQL statement, which gives the count of records. For example, consider a table named ‘person’ and we need to find the count of persons with name ‘ABC’." }, { "code": null, "e": 43964, "s": 43920, "text": "print db(db.person.name ==' ABC ')._count()" }, { "code": null, "e": 43987, "s": 43964, "text": "SQL statement output −" }, { "code": null, "e": 44045, "s": 43987, "text": "SELECT count(*) FROM person WHERE person.name = ' ABC ';\n" }, { "code": null, "e": 44191, "s": 44045, "text": "It helps in fetching select SQL statements. For example, consider a table named ‘person’ and we need to find the list of persons with name ‘ABC’." }, { "code": null, "e": 44237, "s": 44191, "text": "print db(db.person.name == ' ABC ')._select()" }, { "code": null, "e": 44260, "s": 44237, "text": "SQL statement output −" }, { "code": null, "e": 44321, "s": 44260, "text": "SELECT person.name FROM person WHERE person.name = ' ABC ';\n" }, { "code": null, "e": 44469, "s": 44321, "text": "It helps in fetching the delete SQL statements. For example, consider for table named ‘person’ and we need to delete the statements with name ‘ABC’" }, { "code": null, "e": 44515, "s": 44469, "text": "print db(db.person.name == ' ABC ')._delete()" }, { "code": null, "e": 44538, "s": 44515, "text": "SQL statement output −" }, { "code": null, "e": 44588, "s": 44538, "text": "DELETE FROM person WHERE person.name = ' ABC ';4\n" }, { "code": null, "e": 44738, "s": 44588, "text": "It helps in fetching updated SQL statements. For example, consider for table named ‘person’ and we need to update a column name with some other value" }, { "code": null, "e": 44784, "s": 44738, "text": "print db(db.person.name == ' ABC ')._update()" }, { "code": null, "e": 44807, "s": 44784, "text": "SQL statement output −" }, { "code": null, "e": 44854, "s": 44807, "text": "UPDATE person SET WHERE person.name = ’Alex’;\n" }, { "code": null, "e": 45040, "s": 44854, "text": "SQLite lacks the support of dropping or altering the columns. Deleting a field from the table keeps it active in the database, due to which web2py will not be aware of any changes made." }, { "code": null, "e": 45232, "s": 45040, "text": "In this case, it is necessary to set the fake_migrate = True which will help to redefine the metadata such that any changes such as alter or delete will be kept under the knowledge of web2py." }, { "code": null, "e": 45399, "s": 45232, "text": "SQLite does not support Boolean types. For this, web2py internally maps the Booleans to 1 character string, with 'T' and 'F' representing true and False respectively." }, { "code": null, "e": 45639, "s": 45399, "text": "MySQL does not support ALTER TABLE feature. Thus, migration of database involves multiple commits. This situation can be avoided by setting the parameter fake_migrate = True while defining the database, which will persist all the metadata." }, { "code": null, "e": 45934, "s": 45639, "text": "Oracle does not support the feature of pagination of records. It also lacks the support for the keywords OFFSET or limit. For this, web2py achieves pagination with the help of a complex three-way nested select of DAL. DAL needs to handle pagination on its own, if Oracle database has been used." }, { "code": null, "e": 46053, "s": 45934, "text": "web2py comes with powerful functions for form generation. Four distinct ways to build forms in web2py are as follows −" }, { "code": null, "e": 46180, "s": 46053, "text": "FORM − In terms of HTML helpers, it is considered as a low-level implementation. A FORM object is aware of its field contents." }, { "code": null, "e": 46307, "s": 46180, "text": "FORM − In terms of HTML helpers, it is considered as a low-level implementation. A FORM object is aware of its field contents." }, { "code": null, "e": 46404, "s": 46307, "text": "SQLFORM − It provides the functionalities of Create, Update and Delete to the existing database." }, { "code": null, "e": 46501, "s": 46404, "text": "SQLFORM − It provides the functionalities of Create, Update and Delete to the existing database." }, { "code": null, "e": 46672, "s": 46501, "text": "SQLFORM.factory − It is considered as abstraction layer on the top of SQLFORM, which generates a form similar to SQLFORM. Here, there is no need to create a new database." }, { "code": null, "e": 46843, "s": 46672, "text": "SQLFORM.factory − It is considered as abstraction layer on the top of SQLFORM, which generates a form similar to SQLFORM. Here, there is no need to create a new database." }, { "code": null, "e": 46988, "s": 46843, "text": "CRUD Methods − As the name suggests, it provides Create, Retrieve, Update and Delete features with the similar functionalities based on SQLFORM." }, { "code": null, "e": 47133, "s": 46988, "text": "CRUD Methods − As the name suggests, it provides Create, Retrieve, Update and Delete features with the similar functionalities based on SQLFORM." }, { "code": null, "e": 47245, "s": 47133, "text": "Consider an application, which accepts an input from the user and has a “submit” button to submit the response." }, { "code": null, "e": 47316, "s": 47245, "text": "“default.py” controller will include the following associated function" }, { "code": null, "e": 47353, "s": 47316, "text": "def display_form():\n return dict()" }, { "code": null, "e": 47446, "s": 47353, "text": "The associated view \"default/display_form.html\" will render the display of form in HTML as −" }, { "code": null, "e": 47707, "s": 47446, "text": "{{extend 'layout.html'}}\n<h2>Basic Form</h2>\n\n<form enctype = \"multipart/form-data\" action = \"{{= URL()}}\" method = \"post\">\n Your name:\n <input name = \"name\" />\n <input type = \"submit\" />\n</form>\n\n<h2>Submitted variables</h2>\n{{= BEAUTIFY(request.vars)}}" }, { "code": null, "e": 47847, "s": 47707, "text": "The above example is the normal HTML form, which asks for the user input. The same form can be generated with the helpers like FORM object." }, { "code": null, "e": 47969, "s": 47847, "text": "def display_form():\n form = FORM('Value:', INPUT(_value = 'name'), INPUT(_type = 'submit'))\n return dict(form = form)" }, { "code": null, "e": 48083, "s": 47969, "text": "The above function in “default.py” controller includes FORM object (HTML helper) which helps in creation of form." }, { "code": null, "e": 48199, "s": 48083, "text": "{{extend 'layout.html'}}\n<h2>Basic form</h2>\n\n{{= form}}\n<h2>Submitted variables</h2>\n\n{{= BEAUTIFY(request.vars)}}" }, { "code": null, "e": 48456, "s": 48199, "text": "He form which is generated by the statement {{= form}} serializes the FORM object. When a user fills the form and clicks on the submit button, the form self-submits, and the variable request.vars.value along with its input value is displayed at the bottom." }, { "code": null, "e": 48567, "s": 48456, "text": "It helps in creation of a form to the existing database. The steps for its implementation are discussed below." }, { "code": null, "e": 48760, "s": 48567, "text": "Establishing connection with database using DAL, this is created using DAL object which is also called DAL constructor. After establishing the connection, user can create the respective table." }, { "code": null, "e": 48866, "s": 48760, "text": "db = DAL('sqlite://storage.sqlite')\ndb.define_table('employee', Field('name', requires = IS_NOT_EMPTY()))" }, { "code": null, "e": 48988, "s": 48866, "text": "Thus, we have created a table named “employee”. The controller builds the form and button with the following statements −" }, { "code": null, "e": 49100, "s": 48988, "text": "form = SQLFORM(\n db.mytable,\n record = mytable_index,\n deletable = True,\n submit_button = T('Update')\n)" }, { "code": null, "e": 49189, "s": 49100, "text": "Therefore, for the employee table created, the modification in the controller would be −" }, { "code": null, "e": 49238, "s": 49189, "text": "def display_form():\n form = SQLFORM(db.person)" }, { "code": null, "e": 49469, "s": 49238, "text": "There is no modification in View. In the new controller, it is necessary build a FORM, since the SQLFORM constructor built one from the table db.employee is defined in the model. The new form, when serialized, appears as follows −" }, { "code": null, "e": 50191, "s": 49469, "text": "<form enctype = \"multipart/form-data\" action = \"\" method = \"post\">\n \n <table>\n <tr id = \"employee_name__row\">\n <td>\n <label id = \"person_name__label\" for = \"person_name\">Your name: </label>\n </td>\n \n <td>\n <input type = \"text\" class = \"string\" name = \"name\" value = \"\" id = \"employee_name\" />\n </td>\n \n <td></td>\n </tr>\n\n <tr id = \"submit_record__row\">\n <td></td>\n <td><input value = \"Submit\" type = \"submit\" /></td>\n <td></td>\n </tr>\n\t\t\n </table>\n\n <input value = \"9038845529\" type = \"hidden\" name = \"_formkey\" />\n <input value = \"employee\" type = \"hidden\" name = \"_formname\" />\n\t\n</form>" }, { "code": null, "e": 50262, "s": 50191, "text": "All tags in the form have names derived from the table and field name." }, { "code": null, "e": 50496, "s": 50262, "text": "An SQLFORM object also deals with \"upload\" fields by saving uploaded files in the \"uploads\" folder. This is done automatically. SQLFORM displays “Boolean” values in the form of checkboxes and text values with the help of “textareas”." }, { "code": null, "e": 50612, "s": 50496, "text": "SQLFORM also uses the process method.This is necessary if the user wants to keep values with an associated SQLFORM." }, { "code": null, "e": 50668, "s": 50612, "text": "If form.process(keepvalues = True) then it is accepted." }, { "code": null, "e": 50919, "s": 50668, "text": "def display_form():\n form = SQLFORM(db.employee)\nif form.process().accepted:\n response.flash = 'form accepted'\n\nelif form.errors:\n response.flash = 'form has errors'\nelse:\n response.flash = 'please fill out the form'\n\nreturn dict(form = form)" }, { "code": null, "e": 51128, "s": 50919, "text": "Sometimes, the user needs to generate a form in a way that there is an existing database table without the implementation of the database. The user simply wants to take an advantage of the SQLFORM capability." }, { "code": null, "e": 51193, "s": 51128, "text": "This is done via form.factory and it is maintained in a session." }, { "code": null, "e": 51591, "s": 51193, "text": "def form_from_factory():\n form = SQLFORM.factory(\n Field('your_name', requires = IS_NOT_EMPTY()),\n Field('your_image', 'upload'))\n\n if form.process().accepted:\n response.flash = 'form accepted'\n session.your_name = form.vars.your_name\n session.your_image = form.vars.your_image\n elif form.errors:\n response.flash = 'form has errors'\n\n return dict(form = form)" }, { "code": null, "e": 51709, "s": 51591, "text": "The form will appear like SQLFORM with name and image as its fields, but there is no such existing table in database." }, { "code": null, "e": 51771, "s": 51709, "text": "The \"default/form_from_factory.html\" view will represent as −" }, { "code": null, "e": 51807, "s": 51771, "text": "{{extend 'layout.html'}}\n{{= form}}" }, { "code": null, "e": 51947, "s": 51807, "text": "CRUD is an API used on top of SQLFORM. As the name suggests, it is used for creation, retrieval, updating and deletion of appropriate form." }, { "code": null, "e": 52063, "s": 51947, "text": "CRUD, in comparison to other APIs in web2py, is not exposed; therefore, it is necessary that it should be imported." }, { "code": null, "e": 52108, "s": 52063, "text": "from gluon.tools import Crud\ncrud = Crud(db)" }, { "code": null, "e": 52167, "s": 52108, "text": "The CRUD object defined above provides the following API −" }, { "code": null, "e": 52181, "s": 52167, "text": "crud.tables()" }, { "code": null, "e": 52231, "s": 52181, "text": "Returns a list of tables defined in the database." }, { "code": null, "e": 52257, "s": 52231, "text": "crud.create(db.tablename)" }, { "code": null, "e": 52304, "s": 52257, "text": "Returns a create form for the table tablename." }, { "code": null, "e": 52332, "s": 52304, "text": "crud.read(db.tablename, id)" }, { "code": null, "e": 52386, "s": 52332, "text": "Returns a read-only form for tablename and record id." }, { "code": null, "e": 52416, "s": 52386, "text": "crud.delete(db.tablename, id)" }, { "code": null, "e": 52435, "s": 52416, "text": "deletes the record" }, { "code": null, "e": 52468, "s": 52435, "text": "crud.select(db.tablename, query)" }, { "code": null, "e": 52519, "s": 52468, "text": "Returns a list of records selected from the table." }, { "code": null, "e": 52545, "s": 52519, "text": "crud.search(db.tablename)" }, { "code": null, "e": 52606, "s": 52545, "text": "Returns a tuple (form, records) where form is a search form." }, { "code": null, "e": 52613, "s": 52606, "text": "crud()" }, { "code": null, "e": 52667, "s": 52613, "text": "Returns one of the above based on the request.args()." }, { "code": null, "e": 52719, "s": 52667, "text": "Let us create a form. Follow the codes given below." }, { "code": null, "e": 52837, "s": 52719, "text": "A new model is created under the models folder of the application. The name of the file would be “dynamic_search.py”." }, { "code": null, "e": 54155, "s": 52837, "text": "def build_query(field, op, value):\n if op == 'equals':\n return field == value\n \n elif op == 'not equal':\n return field != value\n \n elif op == 'greater than':\n return field > value\n \n elif op == 'less than':\n return field < value\n \n elif op == 'starts with':\n return field.startswith(value)\n \n elif op == 'ends with':\n return field.endswith(value)\n \n elif op == 'contains':\n return field.contains(value)\n\ndef dynamic_search(table):\n tbl = TABLE()\n selected = []\n ops = ['equals', \n 'not equal',\n 'greater than',\n 'less than',\n 'starts with',\n 'ends with',\n 'contains']\n\t\t\nquery = table.id > 0\n\nfor field in table.fields:\n chkval = request.vars.get('chk'+field,None)\n txtval = request.vars.get('txt'+field,None)\n opval = request.vars.get('op'+field,None)\n\t\nrow = TR(TD(INPUT(_type = \"checkbox\",_name = \"chk\"+field,value = chkval == 'on')),\n TD(field),TD(SELECT(ops,_name = \"op\"+field,value = opval)),\n TD(INPUT(_type = \"text\",_name = \"txt\"+field,_value = txtval)))\n\t\ntbl.append(row)\n\nif chkval:\n if txtval:\n query &= build_query(table[field], opval,txtval)\n selected.append(table[field])\n form = FORM(tbl,INPUT(_type=\"submit\"))\n results = db(query).select(*selected)\n return form, results" }, { "code": null, "e": 54262, "s": 54155, "text": "The associated file namely “dynamic_search.py” under controllers section will include the following code −" }, { "code": null, "e": 54365, "s": 54262, "text": "def index():\n form,results = dynamic_search(db.things)\n return dict(form = form,results = results)" }, { "code": null, "e": 54409, "s": 54365, "text": "We can render this with the following view." }, { "code": null, "e": 54459, "s": 54409, "text": "{{extend 'layout.html'}}\n{{= form}}\n{{= results}}" }, { "code": null, "e": 54488, "s": 54459, "text": "Here is what it looks like −" }, { "code": null, "e": 54601, "s": 54488, "text": "web2py includes functionalities of sending e-mail and SMS to the user. It uses libraries to send emails and sms." }, { "code": null, "e": 54736, "s": 54601, "text": "The in-built class namely gluon.tools.Mail class is used to send email in web2py framework. The mailer can be defined with this class." }, { "code": null, "e": 54907, "s": 54736, "text": "from gluon.tools import Mail\nmail = Mail()\nmail.settings.server = 'smtp.example.com:25'\nmail.settings.sender = '[email protected]'\nmail.settings.login = 'username:password'" }, { "code": null, "e": 55037, "s": 54907, "text": "The sender email as mentioned in the above example along with the password will be authenticated each time when an email is sent." }, { "code": null, "e": 55151, "s": 55037, "text": "If the user needs to experiment or use for some debugging purpose, this can be achieved using the following code." }, { "code": null, "e": 55184, "s": 55151, "text": "mail.settings.server = 'logging'" }, { "code": null, "e": 55259, "s": 55184, "text": "Now, all the emails will not be sent but it will be logged in the console." }, { "code": null, "e": 55371, "s": 55259, "text": "Once we have set the configuration settings for an email using mail object, an email can be sent to many users." }, { "code": null, "e": 55422, "s": 55371, "text": "The complete syntax of mail.send() is as follows −" }, { "code": null, "e": 55596, "s": 55422, "text": "send(\n to, subject = 'Abc',\n message = 'None', attachments = [],\n cc = [], bcc = [], reply_to = [],\n sender = None, encoding = 'utf-8',\n raw = True, headers = {}\n)" }, { "code": null, "e": 55646, "s": 55596, "text": "The implementation of mail.send() is given below." }, { "code": null, "e": 55779, "s": 55646, "text": "mail.send(\n to = ['[email protected]'], subject = 'hello',\n reply_to = '[email protected]',\n message = 'Hello ! How are you?'\n)" }, { "code": null, "e": 55965, "s": 55779, "text": "Mail returns a Boolean expression based on the response of the mailing server, that the mail is received by the end user. It returns True if it succeeds in sending an email to the user." }, { "code": null, "e": 56081, "s": 55965, "text": "The attributes to, cc and bcc includes the list of valid email addresses for which the mail is intended to be sent." }, { "code": null, "e": 56385, "s": 56081, "text": "The implementation for sending SMS messages differs from sending emails in web2py framework as it will require third party service that can relay the messages to the receiver. The third party service is not a free service and will obviously differ based on geographical region (from country to country)." }, { "code": null, "e": 56455, "s": 56385, "text": "web2py uses a module to help sending SMS with the following process −" }, { "code": null, "e": 56628, "s": 56455, "text": "from gluon.contrib.sms_utils\nimport SMSCODES, sms_email\nemail = sms_email('1 (111) 111-1111','T-Mobile USA (abc)')\nmail.send(to = email, subject = 'test', message = 'test')" }, { "code": null, "e": 56777, "s": 56628, "text": "In the above example, SMSCODES is the dictionary maintained by web2py that maps the names of the major phone companies to the email address postfix." }, { "code": null, "e": 57073, "s": 56777, "text": "Telephone companies usually treat emails originating from third party services as spam. A better method is that the phone companies themselves relay the SMS. Every phone company includes a unique email address for every mobile number in its storage and the SMS can be sent directly to the email." }, { "code": null, "e": 57095, "s": 57073, "text": "In the above example," }, { "code": null, "e": 57200, "s": 57095, "text": "The sms_email function takes a phone number (as a string), which returns the email address of the phone." }, { "code": null, "e": 57305, "s": 57200, "text": "The sms_email function takes a phone number (as a string), which returns the email address of the phone." }, { "code": null, "e": 57398, "s": 57305, "text": "The scaffolding app includes several files. One of them is models/db.py, which imports four." }, { "code": null, "e": 57491, "s": 57398, "text": "The scaffolding app includes several files. One of them is models/db.py, which imports four." }, { "code": null, "e": 57587, "s": 57491, "text": "Classes from gluon.tools include mail libraries as well and defines the various global objects." }, { "code": null, "e": 57683, "s": 57587, "text": "Classes from gluon.tools include mail libraries as well and defines the various global objects." }, { "code": null, "e": 58015, "s": 57683, "text": "The scaffolding application also defines tables required by the auth object, such as db.auth_user. The default scaffolding application is designed to minimize the number of files, not to be modular. In particular, the model file, db.py, contains the configuration, which in a production environment, is best kept in separate files." }, { "code": null, "e": 58347, "s": 58015, "text": "The scaffolding application also defines tables required by the auth object, such as db.auth_user. The default scaffolding application is designed to minimize the number of files, not to be modular. In particular, the model file, db.py, contains the configuration, which in a production environment, is best kept in separate files." }, { "code": null, "e": 58396, "s": 58347, "text": "Here, we suggest creating a configuration file −" }, { "code": null, "e": 59234, "s": 58396, "text": "from gluon.storage import Storage\n settings = Storage()\n settings.production = False\n \n if\n settings.production:\n settings.db_uri = 'sqlite://production.sqlite'\n settings.migrate = False\n else:\n settings.db_uri = 'sqlite://development.sqlite'\n settings.migrate = True\n settings.title = request.\n settings.subtitle = 'write something here'\n\t\t\n settings.author = 'you'\n settings.author_email = '[email protected]'\n\t\t\n settings.keywords = ''\n settings.description = ''\n settings.layout_theme = 'Default'\n settings.security_key = 'a098c897-724b-4e05-b2d8-8ee993385ae6'\n\t\t\n settings.email_server = 'localhost'\n settings.email_sender = '[email protected]'\n settings.email_login = ''\n\t\t\n settings.login_method = 'local'\n settings.login_config = ''" }, { "code": null, "e": 59507, "s": 59234, "text": "Almost every application needs to be able to authenticate users and set permissions. web2py comes with an extensive and customizable role-based access control mechanism.web2py. It also supports the protocols, such as CAS, OpenID, OAuth 1.0, LDAP, PAM, X509, and many more." }, { "code": null, "e": 59712, "s": 59507, "text": "web2py includes a mechanism known as Role Based Access Control mechanism (RBAC) which is an approach to restricting system access to authorized users. The web2py class that implements RBAC is called Auth." }, { "code": null, "e": 59744, "s": 59712, "text": "Look at the schema given below." }, { "code": null, "e": 59780, "s": 59744, "text": "Auth defines the following tables −" }, { "code": null, "e": 59790, "s": 59780, "text": "auth_user" }, { "code": null, "e": 59847, "s": 59790, "text": "stores users' name, email address, password, and status." }, { "code": null, "e": 59858, "s": 59847, "text": "auth_group" }, { "code": null, "e": 59919, "s": 59858, "text": "stores groups or roles for users in a many-to-many structure" }, { "code": null, "e": 59935, "s": 59919, "text": "auth_membership" }, { "code": null, "e": 60012, "s": 59935, "text": "Stores the information of links users and groups in a many-to-many structure" }, { "code": null, "e": 60028, "s": 60012, "text": "auth_permission" }, { "code": null, "e": 60068, "s": 60028, "text": "The table links groups and permissions." }, { "code": null, "e": 60079, "s": 60068, "text": "auth_event" }, { "code": null, "e": 60134, "s": 60079, "text": "logs changes in the other tables and successful access" }, { "code": null, "e": 60143, "s": 60134, "text": "auth_cas" }, { "code": null, "e": 60189, "s": 60143, "text": "It is used for Central Authentication Service" }, { "code": null, "e": 60227, "s": 60189, "text": "There are two ways to customize Auth." }, { "code": null, "e": 60279, "s": 60227, "text": "To define a custom db.auth_user table from scratch." }, { "code": null, "e": 60331, "s": 60279, "text": "To define a custom db.auth_user table from scratch." }, { "code": null, "e": 60365, "s": 60331, "text": "Let web2py define the auth table." }, { "code": null, "e": 60399, "s": 60365, "text": "Let web2py define the auth table." }, { "code": null, "e": 60507, "s": 60399, "text": "Let us look at the last method of defining the auth table. In the db.py model, replace the following line −" }, { "code": null, "e": 60529, "s": 60507, "text": "auth.define_tables()\n" }, { "code": null, "e": 60566, "s": 60529, "text": "Replace it with the following code −" }, { "code": null, "e": 60745, "s": 60566, "text": "auth.settings.extra_fields['auth_user'] = [\n Field('phone_number',requires = IS_MATCH('\\d{3}\\-\\d{3}\\-\\d{4}')),\n Field('address','text')\n]\n\nauth.define_tables(username = True)" }, { "code": null, "e": 60826, "s": 60745, "text": "The assumption is that each user consists of phone number, username and address." }, { "code": null, "e": 61059, "s": 60826, "text": "auth.settings.extra_fields is a dictionary of extra fields. The key is the name of the auth table to which to add the extra fields. The value is a list of extra fields. Here, we have added two extra fields, phone_number and address." }, { "code": null, "e": 61404, "s": 61059, "text": "username has to be treated in a special way, because it is involved in the authentication process, which is normally based on the email field. By passing the username argument to the following line, it is informed to web2py that we want the username field, and we want to use it for login instead of the email field. It acts like a primary key." }, { "code": null, "e": 61441, "s": 61404, "text": "auth.define_tables(username = True)\n" }, { "code": null, "e": 61657, "s": 61441, "text": "The username is treated as a unique value. There may be cases when registration happens outside the normal registration form. It also happens so, that the new user is forced to login, to complete their registration." }, { "code": null, "e": 61801, "s": 61657, "text": "This can be done using a dummy field, complete_registration that is set to False by default, and is set to True when they update their profile." }, { "code": null, "e": 62118, "s": 61801, "text": "auth.settings.extra_fields['auth_user'] = [\n Field('phone_number',requires = IS_MATCH('\\d{3}\\-\\d{3}\\-\\d{4}'),\n comment = \"i.e. 123-123-1234\"),\n Field('address','text'),\n Field('complete_registration',default = False,update = True,\n writable = False, readable = False)\n]\n\nauth.define_tables(username = True)" }, { "code": null, "e": 62202, "s": 62118, "text": "This scenario may intend the new users, upon login, to complete their registration." }, { "code": null, "e": 62269, "s": 62202, "text": "In db.py, in the models folder, we can append the following code −" }, { "code": null, "e": 62434, "s": 62269, "text": "if auth.user and not auth.user.complete_registration:\nif not (request.controller,request.function) == ('default','user'):\n redirect(URL('default','user/profile'))" }, { "code": null, "e": 62511, "s": 62434, "text": "This will force the new users to edit their profile as per the requirements." }, { "code": null, "e": 62601, "s": 62511, "text": "It is the process of granting some access or giving permission of something to the users." }, { "code": null, "e": 62815, "s": 62601, "text": "In web2py once the new user is created or registered, a new group is created to contain the user. The role of the new user is conventionally termed as “user_[id]” where id is the unique identification of the user." }, { "code": null, "e": 62872, "s": 62815, "text": "The default value for the creation of the new group is −" }, { "code": null, "e": 62922, "s": 62872, "text": "auth.settings.create_user_groups = \"user_%(id)s\"\n" }, { "code": null, "e": 62986, "s": 62922, "text": "The creation of the groups among the users can be disabled by −" }, { "code": null, "e": 63027, "s": 62986, "text": "auth.settings.create_user_groups = None\n" }, { "code": null, "e": 63156, "s": 63027, "text": "Creation, granting access to particular members and permissions can be achieved programmatically with the help of appadmin also." }, { "code": null, "e": 63208, "s": 63156, "text": "Some of the implementations are listed as follows −" }, { "code": null, "e": 63246, "s": 63208, "text": "auth.add_group('role', 'description')" }, { "code": null, "e": 63289, "s": 63246, "text": "returns the id of the newly created group." }, { "code": null, "e": 63314, "s": 63289, "text": "auth.del_group(group_id)" }, { "code": null, "e": 63354, "s": 63314, "text": "Deletes the group with the specified id" }, { "code": null, "e": 63394, "s": 63354, "text": "auth.del_group(auth.id_group('user_7'))" }, { "code": null, "e": 63448, "s": 63394, "text": "Deletes the user group with the given identification." }, { "code": null, "e": 63473, "s": 63448, "text": "auth.user_group(user_id)" }, { "code": null, "e": 63546, "s": 63473, "text": "Returns the value of id of group uniquely associated for the given user." }, { "code": null, "e": 63585, "s": 63546, "text": "auth.add_membership(group_id, user_id)" }, { "code": null, "e": 63637, "s": 63585, "text": "Returns the value of user_id for the given group_id" }, { "code": null, "e": 63676, "s": 63637, "text": "auth.del_membership(group_id, user_id)" }, { "code": null, "e": 63749, "s": 63676, "text": "Revokes access of the given member_id i.e. user_id from the given group." }, { "code": null, "e": 63794, "s": 63749, "text": "auth.has_membership(group_id, user_id, role)" }, { "code": null, "e": 63845, "s": 63794, "text": "Checks whether user_id belongs to the given group." }, { "code": null, "e": 64011, "s": 63845, "text": "web2py provides an industry standard namely, Client Authentication Service – CAS for both client and server built-in web2py. It is a third party authentication tool." }, { "code": null, "e": 64101, "s": 64011, "text": "It is an open protocol for distributed authentication. The working of CAS is as follows −" }, { "code": null, "e": 64188, "s": 64101, "text": "If the user visits the website, the protocol checks whether the user is authenticated." }, { "code": null, "e": 64275, "s": 64188, "text": "If the user visits the website, the protocol checks whether the user is authenticated." }, { "code": null, "e": 64421, "s": 64275, "text": "If the user is not authenticated to the application, the protocol redirects to the page where the user can register or log in to the application." }, { "code": null, "e": 64567, "s": 64421, "text": "If the user is not authenticated to the application, the protocol redirects to the page where the user can register or log in to the application." }, { "code": null, "e": 64700, "s": 64567, "text": "If the registration is completed, user receives an email. The registration is not complete until and unless user verifies the email." }, { "code": null, "e": 64833, "s": 64700, "text": "If the registration is completed, user receives an email. The registration is not complete until and unless user verifies the email." }, { "code": null, "e": 64936, "s": 64833, "text": "After successful registration, the user is authenticated with the key, which is used by CAS appliance." }, { "code": null, "e": 65039, "s": 64936, "text": "After successful registration, the user is authenticated with the key, which is used by CAS appliance." }, { "code": null, "e": 65136, "s": 65039, "text": "The key is used to get the credentials of user via HTTP request, which is set in the background." }, { "code": null, "e": 65233, "s": 65136, "text": "The key is used to get the credentials of user via HTTP request, which is set in the background." }, { "code": null, "e": 65431, "s": 65233, "text": "web2py provides support for various protocols like XML, JSON, RSS, CSV, XMLRPC, JSONRPC, AMFRPC, and SOAP. Each of those protocols is supported in multiple ways, and we make a distinction between −" }, { "code": null, "e": 65485, "s": 65431, "text": "Rendering the output of a function in a given format." }, { "code": null, "e": 65509, "s": 65485, "text": "Remote Procedure Calls." }, { "code": null, "e": 65580, "s": 65509, "text": "Consider the following code which maintains the count of the sessions." }, { "code": null, "e": 65702, "s": 65580, "text": "def count():\n session.counter = (session.counter or 0) + 1\n return dict(counter = session.counter, now = request.now)" }, { "code": null, "e": 65969, "s": 65702, "text": "The above function increases the number of counts as and when the user visits the page. Suppose the given function is defined in “default.py” controller of web2py application. The page can be requested with the following URL − http://127.0.0.1:8000/app/default/count" }, { "code": null, "e": 66068, "s": 65969, "text": "web2py can render the above page in different protocols and by adding extension to the URL, like −" }, { "code": null, "e": 66113, "s": 66068, "text": "http://127.0.0.1:8000/app/default/count.html" }, { "code": null, "e": 66157, "s": 66113, "text": "http://127.0.0.1:8000/app/default/count.xml" }, { "code": null, "e": 66202, "s": 66157, "text": "http://127.0.0.1:8000/app/default/count.json" }, { "code": null, "e": 66286, "s": 66202, "text": "The dictionary returned by the above action will be rendered in HTML, XML and JSON." }, { "code": null, "e": 66453, "s": 66286, "text": "web2py framework provides a mechanism which converts a function into a web service. The mechanism described here differs from the mechanism described before because −" }, { "code": null, "e": 66489, "s": 66453, "text": "Inclusion of arguments in function." }, { "code": null, "e": 66530, "s": 66489, "text": "The function must be defined in a model." }, { "code": null, "e": 66579, "s": 66530, "text": "It enforces a more strict URL naming convention." }, { "code": null, "e": 66646, "s": 66579, "text": "It works for a fixed set of protocols and it is easily extensible." }, { "code": null, "e": 66723, "s": 66646, "text": "To use this feature it is necessary to import and initiate a service object." }, { "code": null, "e": 66812, "s": 66723, "text": "To implement this mechanism, at first, you must import and instantiate a service object." }, { "code": null, "e": 66864, "s": 66812, "text": "from gluon.tools import Service\nservice = Service()" }, { "code": null, "e": 67093, "s": 66864, "text": "This is implemented in the \"db.py\" model file in the scaffolding application. Db.py model is the default model in web2py framework, which interacts with the database and the controller to achieve the desired output to the users." }, { "code": null, "e": 67193, "s": 67093, "text": "After implementing, the service in model can be accessed from the controllers as and when required." }, { "code": null, "e": 67305, "s": 67193, "text": "The following example shows various implementations of remote procedure calls using web services and many more." }, { "code": null, "e": 67444, "s": 67305, "text": "Web Services can be defined as a standardized way of integrating Web-based applications using the protocols like XML, SOAP, WSDL and UDDI." }, { "code": null, "e": 67516, "s": 67444, "text": "web2py supports most of them, but the integration will be quite tricky." }, { "code": null, "e": 67627, "s": 67516, "text": "There are many ways to return JSON form web2py, but here we consider the case of a JSON service. For example −" }, { "code": null, "e": 67772, "s": 67627, "text": "def consumer():return dict()@service.json\ndef get_days():return [\"Sun\", \"Mon\", \"Tues\", \"Wed\", \"Thurs\", \"Fri\", \"Sat\"]\ndef call():return service()" }, { "code": null, "e": 67796, "s": 67772, "text": "Here, we observe that −" }, { "code": null, "e": 67894, "s": 67796, "text": "the function just returns an empty dictionary to render the view, which will consume the service." }, { "code": null, "e": 67992, "s": 67894, "text": "the function just returns an empty dictionary to render the view, which will consume the service." }, { "code": null, "e": 68077, "s": 67992, "text": "get_days defines the service, and the function call exposes all registered services." }, { "code": null, "e": 68162, "s": 68077, "text": "get_days defines the service, and the function call exposes all registered services." }, { "code": null, "e": 68233, "s": 68162, "text": "get_days does not need to be in the controller, and can be in a model." }, { "code": null, "e": 68304, "s": 68233, "text": "get_days does not need to be in the controller, and can be in a model." }, { "code": null, "e": 68361, "s": 68304, "text": "call is always in the default.py scaffolding controller." }, { "code": null, "e": 68418, "s": 68361, "text": "call is always in the default.py scaffolding controller." }, { "code": null, "e": 68466, "s": 68418, "text": "View with the consumer actions are as follows −" }, { "code": null, "e": 68733, "s": 68466, "text": "{{extend 'layout.html'}}\n<div id = \"target\"></div>\n\n<script>\n jQuery.getJSON(\"{{= URL('call',args = ['json','get_days'])}}\",\n function(msg){\n jQuery.each(msg, function(){ jQuery(\"#target\").\n append(this + \"<br />\"); } )\n }\n );\n</script>" }, { "code": null, "e": 68861, "s": 68733, "text": "The first argument of jQuery.getJSON is the URL of the following service − http://127.0.0.1:8000/app/default/call/json/get_days" }, { "code": null, "e": 68895, "s": 68861, "text": "This always follows the pattern −" }, { "code": null, "e": 68953, "s": 68895, "text": "http://<domain>/<app>/<controller>/call/<type>/<service>\n" }, { "code": null, "e": 69174, "s": 68953, "text": "The URL is in between {{...}}, because it is resolved at the server-side, while everything else is executed at the client-side. The second argument of jQuery.getJSON is a callback, which will be passed the JSON response." }, { "code": null, "e": 69345, "s": 69174, "text": "In this case, the callback loops over each item in the response (a list of week days as strings), and appends each string, followed by a <br/> to the <div id = \"target\">." }, { "code": null, "e": 69426, "s": 69345, "text": "In this way, web2py manages implementation of web services using jQuery.getJSON." }, { "code": null, "e": 69653, "s": 69426, "text": "In this chapter, we will discuss examples of integration of jQuery plugins with web2py. These plugins help in making forms and tables more interactive and friendly to the user, thus improving the usability of your application." }, { "code": null, "e": 69682, "s": 69653, "text": "In particular, we will learn" }, { "code": null, "e": 69763, "s": 69682, "text": "how to improve the multi-select drop-down with an interactive add option button," }, { "code": null, "e": 69844, "s": 69763, "text": "how to improve the multi-select drop-down with an interactive add option button," }, { "code": null, "e": 69893, "s": 69844, "text": "how to replace an input field with a slider, and" }, { "code": null, "e": 69942, "s": 69893, "text": "how to replace an input field with a slider, and" }, { "code": null, "e": 69996, "s": 69942, "text": "how to display tabular data using jqGrid and WebGrid." }, { "code": null, "e": 70050, "s": 69996, "text": "how to display tabular data using jqGrid and WebGrid." }, { "code": null, "e": 70261, "s": 70050, "text": "Although web2py is a server-side development component, the welcome scaffolding app includes the base jQuery library. This scaffolding web2py application \"welcome\" includes a file called views/web2py_ajax.html." }, { "code": null, "e": 70303, "s": 70261, "text": "The contents of the view are as follows −" }, { "code": null, "e": 71200, "s": 70303, "text": "<script type = \"text/javascript\"><!--\n\n // These variables are used by the web2py_ajax_init function in web2py_ajax.js \n (which is loaded below).\n\t\t\n var w2p_ajax_confirm_message = \"{{= T('Are you sure you want to delete this object?')}}\";\n var w2p_ajax_disable_with_message = \"{{= T('Working...')}}\";\n var w2p_ajax_date_format = \"{{= T('%Y-%m-%d')}}\";\n var w2p_ajax_datetime_format = \"{{= T('%Y-%m-%d %H:%M:%S')}}\";\n \n var ajax_error_500 = '{{=T.M('An error occured, please [[reload %s]] the page') %\n\t\n URL(args = request.args, vars = request.get_vars) }}'\n\t\t\n//--></script>\n\n{{\n response.files.insert(0,URL('static','js/jquery.js'))\n response.files.insert(1,URL('static','css/calendar.css'))\n response.files.insert(2,URL('static','js/calendar.js'))\n response.files.insert(3,URL('static','js/web2py.js'))\n response.include_meta()\n response.include_files()\n}}" }, { "code": null, "e": 71439, "s": 71200, "text": "The file consists of implementation of JavaScript and AJAX implementation. web2py will prevent the user from using other AJAX libraries such as Prototype, ExtJS, because it is always observed that it is easier to implement such libraries." }, { "code": null, "e": 71852, "s": 71439, "text": "The default rendering of <select multiple = \"true\">..</select> is considered not so intuitive to use, in particular, when it is necessary to select non-contiguous options. This can not be called as an HTML shortcoming, but a poor design of most of the browsers. The presentation of the multiple select can be overwritten using JavaScript. This can be implemented using jQuery plugin called jquery.multiselect.js." }, { "code": null, "e": 72086, "s": 71852, "text": "For this, a user should download the plugin jquery.muliselect.js from http://abeautifulsite.net/2008/04/jquery-multiselect, and place the corresponding files into static/js/jquery.multiselect.js and static/css/jquery.multiselect.css." }, { "code": null, "e": 72179, "s": 72086, "text": "The following code should be added in the corresponding view before {{extend ‘layout.html’}}" }, { "code": null, "e": 72554, "s": 72179, "text": "{{\n response.files.append('https://ajax.googleapis.com/ajax\\\n /libs/jqueryui/1.8.9/jquery-ui.js')\n \n response.files.append('https://ajax.googleapis.com/ajax\\\n /libs/jqueryui/1.8.9/themes/ui-darkness/jquery-ui.css')\n \n response.files.append(URL('static','js/jquery.multiSelect.js'))\n response.files.append(URL('static','css/jquery.\\multiSelect.css'))\n}}" }, { "code": null, "e": 72607, "s": 72554, "text": "Place the following after {{extend 'layout.html'}} −" }, { "code": null, "e": 72702, "s": 72607, "text": "<script>\n jQuery(document).ready(function(){jQuery('[multiple]').multiSelect();});\n</script>" }, { "code": null, "e": 72757, "s": 72702, "text": "This will help to style multiselect for the given form" }, { "code": null, "e": 73031, "s": 72757, "text": "def index():\n is_fruits = IS_IN_SET(['Apples','Oranges','Bananas','Kiwis','Lemons'], multiple = True)\n form = SQLFORM.factory(Field('fruits','list:string', requires = is_fruits))\n \n if form.accepts(request,session):response.flash = 'Yummy!'\nreturn dict(form = form)" }, { "code": null, "e": 73082, "s": 73031, "text": "This action can be tried with the following view −" }, { "code": null, "e": 73589, "s": 73082, "text": "{{\n response.files.append('https://ajax.googleapis.com/ajax\\\n /libs/jqueryui/1.8.9/jquery-ui.js')\n \n response.files.append('https://ajax.googleapis.com/ajax\\\n /libs/jqueryui/1.8.9/themes/ui-darkness/jquery-ui.css')\n \n response.files.append(URL('static','js/jquery.multiSelect.js'))\n response.files.append(URL('static','css/jquery.\\multiSelect.css'))\n}}\n\n{{extend 'layout.html}}\n<script>\n jQuery(document).ready(function(){jQuery('[multiple]'). multiSelect();});\n</script>\n{{= form}}" }, { "code": null, "e": 73634, "s": 73589, "text": "The screenshot of the output is as follows −" }, { "code": null, "e": 73703, "s": 73634, "text": "Some of the useful Jquery events are listed in the following table −" }, { "code": null, "e": 73712, "s": 73703, "text": "onchange" }, { "code": null, "e": 73747, "s": 73712, "text": "to be run when the element changes" }, { "code": null, "e": 73756, "s": 73747, "text": "onsubmit" }, { "code": null, "e": 73793, "s": 73756, "text": "to be run when the form is submitted" }, { "code": null, "e": 73802, "s": 73793, "text": "onselect" }, { "code": null, "e": 73841, "s": 73802, "text": "to be run when the element is selected" }, { "code": null, "e": 73848, "s": 73841, "text": "onblur" }, { "code": null, "e": 73887, "s": 73848, "text": "to be run when the element loses focus" }, { "code": null, "e": 73895, "s": 73887, "text": "onfocus" }, { "code": null, "e": 73933, "s": 73895, "text": "to be run when the element gets focus" }, { "code": null, "e": 74223, "s": 73933, "text": "jqGrid is an Ajax-enabled JavaScript control built on jQuery that provides a solution for representing and manipulating tabular data. jqGrid is a client-side solution, and it loads data dynamically through Ajax callbacks, thus providing pagination, search popup, inline editing, and so on." }, { "code": null, "e": 74459, "s": 74223, "text": "jqGrid is integrated into PluginWiki, but, here, we discuss it as a standalone for web2py programs that do not use the plugin. jqGrid deserves a book of its own but here we will only discuss its basic features and simplest integration." }, { "code": null, "e": 74501, "s": 74459, "text": "The syntax of jqGrid will be as follows −" }, { "code": null, "e": 74690, "s": 74501, "text": "def JQGRID(\n table, fieldname = None,\n fieldvalue = None, col_widths = [],\n colnames = [], _id = None, fields = [],\n col_width = 80, width = 700,\n height = 300, dbname = 'db'\n):\n" }, { "code": null, "e": 74983, "s": 74690, "text": "A component is defined as the functional part of a web page, which works autonomously. It can be composed of modules, controllers and views, which are embedded in a web page. The component in an application, must be localized tag and the performance is considered to be independent of module." }, { "code": null, "e": 75118, "s": 74983, "text": "In web2py, the main focus is on using components that are loaded in page and which communicate with the component controller via AJAX." }, { "code": null, "e": 75276, "s": 75118, "text": "web2py includes a function, which is called the LOAD function, which makes implementation of components easy without explicit JavaScript or AJAX programming." }, { "code": null, "e": 75411, "s": 75276, "text": "Consider a simple web application namely “test” that extends the web2py application with custom model in file “models/db_comments.py”." }, { "code": null, "e": 75512, "s": 75411, "text": "db.define_table(\n 'comment_post', Field('body','text',\n label = 'Your comment'),auth.signature\n)" }, { "code": null, "e": 75684, "s": 75512, "text": "The above code will create a table “comment_post” with the proper table definition. The action will be implemented with the help of functions in “controllers/comments.py”." }, { "code": null, "e": 75812, "s": 75684, "text": "def post():\n return dict(\n form = SQLFORM(db.comment_post).process(),\n comments = db(db.comment_post).select()\n )" }, { "code": null, "e": 75858, "s": 75812, "text": "The corresponding view will be displayed as −" }, { "code": null, "e": 76077, "s": 75858, "text": "{{extend 'layout.html'}}\n{{for post in comments:}}\n\n<div class = \"post\">\n On {{= post.created_on}} {{= post.created_by.first_name}}\n says <span class = \"post_body\">{{= post.body}}</span>\n</div>\n\n{{pass}}\n{{= form}}" }, { "code": null, "e": 76165, "s": 76077, "text": "The page can be accessed using the given URL − http://127.0.0.1:8000/test/comments/post" }, { "code": null, "e": 76301, "s": 76165, "text": "The method mentioned above is a traditional way of accessing a view, which can be changed with the implementation of the LOAD function." }, { "code": null, "e": 76405, "s": 76301, "text": "This can be achieved by creating a new view with the extension \".load\" that does not extend the layout." }, { "code": null, "e": 76464, "s": 76405, "text": "The new view created would be \"views/comments/post.load\" −" }, { "code": null, "e": 76643, "s": 76464, "text": "<div class = \"post\">\n On {{= post.created_on}} {{= post.created_by.first_name}}\n says <blockquote class = \"post_body\">{{= post.body}}</blockquote>\n</div>\n\n{{pass}}\n{{= form}}" }, { "code": null, "e": 76727, "s": 76643, "text": "The URL to access the page would be − http://127.0.0.1:8000/test/comments/post.load" }, { "code": null, "e": 76856, "s": 76727, "text": "The LOAD component can be embedded into any other page of web2py application. This can be done by using the following statement." }, { "code": null, "e": 76903, "s": 76856, "text": "{{= LOAD('comments','post.load',ajax = True)}}" }, { "code": null, "e": 76951, "s": 76903, "text": "For example, the Controllers can be edited as −" }, { "code": null, "e": 76981, "s": 76951, "text": "def index():\n return dict()" }, { "code": null, "e": 77017, "s": 76981, "text": "In View, we can add the component −" }, { "code": null, "e": 77089, "s": 77017, "text": "{{extend 'layout.html'}}\n{{= LOAD('comments','post.load',ajax = True)}}" }, { "code": null, "e": 77170, "s": 77089, "text": "The page can be accessed with the URL − http://127.0.0.1:8000/test/default/index" }, { "code": null, "e": 77308, "s": 77170, "text": "Component plugins are the plugins, which uniquely define Components. Components access the database directly with their model definition." }, { "code": null, "e": 77424, "s": 77308, "text": "As mentioned in the previous example, comments component into a comments_plugin can be done in the Models section −" }, { "code": null, "e": 77454, "s": 77424, "text": "\"models/plugin_comments.py\" −" }, { "code": null, "e": 77570, "s": 77454, "text": "db.define_table(\n 'plugin_comments_comment',\n Field('body','text', label = 'Your comment'),\n auth.signature\n)" }, { "code": null, "e": 77621, "s": 77570, "text": "The Controller will include the following plugin −" }, { "code": null, "e": 77697, "s": 77621, "text": "def plugin_comments():\n return LOAD('plugin_comments','post',ajax = True)" }, { "code": null, "e": 77783, "s": 77697, "text": "The following steps are implemented for installation of web2py in the Ubuntu Desktop." }, { "code": null, "e": 77808, "s": 77783, "text": "Step 1 − Download web2py" }, { "code": null, "e": 77902, "s": 77808, "text": "cd /home\nmkdir www-dev\n\ncd www-dev\nwget http://www.web2py.com/examples/static/web2py_src.zip\n" }, { "code": null, "e": 77953, "s": 77902, "text": "Step 2 − After the download is complete, unzip it." }, { "code": null, "e": 77978, "s": 77953, "text": "unzip -x web2py_src.zip\n" }, { "code": null, "e": 78064, "s": 77978, "text": "Step 3 − Optionally install the tk library for Python, if you need to access the GUI." }, { "code": null, "e": 78096, "s": 78064, "text": "sudo apt-get install python-tk\n" }, { "code": null, "e": 78166, "s": 78096, "text": "Step 4 − To start web2py, access the web2py directory and run web2py." }, { "code": null, "e": 78194, "s": 78166, "text": "cd web2py\npython web2py.py\n" }, { "code": null, "e": 78227, "s": 78194, "text": "The GUI will appear as follows −" }, { "code": null, "e": 78436, "s": 78227, "text": "After installation, each time you run it, web2py will ask you to choose a password. This password is your administrative password. If the password is left blank, the administrative interface will be disabled." }, { "code": null, "e": 78553, "s": 78436, "text": "Once the server is started, web2py will redirect to the screen with following mentioned URL − http://127.0.0.1:8000/" }, { "code": null, "e": 78624, "s": 78553, "text": "This will conclude that web2py is perfectly running in Ubuntu desktop." }, { "code": null, "e": 78687, "s": 78624, "text": "Step 1 − Installation of all the modules needed to run web2py." }, { "code": null, "e": 78720, "s": 78687, "text": "sudo apt-get install postgresql\n" }, { "code": null, "e": 78784, "s": 78720, "text": "sudo apt-get install unzip\nsudo apt-get install openssh-server\n" }, { "code": null, "e": 78855, "s": 78784, "text": "sudo apt-get install apache2\nsudo apt-get install libapache2-mod-wsgi\n" }, { "code": null, "e": 78905, "s": 78855, "text": "Step 2 − Installation of web2py in /home/www-data" }, { "code": null, "e": 78965, "s": 78905, "text": "This helps for proper deployment in production environment." }, { "code": null, "e": 79070, "s": 78965, "text": "sudo apt-get install unzip\nsudo apt-get install openssh-server\ncd /home\nsudo mkdir www-data\ncd www-data\n" }, { "code": null, "e": 79115, "s": 79070, "text": "Get the web2py source from the web2py site −" }, { "code": null, "e": 79240, "s": 79115, "text": "sudo wget http://web2py.com/examples/static/web2py_src.zip\nsudo unzip web2py_src.zip\nsudo chown -R www-data:www-data web2py\n" }, { "code": null, "e": 79409, "s": 79240, "text": "Step 3 − Create a self-signed certificate. SSL certificates should be obtained from a trusted Certificate Authority. Maintain an SSL folder with the certificates in it." }, { "code": null, "e": 79498, "s": 79409, "text": "Step 4 − Edit the apache configuration as per the requirement of production environment." }, { "code": null, "e": 79606, "s": 79498, "text": "Step 5 − Restart the Apache server and verify if the production environment works for the given IP address." }, { "code": null, "e": 79793, "s": 79606, "text": "Although there is a binary distribution for Windows environments (packaging executables and standard libraries), web2py is open source, and can be used with a normal Python installation." }, { "code": null, "e": 79903, "s": 79793, "text": "This method allows working with the latest releases of web2py, and customizing the python modules to be used." }, { "code": null, "e": 80038, "s": 79903, "text": "Step 1 − Download the source package from web2py official website − http://www.web2py.com/examples/static/web2py_src.zip and unzip it." }, { "code": null, "e": 80116, "s": 80038, "text": "As web2py does not require installation, the user can unzip it in any folder." }, { "code": null, "e": 80181, "s": 80116, "text": "Step 2 − To start it, double-click web2py.py. From the console −" }, { "code": null, "e": 80228, "s": 80181, "text": "cd c:\\web2py\nc:\\python27\\python.exe web2py.py\n" }, { "code": null, "e": 80385, "s": 80228, "text": "Step 3 − Here command line parameters can be added (−a to set an admin password, −p to specify an alternate port). The startup options are visible through −" }, { "code": null, "e": 80436, "s": 80385, "text": "C:\\web2py>c:\\python27\\python.exe web2py.py --help\n" }, { "code": null, "e": 80580, "s": 80436, "text": "web2py is written in Python, a portable, interpreted and dynamic language that does not require compilation or complicated installation to run." }, { "code": null, "e": 80724, "s": 80580, "text": "web2py is written in Python, a portable, interpreted and dynamic language that does not require compilation or complicated installation to run." }, { "code": null, "e": 80868, "s": 80724, "text": "It uses a virtual machine (such as Java and .Net), and it can transparently byte-compile your source code on the fly when you run your scripts." }, { "code": null, "e": 81012, "s": 80868, "text": "It uses a virtual machine (such as Java and .Net), and it can transparently byte-compile your source code on the fly when you run your scripts." }, { "code": null, "e": 81164, "s": 81012, "text": "It is a software called SQLDesigner which helps in making web2py models and generates the corresponding code. Given below are some of the screenshots −" }, { "code": null, "e": 81315, "s": 81164, "text": "SQLDesigner helps in maintaining the relations of the tables in simple manner and generates the corresponding code in the models of given application." }, { "code": null, "e": 81454, "s": 81315, "text": "Functional testing involves testing of the functions of components or overall system. It can be based on requirement and business process." }, { "code": null, "e": 81650, "s": 81454, "text": "web2py comes with a module gluon.contrib.webclient, which performs functional testing in remote and local web2py applications. It is basically designed to understand web2py session and postbacks." }, { "code": null, "e": 81766, "s": 81650, "text": "All it requires is to import the package such that the functional testing would be implemented on the given module." }, { "code": null, "e": 81815, "s": 81766, "text": "The syntax to import the package is as follows −" }, { "code": null, "e": 81862, "s": 81815, "text": "from gluon.contrib.webclient import WebClient\n" }, { "code": null, "e": 82069, "s": 81862, "text": "In the previous chapters, there was complete information on the implementation of web2py with various tools. The major concern for developing web2py applications includes security from a user’s perspective." }, { "code": null, "e": 82116, "s": 82069, "text": "The unique features of web2py are as follows −" }, { "code": null, "e": 82205, "s": 82116, "text": "Users can learn the implementation easily. It requires no installation and dependencies." }, { "code": null, "e": 82294, "s": 82205, "text": "Users can learn the implementation easily. It requires no installation and dependencies." }, { "code": null, "e": 82338, "s": 82294, "text": "It has been stable since the day of launch." }, { "code": null, "e": 82382, "s": 82338, "text": "It has been stable since the day of launch." }, { "code": null, "e": 82477, "s": 82382, "text": "web2py is lightweight and includes libraries for Data Abstraction Layer and template language." }, { "code": null, "e": 82572, "s": 82477, "text": "web2py is lightweight and includes libraries for Data Abstraction Layer and template language." }, { "code": null, "e": 82696, "s": 82572, "text": "It works with the help of Web Server Gateway Interface, which acts as a communication between web servers and applications." }, { "code": null, "e": 82820, "s": 82696, "text": "It works with the help of Web Server Gateway Interface, which acts as a communication between web servers and applications." }, { "code": null, "e": 82941, "s": 82820, "text": "Open web application security project (OWASP) is a community, which lists down the security breaches of web application." }, { "code": null, "e": 83049, "s": 82941, "text": "With respect to OWASP, issues related to web applications and how web2py overcomes them is discussed below." }, { "code": null, "e": 83300, "s": 83049, "text": "It is also known as XSS. It occurs whenever an application takes a user supplied data and sends it to the user’s browser without encoding or validating the content. The attackers execute scripts to inject worms and viruses using cross side scripting." }, { "code": null, "e": 83385, "s": 83300, "text": "web2py helps in preventing XSS by preventing all the rendered variables in the View." }, { "code": null, "e": 83561, "s": 83385, "text": "Sometimes, applications leak information about internal workings, privacy and configurations. Attackers use this to breach sensitive data, which could lead to serious attacks." }, { "code": null, "e": 83751, "s": 83561, "text": "web2py prevents this by ticketing system. It logs all the errors and the ticket is issued to the user whose error is being registered. These errors are only accessible to the administrator." }, { "code": null, "e": 83885, "s": 83751, "text": "Account credentials are not often protected. Attackers compromise on passwords, authentication tokens to steal the user’s identities." }, { "code": null, "e": 84017, "s": 83885, "text": "web2py provides a mechanism for administrative interface. It also forces to use secure sessions when the client is not “localhost”." }, { "code": null, "e": 84148, "s": 84017, "text": "Sometimes applications fail to encrypt the network traffic. It is necessary to manage traffic to protect sensitive communications." }, { "code": null, "e": 84283, "s": 84148, "text": "web2py provides SSL enabled certificates to provide encryption of communications. This also helps to maintain sensitive communication." }, { "code": null, "e": 84499, "s": 84283, "text": "Web applications normally protect the sensitive functionality by preventing display of the links and URLs to some users. Attackers can try to breach some sensitive data by manipulating the URL with some information." }, { "code": null, "e": 84722, "s": 84499, "text": "In wb2py, a URL maps to the modules and functions rather than the given file. It also includes a mechanism, which specifies which functions are public and which are maintained as private. This helps in resolving the issue." }, { "code": null, "e": 84729, "s": 84722, "text": " Print" }, { "code": null, "e": 84740, "s": 84729, "text": " Add Notes" } ]
XML-RPC - Examples
To demonstrate XML-RPC, we're going to create a server that uses Java to process XML-RPC messages, and we will create a Java client to call procedures on that server. The Java side of the conversation uses the Apache XML Project's Apache XML-RPC, available at http://xml.apache.org/xmlrpc/ Put all the .jar files in appropriate path and let us create one client and one small XML-RPC server using JAVA. Let us write an XML-RPC client to call a function called sum function. This function takes two parameters and returns their sum. import java.util.*; import org.apache.xmlrpc.*; public class JavaClient { public static void main (String [] args) { try { XmlRpcClient client = new XmlRpcClient("http://localhost/RPC2"); Vector params = new Vector(); params.addElement(new Integer(17)); params.addElement(new Integer(13)); Object result = server.execute("sample.sum", params); int sum = ((Integer) result).intValue(); System.out.println("The sum is: "+ sum); } catch (Exception exception) { System.err.println("JavaClient: " + exception); } } } Let us see what has happened in the above example client. The Java package org.apache.xmlrpc contains classes for XML-RPC Java clients and XML-RPC server, e.g., XmlRpcClient. The Java package org.apache.xmlrpc contains classes for XML-RPC Java clients and XML-RPC server, e.g., XmlRpcClient. The package java.util is necessary for the Vector class. The package java.util is necessary for the Vector class. The function server.execute(...) sends the request to the server. The procedure sum(17,13) is called on the server as if it were a local procedure. The return value of a procedure call is always an Object. The function server.execute(...) sends the request to the server. The procedure sum(17,13) is called on the server as if it were a local procedure. The return value of a procedure call is always an Object. Here "sample" denotes a handler that is defined in the server. Here "sample" denotes a handler that is defined in the server. Note that all the parameters of the procedure call are always collected in a Vector. Note that all the parameters of the procedure call are always collected in a Vector. The XmlRpcClient class is constructed by specifying the "web address" of the server machine followed by /RPC2. localhost - means the local machine You can specify an IP number instead of localhost, e.g. 194.80.215.219 You can specify a domain name like xyz.dyndns.org You can specify a port number along with domain name as xyz.dyndns.org:8080. The default port is 80 The XmlRpcClient class is constructed by specifying the "web address" of the server machine followed by /RPC2. localhost - means the local machine localhost - means the local machine You can specify an IP number instead of localhost, e.g. 194.80.215.219 You can specify an IP number instead of localhost, e.g. 194.80.215.219 You can specify a domain name like xyz.dyndns.org You can specify a domain name like xyz.dyndns.org You can specify a port number along with domain name as xyz.dyndns.org:8080. The default port is 80 You can specify a port number along with domain name as xyz.dyndns.org:8080. The default port is 80 Note that the result of the remote procedure call is always an Object and it has to be casted to the appropriate type. Note that the result of the remote procedure call is always an Object and it has to be casted to the appropriate type. When problems occur (no connection, etc.), an Exception is thrown and it has to be caught using catch statement. When problems occur (no connection, etc.), an Exception is thrown and it has to be caught using catch statement. Due to the above call, a client sends the following message to the server. Note that this is handled by server.execute(...) internally and you have nothing to do with it. <?xml version="1.0" encoding="ISO-8859-1"?> <methodCall> <methodName>sample.sum</methodName> <params> <param> <value><int>17</int></value> </param> <param> <value><int>13</int></value> </param> </params> </methodCall> Following is the source code of XML-RPC Server written in Java. It makes use of built-in classes available in org.apache.xmlrpc.* import org.apache.xmlrpc.*; public class JavaServer { public Integer sum(int x, int y){ return new Integer(x+y); } public static void main (String [] args){ try { System.out.println("Attempting to start XML-RPC Server..."); WebServer server = new WebServer(80); server.addHandler("sample", new JavaServer()); server.start(); System.out.println("Started successfully."); System.out.println("Accepting requests. (Halt program to stop.)"); } catch (Exception exception){ System.err.println("JavaServer: " + exception); } } } Let us see what we have done in the above example server. The package org.apache.xmlrpc contains the class WebServer for a XML-RPC Server implementation. The package org.apache.xmlrpc contains the class WebServer for a XML-RPC Server implementation. The procedure sum that is called remotely is implemented as a public method in a class. The procedure sum that is called remotely is implemented as a public method in a class. An instance of the same server class is then associated with a handler that is accessible by the client. An instance of the same server class is then associated with a handler that is accessible by the client. The server is initialized by the port number (here: 80). The server is initialized by the port number (here: 80). When problems occur, an Exception is thrown and has to be caught using the catch statement. When problems occur, an Exception is thrown and has to be caught using the catch statement. For the call mentioned in the given example client, the server sends the following response back to the client: <?xml version="1.0" encoding="ISO-8859-1"?> <methodResponse> <params> <param> <value><int>30</int></value> </param> </params> </methodResponse> Now your server is ready, so compile and run it at your prompt as follows: C:\ora\xmlrpc\java>java JavaServer Attempting to start XML-RPC Server... Started successfully. Accepting requests. (Halt program to stop.) Now to test the functionality, give a call to this server as follows: C:\ora\xmlrpc\java>java JavaClient 30 Print Add Notes Bookmark this page
[ { "code": null, "e": 1851, "s": 1684, "text": "To demonstrate XML-RPC, we're going to create a server that uses Java to process XML-RPC messages, and we will create a Java client to call procedures on that server." }, { "code": null, "e": 1974, "s": 1851, "text": "The Java side of the conversation uses the Apache XML Project's Apache XML-RPC, available at http://xml.apache.org/xmlrpc/" }, { "code": null, "e": 2087, "s": 1974, "text": "Put all the .jar files in appropriate path and let us create one client and one small XML-RPC server using JAVA." }, { "code": null, "e": 2216, "s": 2087, "text": "Let us write an XML-RPC client to call a function called sum function. This function takes two parameters and returns their sum." }, { "code": null, "e": 2843, "s": 2216, "text": "import java.util.*;\nimport org.apache.xmlrpc.*;\n\npublic class JavaClient {\n public static void main (String [] args) {\n \n try {\n XmlRpcClient client = new XmlRpcClient(\"http://localhost/RPC2\"); \n Vector params = new Vector();\n \n params.addElement(new Integer(17));\n params.addElement(new Integer(13));\n\n Object result = server.execute(\"sample.sum\", params);\n\n int sum = ((Integer) result).intValue();\n System.out.println(\"The sum is: \"+ sum);\n\n } catch (Exception exception) {\n System.err.println(\"JavaClient: \" + exception);\n }\n }\n}" }, { "code": null, "e": 2901, "s": 2843, "text": "Let us see what has happened in the above example client." }, { "code": null, "e": 3018, "s": 2901, "text": "The Java package org.apache.xmlrpc contains classes for XML-RPC Java clients and XML-RPC server, e.g., XmlRpcClient." }, { "code": null, "e": 3135, "s": 3018, "text": "The Java package org.apache.xmlrpc contains classes for XML-RPC Java clients and XML-RPC server, e.g., XmlRpcClient." }, { "code": null, "e": 3192, "s": 3135, "text": "The package java.util is necessary for the Vector class." }, { "code": null, "e": 3249, "s": 3192, "text": "The package java.util is necessary for the Vector class." }, { "code": null, "e": 3455, "s": 3249, "text": "The function server.execute(...) sends the request to the server. The procedure sum(17,13) is called on the server as if it were a local procedure. The return value of a procedure call is always an Object." }, { "code": null, "e": 3661, "s": 3455, "text": "The function server.execute(...) sends the request to the server. The procedure sum(17,13) is called on the server as if it were a local procedure. The return value of a procedure call is always an Object." }, { "code": null, "e": 3724, "s": 3661, "text": "Here \"sample\" denotes a handler that is defined in the server." }, { "code": null, "e": 3787, "s": 3724, "text": "Here \"sample\" denotes a handler that is defined in the server." }, { "code": null, "e": 3872, "s": 3787, "text": "Note that all the parameters of the procedure call are always collected in a Vector." }, { "code": null, "e": 3957, "s": 3872, "text": "Note that all the parameters of the procedure call are always collected in a Vector." }, { "code": null, "e": 4328, "s": 3957, "text": "The XmlRpcClient class is constructed by specifying the \"web address\" of the server machine followed by /RPC2.\n\nlocalhost - means the local machine\nYou can specify an IP number instead of localhost, e.g. 194.80.215.219\nYou can specify a domain name like xyz.dyndns.org\nYou can specify a port number along with domain name as xyz.dyndns.org:8080. The default port is 80\n\n" }, { "code": null, "e": 4439, "s": 4328, "text": "The XmlRpcClient class is constructed by specifying the \"web address\" of the server machine followed by /RPC2." }, { "code": null, "e": 4475, "s": 4439, "text": "localhost - means the local machine" }, { "code": null, "e": 4511, "s": 4475, "text": "localhost - means the local machine" }, { "code": null, "e": 4582, "s": 4511, "text": "You can specify an IP number instead of localhost, e.g. 194.80.215.219" }, { "code": null, "e": 4653, "s": 4582, "text": "You can specify an IP number instead of localhost, e.g. 194.80.215.219" }, { "code": null, "e": 4703, "s": 4653, "text": "You can specify a domain name like xyz.dyndns.org" }, { "code": null, "e": 4753, "s": 4703, "text": "You can specify a domain name like xyz.dyndns.org" }, { "code": null, "e": 4853, "s": 4753, "text": "You can specify a port number along with domain name as xyz.dyndns.org:8080. The default port is 80" }, { "code": null, "e": 4953, "s": 4853, "text": "You can specify a port number along with domain name as xyz.dyndns.org:8080. The default port is 80" }, { "code": null, "e": 5072, "s": 4953, "text": "Note that the result of the remote procedure call is always an Object and it has to be casted to the appropriate type." }, { "code": null, "e": 5191, "s": 5072, "text": "Note that the result of the remote procedure call is always an Object and it has to be casted to the appropriate type." }, { "code": null, "e": 5304, "s": 5191, "text": "When problems occur (no connection, etc.), an Exception is thrown and it has to be caught using catch statement." }, { "code": null, "e": 5417, "s": 5304, "text": "When problems occur (no connection, etc.), an Exception is thrown and it has to be caught using catch statement." }, { "code": null, "e": 5588, "s": 5417, "text": "Due to the above call, a client sends the following message to the server. Note that this is handled by server.execute(...) internally and you have nothing to do with it." }, { "code": null, "e": 5861, "s": 5588, "text": "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<methodCall>\n <methodName>sample.sum</methodName>\n <params>\n <param>\n <value><int>17</int></value>\n </param>\n\t\t \n <param>\n <value><int>13</int></value>\n </param>\n </params>\n</methodCall>" }, { "code": null, "e": 5991, "s": 5861, "text": "Following is the source code of XML-RPC Server written in Java. It makes use of built-in classes available in org.apache.xmlrpc.*" }, { "code": null, "e": 6651, "s": 5991, "text": "import org.apache.xmlrpc.*;\n\npublic class JavaServer { \n\n public Integer sum(int x, int y){\n return new Integer(x+y);\n }\n\n public static void main (String [] args){\n \n try {\n\n System.out.println(\"Attempting to start XML-RPC Server...\");\n \n WebServer server = new WebServer(80);\n server.addHandler(\"sample\", new JavaServer());\n server.start();\n \n System.out.println(\"Started successfully.\");\n System.out.println(\"Accepting requests. (Halt program to stop.)\");\n \n } catch (Exception exception){\n System.err.println(\"JavaServer: \" + exception);\n }\n }\n}" }, { "code": null, "e": 6709, "s": 6651, "text": "Let us see what we have done in the above example server." }, { "code": null, "e": 6805, "s": 6709, "text": "The package org.apache.xmlrpc contains the class WebServer for a XML-RPC Server implementation." }, { "code": null, "e": 6901, "s": 6805, "text": "The package org.apache.xmlrpc contains the class WebServer for a XML-RPC Server implementation." }, { "code": null, "e": 6989, "s": 6901, "text": "The procedure sum that is called remotely is implemented as a public method in a class." }, { "code": null, "e": 7077, "s": 6989, "text": "The procedure sum that is called remotely is implemented as a public method in a class." }, { "code": null, "e": 7182, "s": 7077, "text": "An instance of the same server class is then associated with a handler that is accessible by the client." }, { "code": null, "e": 7287, "s": 7182, "text": "An instance of the same server class is then associated with a handler that is accessible by the client." }, { "code": null, "e": 7344, "s": 7287, "text": "The server is initialized by the port number (here: 80)." }, { "code": null, "e": 7401, "s": 7344, "text": "The server is initialized by the port number (here: 80)." }, { "code": null, "e": 7493, "s": 7401, "text": "When problems occur, an Exception is thrown and has to be caught using the catch statement." }, { "code": null, "e": 7585, "s": 7493, "text": "When problems occur, an Exception is thrown and has to be caught using the catch statement." }, { "code": null, "e": 7697, "s": 7585, "text": "For the call mentioned in the given example client, the server sends the following response back to the client:" }, { "code": null, "e": 7868, "s": 7697, "text": "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<methodResponse>\n <params>\n <param>\n <value><int>30</int></value>\n </param>\n </params>\n</methodResponse>" }, { "code": null, "e": 7943, "s": 7868, "text": "Now your server is ready, so compile and run it at your prompt as follows:" }, { "code": null, "e": 8083, "s": 7943, "text": "C:\\ora\\xmlrpc\\java>java JavaServer\nAttempting to start XML-RPC Server...\nStarted successfully.\nAccepting requests. (Halt program to stop.)\n" }, { "code": null, "e": 8153, "s": 8083, "text": "Now to test the functionality, give a call to this server as follows:" }, { "code": null, "e": 8192, "s": 8153, "text": "C:\\ora\\xmlrpc\\java>java JavaClient\n30\n" }, { "code": null, "e": 8199, "s": 8192, "text": " Print" }, { "code": null, "e": 8210, "s": 8199, "text": " Add Notes" } ]
Java Program to generate n distinct random numbers
For distinct numbers, use Set, since all its implementations remove duplicates − Set<Integer>set = new LinkedHashSet<Integer>(); Now, create a Random class object − Random randNum = new Random(); Generate 10 distinct random numbers now with nextInt of the Random class − while (set.size() < 10) { set.add(randNum.nextInt(10)+1); } import java.util.LinkedHashSet; import java.util.Random; import java.util.Set; public class Demo { public static void main(final String[] args) throws Exception { Random randNum = new Random(); Set<Integer>set = new LinkedHashSet<Integer>(); while (set.size() < 10) { set.add(randNum.nextInt(10)+1); } System.out.println("Distinct random numbers = "+set); } } Distinct random numbers = [4, 6, 9, 1, 5, 2, 8, 7, 10, 3]
[ { "code": null, "e": 1143, "s": 1062, "text": "For distinct numbers, use Set, since all its implementations remove duplicates −" }, { "code": null, "e": 1191, "s": 1143, "text": "Set<Integer>set = new LinkedHashSet<Integer>();" }, { "code": null, "e": 1227, "s": 1191, "text": "Now, create a Random class object −" }, { "code": null, "e": 1258, "s": 1227, "text": "Random randNum = new Random();" }, { "code": null, "e": 1333, "s": 1258, "text": "Generate 10 distinct random numbers now with nextInt of the Random class −" }, { "code": null, "e": 1396, "s": 1333, "text": "while (set.size() < 10) {\n set.add(randNum.nextInt(10)+1);\n}" }, { "code": null, "e": 1801, "s": 1396, "text": "import java.util.LinkedHashSet;\nimport java.util.Random;\nimport java.util.Set;\npublic class Demo {\n public static void main(final String[] args) throws Exception {\n Random randNum = new Random();\n Set<Integer>set = new LinkedHashSet<Integer>();\n while (set.size() < 10) {\n set.add(randNum.nextInt(10)+1);\n }\n System.out.println(\"Distinct random numbers = \"+set);\n }\n}" }, { "code": null, "e": 1859, "s": 1801, "text": "Distinct random numbers = [4, 6, 9, 1, 5, 2, 8, 7, 10, 3]" } ]
Stream Editor - Pattern Buffer
One of the basic operations we perform on any file is display its contents. For this purpose, we can use the print command which prints the contents of the pattern buffer. So let us learn more about the pattern buffer First create a file containing the line number, the name of the book, its author, and the number of pages. In this tutorial, we will be using this file. You can use any text file according to your convenience. Our text file will look like this: [jerry]$ vi books.txt 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 3) The Alchemist, Paulo Coelho, 197 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 5) The Pilgrimage, Paulo Coelho,288 6) A Game of Thrones, George R. R. Martin, 864 Now, let us print the file contents. [jerry]$ sed 'p' books.txt When the above code is executed, it will produce the following result. 1) A Storm of Swords, George R. R. Martin, 1216 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 2) The Two Towers, J. R. R. Tolkien, 352 3) The Alchemist, Paulo Coelho, 197 3) The Alchemist, Paulo Coelho, 197 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 5) The Pilgrimage, Paulo Coelho, 288 5) The Pilgrimage, Paulo Coelho, 288 6) A Game of Thrones, George R. R. Martin, 864 6) A Game of Thrones, George R. R. Martin, 864 You might wonder why each line is being displayed twice. Let us find out. Do you remember the workflow of SED? By default, SED prints the contents of the pattern buffer. In addition, we have included a print command explicitly in our command section. Hence each line is printed twice. But don't worry. SED has the -n option to suppress the default printing of the pattern buffer. The following command illustrates that. [jerry]$ sed -n 'p' books.txt When the above code is executed, it will produce the following result. 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 3) The Alchemist, Paulo Coelho, 197 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 5) The Pilgrimage, Paulo Coelho, 288 6) A Game of Thrones, George R. R. Martin, 864 Congratulations! we got the expected result. By default, SED operates on all lines. But we can force SED to operate only on certain lines. For instance, in the example below, SED only operates on the 3rd line. In this example, we have specified an address range before the SED command. [jerry]$ sed -n '3p' books.txt When the above code is executed, it will produce the following result. 3) The Alchemist, Paulo Coelho, 197 Additionally, we can also instruct SED to print only certain lines. For instance, the following code prints all the lines from 2 to 5. Here we have used the comma(,) operator to specify the address range. [jerry]$ sed -n '2,5 p' books.txt When the above code is executed, it will produce the following result. 2) The Two Towers, J. R. R. Tolkien, 352 3) The Alchemist, Paulo Coelho, 197 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 5) The Pilgrimage, Paulo Coelho, 288 There is also a special character Dollar($) which represents the last line of the file. So let us print the last line of the file. [jerry]$ sed -n '$ p' books.txt When the above code is executed, it will produce the following result. 6) A Game of Thrones, George R. R. Martin, 864 However we can also use Dollar($) character to specify address range. Below example prints through line 3 to last line. [jerry]$ sed -n '3,$ p' books.txt When the above code is executed, it will produce the following result. 3) The Alchemist, Paulo Coelho, 197 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 5) The Pilgrimage, Paulo Coelho, 288 6) A Game of Thrones, George R. R. Martin, 864 We learnt how to specify an address range using the comma(,) operator. SED supports two more operators that can be used to specify address range. First is the plus(+) operator and it can be used with the comma(,) operator. For instance M, +n will print the next n lines starting from line number M. Sounds confusing? Let us check it with a simple example. The following example prints the next 4 lines starting from line number 2. [jerry]$ sed -n '2,+4 p' books.txt When the above code is executed, it will produce the following result. 2) The Two Towers, J. R. R. Tolkien, 352 3) The Alchemist, Paulo Coelho, 197 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 5) The Pilgrimage, Paulo Coelho, 288 6) A Game of Thrones, George R. R. Martin, 864 Optionally, we can also specify address range using the tilde(~) operator. It uses M~n form. It indicates that SED should start at line number M and process every n(th) line. For instance, 50~5 matches line number 50, 55, 60, 65, and so on. Let us print only odd lines from the file. [jerry]$ sed -n '1~2 p' books.txt When the above code is executed, it will produce the following result. 1) A Storm of Swords, George R. R. Martin, 1216 3) The Alchemist, Paulo Coelho, 197 5) The Pilgrimage, Paulo Coelho, 288 The following code prints only even lines from the file. [jerry]$ sed -n '2~2 p' books.txt When the above code is executed, it will produce the following result. 2) The Two Towers, J. R. R. Tolkien, 352 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 6) A Game of Thrones, George R. R. Martin, 864 53 Lectures 3.5 hours Senol Atac 14 Lectures 44 mins Zach Miller 13 Lectures 2 hours Sandip Bhattacharya 28 Lectures 1 hours PARTHA MAJUMDAR 16 Lectures 1.5 hours Taurius Litvinavicius 38 Lectures 2 hours Davida Shensky Print Add Notes Bookmark this page
[ { "code": null, "e": 2041, "s": 1823, "text": "One of the basic operations we perform on any file is display its contents. For this purpose, we can use the print command which prints the contents of the pattern buffer. So let us learn more about the pattern buffer" }, { "code": null, "e": 2286, "s": 2041, "text": "First create a file containing the line number, the name of the book, its author, and the number of pages. In this tutorial, we will be using this file. You can use any text file according to your convenience. Our text file will look like this:" }, { "code": null, "e": 2576, "s": 2286, "text": "[jerry]$ vi books.txt \n1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n5) The Pilgrimage, Paulo Coelho,288 \n6) A Game of Thrones, George R. R. Martin, 864\n" }, { "code": null, "e": 2613, "s": 2576, "text": "Now, let us print the file contents." }, { "code": null, "e": 2641, "s": 2613, "text": "[jerry]$ sed 'p' books.txt\n" }, { "code": null, "e": 2712, "s": 2641, "text": "When the above code is executed, it will produce the following result." }, { "code": null, "e": 3248, "s": 2712, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \n2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197 \n3) The Alchemist, Paulo Coelho, 197 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n5) The Pilgrimage, Paulo Coelho, 288 \n5) The Pilgrimage, Paulo Coelho, 288 \n6) A Game of Thrones, George R. R. Martin, 864 \n6) A Game of Thrones, George R. R. Martin, 864\n" }, { "code": null, "e": 3322, "s": 3248, "text": "You might wonder why each line is being displayed twice. Let us find out." }, { "code": null, "e": 3668, "s": 3322, "text": "Do you remember the workflow of SED? By default, SED prints the contents of the pattern buffer. In addition, we have included a print command explicitly in our command section. Hence each line is printed twice. But don't worry. SED has the -n option to suppress the default printing of the pattern buffer. The following command illustrates that." }, { "code": null, "e": 3700, "s": 3668, "text": "[jerry]$ sed -n 'p' books.txt \n" }, { "code": null, "e": 3771, "s": 3700, "text": "When the above code is executed, it will produce the following result." }, { "code": null, "e": 4040, "s": 3771, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n5) The Pilgrimage, Paulo Coelho, 288 \n6) A Game of Thrones, George R. R. Martin, 864 \n" }, { "code": null, "e": 4326, "s": 4040, "text": "Congratulations! we got the expected result. By default, SED operates on all lines. But we can force SED to operate only on certain lines. For instance, in the example below, SED only operates on the 3rd line. In this example, we have specified an address range before the SED command." }, { "code": null, "e": 4359, "s": 4326, "text": "[jerry]$ sed -n '3p' books.txt \n" }, { "code": null, "e": 4430, "s": 4359, "text": "When the above code is executed, it will produce the following result." }, { "code": null, "e": 4468, "s": 4430, "text": "3) The Alchemist, Paulo Coelho, 197 \n" }, { "code": null, "e": 4673, "s": 4468, "text": "Additionally, we can also instruct SED to print only certain lines. For instance, the following code prints all the lines from 2 to 5. Here we have used the comma(,) operator to specify the address range." }, { "code": null, "e": 4709, "s": 4673, "text": "[jerry]$ sed -n '2,5 p' books.txt \n" }, { "code": null, "e": 4780, "s": 4709, "text": "When the above code is executed, it will produce the following result." }, { "code": null, "e": 4951, "s": 4780, "text": "2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n5) The Pilgrimage, Paulo Coelho, 288\n" }, { "code": null, "e": 5082, "s": 4951, "text": "There is also a special character Dollar($) which represents the last line of the file. So let us print the last line of the file." }, { "code": null, "e": 5116, "s": 5082, "text": "[jerry]$ sed -n '$ p' books.txt \n" }, { "code": null, "e": 5187, "s": 5116, "text": "When the above code is executed, it will produce the following result." }, { "code": null, "e": 5236, "s": 5187, "text": "6) A Game of Thrones, George R. R. Martin, 864 \n" }, { "code": null, "e": 5356, "s": 5236, "text": "However we can also use Dollar($) character to specify address range. Below example prints through line 3 to last line." }, { "code": null, "e": 5392, "s": 5356, "text": "[jerry]$ sed -n '3,$ p' books.txt \n" }, { "code": null, "e": 5463, "s": 5392, "text": "When the above code is executed, it will produce the following result." }, { "code": null, "e": 5638, "s": 5463, "text": "3) The Alchemist, Paulo Coelho, 197 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 5) The Pilgrimage, Paulo Coelho, 288 6) A Game of Thrones, George R. R. Martin, 864 \n" }, { "code": null, "e": 6069, "s": 5638, "text": "We learnt how to specify an address range using the comma(,) operator. SED supports two more operators that can be used to specify address range. First is the plus(+) operator and it can be used with the comma(,) operator. For instance M, +n will print the next n lines starting from line number M. Sounds confusing? Let us check it with a simple example. The following example prints the next 4 lines starting from line number 2." }, { "code": null, "e": 6106, "s": 6069, "text": "[jerry]$ sed -n '2,+4 p' books.txt \n" }, { "code": null, "e": 6177, "s": 6106, "text": "When the above code is executed, it will produce the following result." }, { "code": null, "e": 6397, "s": 6177, "text": "2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n5) The Pilgrimage, Paulo Coelho, 288 \n6) A Game of Thrones, George R. R. Martin, 864 \n" }, { "code": null, "e": 6681, "s": 6397, "text": "Optionally, we can also specify address range using the tilde(~) operator. It uses M~n form. It indicates that SED should start at line number M and process every n(th) line. For instance, 50~5 matches line number 50, 55, 60, 65, and so on. Let us print only odd lines from the file." }, { "code": null, "e": 6717, "s": 6681, "text": "[jerry]$ sed -n '1~2 p' books.txt \n" }, { "code": null, "e": 6788, "s": 6717, "text": "When the above code is executed, it will produce the following result." }, { "code": null, "e": 6912, "s": 6788, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n3) The Alchemist, Paulo Coelho, 197 \n5) The Pilgrimage, Paulo Coelho, 288\n" }, { "code": null, "e": 6969, "s": 6912, "text": "The following code prints only even lines from the file." }, { "code": null, "e": 7005, "s": 6969, "text": "[jerry]$ sed -n '2~2 p' books.txt \n" }, { "code": null, "e": 7076, "s": 7005, "text": "When the above code is executed, it will produce the following result." }, { "code": null, "e": 7221, "s": 7076, "text": "2) The Two Towers, J. R. R. Tolkien, 352 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n6) A Game of Thrones, George R. R. Martin, 864 \n" }, { "code": null, "e": 7256, "s": 7221, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7268, "s": 7256, "text": " Senol Atac" }, { "code": null, "e": 7300, "s": 7268, "text": "\n 14 Lectures \n 44 mins\n" }, { "code": null, "e": 7313, "s": 7300, "text": " Zach Miller" }, { "code": null, "e": 7346, "s": 7313, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 7367, "s": 7346, "text": " Sandip Bhattacharya" }, { "code": null, "e": 7400, "s": 7367, "text": "\n 28 Lectures \n 1 hours \n" }, { "code": null, "e": 7417, "s": 7400, "text": " PARTHA MAJUMDAR" }, { "code": null, "e": 7452, "s": 7417, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7475, "s": 7452, "text": " Taurius Litvinavicius" }, { "code": null, "e": 7508, "s": 7475, "text": "\n 38 Lectures \n 2 hours \n" }, { "code": null, "e": 7524, "s": 7508, "text": " Davida Shensky" }, { "code": null, "e": 7531, "s": 7524, "text": " Print" }, { "code": null, "e": 7542, "s": 7531, "text": " Add Notes" } ]
How to Calculate Mean in Excel?
28 Jul, 2021 The mean (also called average) of the data set is calculated by adding all the numbers in the data set and then dividing it by the total number of values in the data set. In this article, we will find out how to calculate the mean in excel. In this method, we are going to use the AVERAGE function which returns the mean of the arguments. For example, the =AVERAGE(A1:A10) returns the average of the numbers in the range of A1 to A10. Syntax: AVERAGE(number1,[number2],...) Here, number1 (Required): The first cell reference or number for which you want the average number2 (optional): Additional cell references or numbers for which you want the average. The maximum limit is 255. Notes: arguments can either be numbers or names, ranges, or cell references that contain numbers. If the argument contains text or logical values or empty cells then those values are ignored. However, if the cell contains the value zero then it is included. if the argument contains error values or text that cannot be translated to numbers then it will cause errors. AVERAGE: This function returns the average of cells with any data (logical values or text representation of numbers) AVERAGEIF: This function is used to calculate the average of only the values that meet a single criterion. AVERAGEIFS: This function is used to calculate the average based on multiple criteria. Example: Let us apply the above formula on some rough data as shown below: In the above example, we have used 4 different functions. =AVERAGE(c4:e12): Returns the average of the numbers in cells c4 to e12 =AVERAGE(c4:f6,6): Returns the average of the numbers in cells c4 to f6 and the number 6. =AVERAGE(b4:b12, “sara”, c4:c12): Returns the average of the numbers in cells c4 to c12 by matching the name “sara” in the range b4 to b12. =AVERAGE(d4:d12,b4:b12,”sara”,g4:g12,”b”): Returns the average of numbers from cells d4 to d12 by matching two conditions i.e., name “sara” in range b4 to b12 and grade “b” in range g4 to g12. In this method first, you need to select the cells for which you have to calculate the average. Then select the INSERT function from the formulas tab, a dialog box will appear. Select the AVERAGE function from the dialog and enter the cell range for your list of numbers in the number1 box. For example, if you need values from column A and from row 1 to row 10 then simply enter A1:A10. You can also simply drag and drop the selected cells and click OK. The result will be shown in the cell you have selected. Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Delete Blank Columns in Excel? How to Normalize Data in Excel? How to Get Length of Array in Excel VBA? How to Find the Last Used Row and Column in Excel VBA? How to Use Solver in Excel? How to make a 3 Axis Graph using Excel? Introduction to Excel Spreadsheet Macros in Excel How to Create a Macro in Excel? How to Show Percentages in Stacked Column Chart in Excel?
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jul, 2021" }, { "code": null, "e": 269, "s": 28, "text": "The mean (also called average) of the data set is calculated by adding all the numbers in the data set and then dividing it by the total number of values in the data set. In this article, we will find out how to calculate the mean in excel." }, { "code": null, "e": 463, "s": 269, "text": "In this method, we are going to use the AVERAGE function which returns the mean of the arguments. For example, the =AVERAGE(A1:A10) returns the average of the numbers in the range of A1 to A10." }, { "code": null, "e": 471, "s": 463, "text": "Syntax:" }, { "code": null, "e": 502, "s": 471, "text": "AVERAGE(number1,[number2],...)" }, { "code": null, "e": 508, "s": 502, "text": "Here," }, { "code": null, "e": 594, "s": 508, "text": "number1 (Required): The first cell reference or number for which you want the average" }, { "code": null, "e": 710, "s": 594, "text": "number2 (optional): Additional cell references or numbers for which you want the average. The maximum limit is 255." }, { "code": null, "e": 717, "s": 710, "text": "Notes:" }, { "code": null, "e": 808, "s": 717, "text": "arguments can either be numbers or names, ranges, or cell references that contain numbers." }, { "code": null, "e": 968, "s": 808, "text": "If the argument contains text or logical values or empty cells then those values are ignored. However, if the cell contains the value zero then it is included." }, { "code": null, "e": 1078, "s": 968, "text": "if the argument contains error values or text that cannot be translated to numbers then it will cause errors." }, { "code": null, "e": 1195, "s": 1078, "text": "AVERAGE: This function returns the average of cells with any data (logical values or text representation of numbers)" }, { "code": null, "e": 1302, "s": 1195, "text": "AVERAGEIF: This function is used to calculate the average of only the values that meet a single criterion." }, { "code": null, "e": 1389, "s": 1302, "text": "AVERAGEIFS: This function is used to calculate the average based on multiple criteria." }, { "code": null, "e": 1398, "s": 1389, "text": "Example:" }, { "code": null, "e": 1464, "s": 1398, "text": "Let us apply the above formula on some rough data as shown below:" }, { "code": null, "e": 1522, "s": 1464, "text": "In the above example, we have used 4 different functions." }, { "code": null, "e": 1594, "s": 1522, "text": "=AVERAGE(c4:e12): Returns the average of the numbers in cells c4 to e12" }, { "code": null, "e": 1684, "s": 1594, "text": "=AVERAGE(c4:f6,6): Returns the average of the numbers in cells c4 to f6 and the number 6." }, { "code": null, "e": 1824, "s": 1684, "text": "=AVERAGE(b4:b12, “sara”, c4:c12): Returns the average of the numbers in cells c4 to c12 by matching the name “sara” in the range b4 to b12." }, { "code": null, "e": 2017, "s": 1824, "text": "=AVERAGE(d4:d12,b4:b12,”sara”,g4:g12,”b”): Returns the average of numbers from cells d4 to d12 by matching two conditions i.e., name “sara” in range b4 to b12 and grade “b” in range g4 to g12." }, { "code": null, "e": 2194, "s": 2017, "text": "In this method first, you need to select the cells for which you have to calculate the average. Then select the INSERT function from the formulas tab, a dialog box will appear." }, { "code": null, "e": 2528, "s": 2194, "text": "Select the AVERAGE function from the dialog and enter the cell range for your list of numbers in the number1 box. For example, if you need values from column A and from row 1 to row 10 then simply enter A1:A10. You can also simply drag and drop the selected cells and click OK. The result will be shown in the cell you have selected." }, { "code": null, "e": 2535, "s": 2528, "text": "Picked" }, { "code": null, "e": 2541, "s": 2535, "text": "Excel" }, { "code": null, "e": 2639, "s": 2541, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2677, "s": 2639, "text": "How to Delete Blank Columns in Excel?" }, { "code": null, "e": 2709, "s": 2677, "text": "How to Normalize Data in Excel?" }, { "code": null, "e": 2750, "s": 2709, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 2805, "s": 2750, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 2833, "s": 2805, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 2873, "s": 2833, "text": "How to make a 3 Axis Graph using Excel?" }, { "code": null, "e": 2907, "s": 2873, "text": "Introduction to Excel Spreadsheet" }, { "code": null, "e": 2923, "s": 2907, "text": "Macros in Excel" }, { "code": null, "e": 2955, "s": 2923, "text": "How to Create a Macro in Excel?" } ]
SQL Server | STUFF() Function
09 Jul, 2021 There are situations when user want to change some portion of the data inserted. The reason may be because of human error or the change in data. For this purpose, stuff() function comes to action. STUFF() : In SQL Server, stuff() function is used to delete a sequence of given length of characters from the source string and inserting the given sequence of characters from the specified starting index. Syntax: STUFF (source_string, start, length, add_string) Where:- 1. source_string: Original string to be modified. 2. start: The starting index from where the given length of characters will be deleted and new sequence of characters will be inserted. 3. length: The numbers of characters to be deleted from the starting index in the original string. 4. add_string: The new set of characters (string) to be inserted in place of deleted characters from the starting index. Note: It is not necessary to have the length of the new string and number of characters to be deleted the same. Example 1: Output: Example 2: Output: Example 3: Output: abhishek0719kadiyan SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL Trigger | Student Database SQL Interview Questions SQL | Views Difference between DELETE, DROP and TRUNCATE Window functions in SQL MySQL | Group_CONCAT() Function Difference between DDL and DML in DBMS Difference between DELETE and TRUNCATE
[ { "code": null, "e": 53, "s": 25, "text": "\n09 Jul, 2021" }, { "code": null, "e": 251, "s": 53, "text": "There are situations when user want to change some portion of the data inserted. The reason may be because of human error or the change in data. For this purpose, stuff() function comes to action. " }, { "code": null, "e": 458, "s": 251, "text": "STUFF() : In SQL Server, stuff() function is used to delete a sequence of given length of characters from the source string and inserting the given sequence of characters from the specified starting index. " }, { "code": null, "e": 467, "s": 458, "text": "Syntax: " }, { "code": null, "e": 516, "s": 467, "text": "STUFF (source_string, start, length, add_string)" }, { "code": null, "e": 931, "s": 516, "text": "Where:- 1. source_string: Original string to be modified. 2. start: The starting index from where the given length of characters will be deleted and new sequence of characters will be inserted. 3. length: The numbers of characters to be deleted from the starting index in the original string. 4. add_string: The new set of characters (string) to be inserted in place of deleted characters from the starting index. " }, { "code": null, "e": 1044, "s": 931, "text": "Note: It is not necessary to have the length of the new string and number of characters to be deleted the same. " }, { "code": null, "e": 1056, "s": 1044, "text": "Example 1: " }, { "code": null, "e": 1066, "s": 1056, "text": "Output: " }, { "code": null, "e": 1079, "s": 1066, "text": "Example 2: " }, { "code": null, "e": 1089, "s": 1079, "text": "Output: " }, { "code": null, "e": 1102, "s": 1089, "text": "Example 3: " }, { "code": null, "e": 1112, "s": 1102, "text": "Output: " }, { "code": null, "e": 1134, "s": 1114, "text": "abhishek0719kadiyan" }, { "code": null, "e": 1145, "s": 1134, "text": "SQL-Server" }, { "code": null, "e": 1149, "s": 1145, "text": "SQL" }, { "code": null, "e": 1153, "s": 1149, "text": "SQL" }, { "code": null, "e": 1251, "s": 1153, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1262, "s": 1251, "text": "CTE in SQL" }, { "code": null, "e": 1328, "s": 1262, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1359, "s": 1328, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 1383, "s": 1359, "text": "SQL Interview Questions" }, { "code": null, "e": 1395, "s": 1383, "text": "SQL | Views" }, { "code": null, "e": 1440, "s": 1395, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 1464, "s": 1440, "text": "Window functions in SQL" }, { "code": null, "e": 1496, "s": 1464, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 1535, "s": 1496, "text": "Difference between DDL and DML in DBMS" } ]
How to easily initialize a list of Tuples in C#?
Tuple can be used where you want to have a data structure to hold an object with properties, but you don't want to create a separate type for it. The Tuple<T> class was introduced in .NET Framework 4.0. A tuple is a data structure that contains a sequence of elements of different data types. Tuple<int, string, string> person = new Tuple <int, string, string>(1, "Test", "Test1"); A tuple can only include a maximum of eight elements. It gives a compiler error when you try to include more than eight elements. var tupleList = new List<(int, string)> { (1, "cow1"), (5, "chickens1"), (1, "airplane1") }; var tupleArray = new(int, string)[] { (1, "cow1"), (5, "chickens1"), (1, "airplane1") }; var numbers = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9, 10, 11, 12, 13)); Tuple as a Method Parameter static void DisplayTuple(Tuple<int,string,string> person) { } static Tuple<int, string, string> GetTest() { return Tuple.Create(1, "Test1", "Test2"); }
[ { "code": null, "e": 1480, "s": 1187, "text": "Tuple can be used where you want to have a data structure to hold an object with properties, but you don't want to create a separate type for it.\nThe Tuple<T> class was introduced in .NET Framework 4.0. A tuple is a data structure that contains a sequence of elements of different data types." }, { "code": null, "e": 1569, "s": 1480, "text": "Tuple<int, string, string> person =\nnew Tuple <int, string, string>(1, \"Test\", \"Test1\");" }, { "code": null, "e": 1699, "s": 1569, "text": "A tuple can only include a maximum of eight elements. It gives a compiler error when you try to include more than eight elements." }, { "code": null, "e": 1801, "s": 1699, "text": "var tupleList = new List<(int, string)>\n{\n (1, \"cow1\"),\n (5, \"chickens1\"),\n (1, \"airplane1\")\n};" }, { "code": null, "e": 1899, "s": 1801, "text": "var tupleArray = new(int, string)[]\n{\n (1, \"cow1\"),\n (5, \"chickens1\"),\n (1, \"airplane1\")\n};" }, { "code": null, "e": 2074, "s": 1899, "text": "var numbers = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9, 10, 11, 12, 13));\nTuple as a Method Parameter\nstatic void DisplayTuple(Tuple<int,string,string> person)\n{\n}" }, { "code": null, "e": 2167, "s": 2074, "text": "static Tuple<int, string, string> GetTest()\n{\n return Tuple.Create(1, \"Test1\", \"Test2\");\n}" } ]
Output of Java Programs | Set 40 (for loop)
27 Sep, 2017 Prerequisite : Loops in Java 1. what will be the output of the following program? publicclass Test {public static void main(String[] args) { for (int i = 0; i < 10; i++) int x = 10; }} Options:1. No Output2. 103. Compile time error4. 10 (10 times) The answer is option (3) Explanation: Curly braces are optional and without curly braces we can take only one statement under for loop which should not be declarative statement. Here we are declaring a variable that’s why we will get compile time error saying error: variable declaration not allowed here. 2. what will be the output of the following program? publicclass Test {public static void main(String[] args) { for (int i = 0, String = "GFG"; i < 2; i++) System.out.println("HELLO GEEKS"); }} Options:1. HELLO GEEKS2. Compile time error3. HELLO GEEKSHELLO GEEKSHELLO GEEKS4. No Output The answer is option (2) Explanation: Initialization part of the for loop will be executed only once in the for loop life cycle. Here we can declare any number of variables but should be of same type. By mistake if we are trying to declare different data types variables then we will get compile time error saying error: incompatible types: String cannot be converted to int. 3. what will be the output of the following program? publicclass Test {public static void main(String[] args) { int i = 0; for (System.out.println("HI"); i < 1; i++) System.out.println("HELLO GEEKS"); }} Output:1. HIHELLO GEEKS2. No Output3. Compile time error4. HELLO GEEKS The answer is option (1) Explanation:I n the initialization section we can take any valid java statement including System.out.println(). In the for loop initialization section is executed only once that’s why here it will print first HI and after that HELLO GEEKS 4. what will be the output of the following program? publicclass Test {public static void main(String[] args) { for (int i = 0;; i++) System.out.println("HELLO GEEKS"); }} Options:1. Compile time error2. HELLO GEEKS3. HELLO GEEKS (Infinitely)4. Run-time Exception The answer is option (3) Explanation: In the conditional check we can take any valid java statement but should be of type Boolean. If we did not give any statement then it always returns true. 5. what will be the output of the following program? publicclass Test {public static void main(String[] args) { for (int i = 0; i < 1; System.out.println("WELCOME")) System.out.println("GEEKS"); }} Options:1.GEEKSWELCOMEGEEKSWELCOME2.No Output3.Compile time error4.GEEKS WELCOME(Infinitely) Output: The answer is option (4) Explanation: In increment-decrement section we can take any valid java statement including System.out.println(). Here in the increment/decrement section, a statement is there, which result the program to go to infinite loop. This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Sep, 2017" }, { "code": null, "e": 81, "s": 52, "text": "Prerequisite : Loops in Java" }, { "code": null, "e": 134, "s": 81, "text": "1. what will be the output of the following program?" }, { "code": "publicclass Test {public static void main(String[] args) { for (int i = 0; i < 10; i++) int x = 10; }}", "e": 264, "s": 134, "text": null }, { "code": null, "e": 327, "s": 264, "text": "Options:1. No Output2. 103. Compile time error4. 10 (10 times)" }, { "code": null, "e": 352, "s": 327, "text": "The answer is option (3)" }, { "code": null, "e": 633, "s": 352, "text": "Explanation: Curly braces are optional and without curly braces we can take only one statement under for loop which should not be declarative statement. Here we are declaring a variable that’s why we will get compile time error saying error: variable declaration not allowed here." }, { "code": null, "e": 686, "s": 633, "text": "2. what will be the output of the following program?" }, { "code": "publicclass Test {public static void main(String[] args) { for (int i = 0, String = \"GFG\"; i < 2; i++) System.out.println(\"HELLO GEEKS\"); }}", "e": 854, "s": 686, "text": null }, { "code": null, "e": 946, "s": 854, "text": "Options:1. HELLO GEEKS2. Compile time error3. HELLO GEEKSHELLO GEEKSHELLO GEEKS4. No Output" }, { "code": null, "e": 971, "s": 946, "text": "The answer is option (2)" }, { "code": null, "e": 1322, "s": 971, "text": "Explanation: Initialization part of the for loop will be executed only once in the for loop life cycle. Here we can declare any number of variables but should be of same type. By mistake if we are trying to declare different data types variables then we will get compile time error saying error: incompatible types: String cannot be converted to int." }, { "code": null, "e": 1375, "s": 1322, "text": "3. what will be the output of the following program?" }, { "code": "publicclass Test {public static void main(String[] args) { int i = 0; for (System.out.println(\"HI\"); i < 1; i++) System.out.println(\"HELLO GEEKS\"); }}", "e": 1560, "s": 1375, "text": null }, { "code": null, "e": 1631, "s": 1560, "text": "Output:1. HIHELLO GEEKS2. No Output3. Compile time error4. HELLO GEEKS" }, { "code": null, "e": 1656, "s": 1631, "text": "The answer is option (1)" }, { "code": null, "e": 1895, "s": 1656, "text": "Explanation:I n the initialization section we can take any valid java statement including System.out.println(). In the for loop initialization section is executed only once that’s why here it will print first HI and after that HELLO GEEKS" }, { "code": null, "e": 1948, "s": 1895, "text": "4. what will be the output of the following program?" }, { "code": "publicclass Test {public static void main(String[] args) { for (int i = 0;; i++) System.out.println(\"HELLO GEEKS\"); }}", "e": 2094, "s": 1948, "text": null }, { "code": null, "e": 2186, "s": 2094, "text": "Options:1. Compile time error2. HELLO GEEKS3. HELLO GEEKS (Infinitely)4. Run-time Exception" }, { "code": null, "e": 2211, "s": 2186, "text": "The answer is option (3)" }, { "code": null, "e": 2379, "s": 2211, "text": "Explanation: In the conditional check we can take any valid java statement but should be of type Boolean. If we did not give any statement then it always returns true." }, { "code": null, "e": 2432, "s": 2379, "text": "5. what will be the output of the following program?" }, { "code": "publicclass Test {public static void main(String[] args) { for (int i = 0; i < 1; System.out.println(\"WELCOME\")) System.out.println(\"GEEKS\"); }}", "e": 2604, "s": 2432, "text": null }, { "code": null, "e": 2697, "s": 2604, "text": "Options:1.GEEKSWELCOMEGEEKSWELCOME2.No Output3.Compile time error4.GEEKS WELCOME(Infinitely)" }, { "code": null, "e": 2705, "s": 2697, "text": "Output:" }, { "code": null, "e": 2730, "s": 2705, "text": "The answer is option (4)" }, { "code": null, "e": 2955, "s": 2730, "text": "Explanation: In increment-decrement section we can take any valid java statement including System.out.println(). Here in the increment/decrement section, a statement is there, which result the program to go to infinite loop." }, { "code": null, "e": 3261, "s": 2955, "text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 3386, "s": 3261, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3398, "s": 3386, "text": "Java-Output" }, { "code": null, "e": 3413, "s": 3398, "text": "Program Output" } ]
How to design a parking lot using object-oriented principles?
22 Jun, 2018 Design a parking lot using object-oriented principles. Asked In : Amazon, Apple, Google and many more interviews Solution: For our purposes right now, we’ll make the following assumptions. We made these specific assumptions to add a bit of complexity to the problem without adding too much. If you made different assumptions, that’s totally fine.1) The parking lot has multiple levels. Each level has multiple rows of spots.2) The parking lot can park motorcycles, cars, and buses.3) The parking lot has motorcycle spots, compact spots, and large spots.4) A motorcycle can park in any spot.5) A car can park in either a single compact spot or a single large spot.6) A bus can park in five large spots that are consecutive and within the same row. It cannot park in small spots. In the below implementation, we have created an abstract class Vehicle, from which Car, Bus, and Motorcycle inherit. To handle the different parking spot sizes, we have just one class ParkingSpot which has a member variable indicating the size. Main Logic in Java given below // Vehicle and its inherited classes.public enum VehicleSize { Motorcycle, Compact,Large } public abstract class Vehicle{ protected ArrayList<ParkingSpot> parkingSpots = new ArrayList<ParkingSpot>(); protected String licensePlate; protected int spotsNeeded; protected VehicleSize size; public int getSpotsNeeded() { return spotsNeeded; } public VehicleSize getSize() { return size; } /* Park vehicle in this spot (among others, potentially) */ public void parkinSpot(ParkingSpot s) { parkingSpots.add(s); } /* Remove vehicle from spot, and notify spot that it's gone */ public void clearSpots() { ... } /* Checks if the spot is big enough for the vehicle (and is available). This * compares the SIZE only.It does not check if it has enough spots. */ public abstract boolean canFitinSpot(ParkingSpot spot);} public class Bus extends Vehicle{ public Bus() { spotsNeeded = 5; size = VehicleSize.Large; } /* Checks if the spot is a Large. Doesn't check num of spots */ public boolean canFitinSpot(ParkingSpot spot) {... }} public class Car extends Vehicle{ public Car() { spotsNeeded = 1; size = VehicleSize.Compact; } /* Checks if the spot is a Compact or a Large. */ public boolean canFitinSpot(ParkingSpot spot) { ... }} public class Motorcycle extends Vehicle{ public Motorcycle() { spotsNeeded = 1; size = VehicleSize.Motorcycle; } public boolean canFitinSpot(ParkingSpot spot) { ... }} The ParkingSpot is implemented by having just a variable which represents the size of the spot. We could have implemented this by having classes for LargeSpot, CompactSpot, and MotorcycleSpot which inherit from ParkingSpot, but this is probably overkilled. The spots probably do not have different behaviors, other than their sizes. public class ParkingSpot{ private Vehicle vehicle; private VehicleSize spotSize; private int row; private int spotNumber; private Level level; public ParkingSpot(Level lvl, int r, int n, VehicleSize s) { ... } public boolean isAvailable() { return vehicle == null; } /* Check if the spot is big enough and is available */ public boolean canFitVehicle(Vehicle vehicle) { ... } /* Park vehicle in this spot. */ public boolean park(Vehicle v) {..} public int getRow() { return row; } public int getSpotNumber() { return spotNumber; } /* Remove vehicle from spot, and notify level that a new spot is available */ public void removeVehicle() { ... }} Source :www.andiamogo.com/S-OOD.pdf More References :https://www.quora.com/How-do-I-answer-design-related-questions-like-design-a-parking-lot-in-an-Amazon-interviewhttp://stackoverflow.com/questions/764933/amazon-interview-question-design-an-oo-parking-lot This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Design Pattern Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Factory method design pattern in Java Builder Design Pattern Unified Modeling Language (UML) | An Introduction Introduction of Programming Paradigms Unified Modeling Language (UML) | Sequence Diagrams MVC Design Pattern Abstract Factory Pattern Monolithic vs Microservices architecture Composite Design Pattern Unified Modeling Language (UML) | Activity Diagrams
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Jun, 2018" }, { "code": null, "e": 109, "s": 54, "text": "Design a parking lot using object-oriented principles." }, { "code": null, "e": 167, "s": 109, "text": "Asked In : Amazon, Apple, Google and many more interviews" }, { "code": null, "e": 832, "s": 167, "text": "Solution: For our purposes right now, we’ll make the following assumptions. We made these specific assumptions to add a bit of complexity to the problem without adding too much. If you made different assumptions, that’s totally fine.1) The parking lot has multiple levels. Each level has multiple rows of spots.2) The parking lot can park motorcycles, cars, and buses.3) The parking lot has motorcycle spots, compact spots, and large spots.4) A motorcycle can park in any spot.5) A car can park in either a single compact spot or a single large spot.6) A bus can park in five large spots that are consecutive and within the same row. It cannot park in small spots." }, { "code": null, "e": 1077, "s": 832, "text": "In the below implementation, we have created an abstract class Vehicle, from which Car, Bus, and Motorcycle inherit. To handle the different parking spot sizes, we have just one class ParkingSpot which has a member variable indicating the size." }, { "code": null, "e": 1108, "s": 1077, "text": "Main Logic in Java given below" }, { "code": "// Vehicle and its inherited classes.public enum VehicleSize { Motorcycle, Compact,Large } public abstract class Vehicle{ protected ArrayList<ParkingSpot> parkingSpots = new ArrayList<ParkingSpot>(); protected String licensePlate; protected int spotsNeeded; protected VehicleSize size; public int getSpotsNeeded() { return spotsNeeded; } public VehicleSize getSize() { return size; } /* Park vehicle in this spot (among others, potentially) */ public void parkinSpot(ParkingSpot s) { parkingSpots.add(s); } /* Remove vehicle from spot, and notify spot that it's gone */ public void clearSpots() { ... } /* Checks if the spot is big enough for the vehicle (and is available). This * compares the SIZE only.It does not check if it has enough spots. */ public abstract boolean canFitinSpot(ParkingSpot spot);} public class Bus extends Vehicle{ public Bus() { spotsNeeded = 5; size = VehicleSize.Large; } /* Checks if the spot is a Large. Doesn't check num of spots */ public boolean canFitinSpot(ParkingSpot spot) {... }} public class Car extends Vehicle{ public Car() { spotsNeeded = 1; size = VehicleSize.Compact; } /* Checks if the spot is a Compact or a Large. */ public boolean canFitinSpot(ParkingSpot spot) { ... }} public class Motorcycle extends Vehicle{ public Motorcycle() { spotsNeeded = 1; size = VehicleSize.Motorcycle; } public boolean canFitinSpot(ParkingSpot spot) { ... }} ", "e": 2802, "s": 1108, "text": null }, { "code": null, "e": 3135, "s": 2802, "text": "The ParkingSpot is implemented by having just a variable which represents the size of the spot. We could have implemented this by having classes for LargeSpot, CompactSpot, and MotorcycleSpot which inherit from ParkingSpot, but this is probably overkilled. The spots probably do not have different behaviors, other than their sizes." }, { "code": "public class ParkingSpot{ private Vehicle vehicle; private VehicleSize spotSize; private int row; private int spotNumber; private Level level; public ParkingSpot(Level lvl, int r, int n, VehicleSize s) { ... } public boolean isAvailable() { return vehicle == null; } /* Check if the spot is big enough and is available */ public boolean canFitVehicle(Vehicle vehicle) { ... } /* Park vehicle in this spot. */ public boolean park(Vehicle v) {..} public int getRow() { return row; } public int getSpotNumber() { return spotNumber; } /* Remove vehicle from spot, and notify level that a new spot is available */ public void removeVehicle() { ... }}", "e": 3909, "s": 3135, "text": null }, { "code": null, "e": 3945, "s": 3909, "text": "Source :www.andiamogo.com/S-OOD.pdf" }, { "code": null, "e": 4166, "s": 3945, "text": "More References :https://www.quora.com/How-do-I-answer-design-related-questions-like-design-a-parking-lot-in-an-Amazon-interviewhttp://stackoverflow.com/questions/764933/amazon-interview-question-design-an-oo-parking-lot" }, { "code": null, "e": 4472, "s": 4166, "text": "This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 4597, "s": 4472, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4612, "s": 4597, "text": "Design Pattern" }, { "code": null, "e": 4710, "s": 4612, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4748, "s": 4710, "text": "Factory method design pattern in Java" }, { "code": null, "e": 4771, "s": 4748, "text": "Builder Design Pattern" }, { "code": null, "e": 4821, "s": 4771, "text": "Unified Modeling Language (UML) | An Introduction" }, { "code": null, "e": 4859, "s": 4821, "text": "Introduction of Programming Paradigms" }, { "code": null, "e": 4911, "s": 4859, "text": "Unified Modeling Language (UML) | Sequence Diagrams" }, { "code": null, "e": 4930, "s": 4911, "text": "MVC Design Pattern" }, { "code": null, "e": 4955, "s": 4930, "text": "Abstract Factory Pattern" }, { "code": null, "e": 4996, "s": 4955, "text": "Monolithic vs Microservices architecture" }, { "code": null, "e": 5021, "s": 4996, "text": "Composite Design Pattern" } ]
Perl | Subroutines or Functions
13 Jul, 2018 A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again. In Perl, the terms function, subroutine, and method are the same but in some programming languages, these are considered different. The word subroutines is used most in Perl programming because it is created using keyword sub. Whenever there is a call to the function, Perl stop executing all its program and jumps to the function to execute it and then returns back to the section of code that it was running earlier. One can avoid using the return statement. Defining Subroutines: The general form of defining the subroutine in Perl is as follows- sub subroutine_name { # body of method or subroutine } Calling Subroutines: In Perl subroutines can be called by passing the arguments list to it as follows- subroutine_name(aruguments_list); The above way of calling the subroutine will only work with Perl version 5.0 and beyond. Before Perl 5.0 there was another way of calling the subroutine but it is not recommended to use because it bypasses the subroutine prototypes. &subroutine_name(aruguments_list); Example: # Perl Program to demonstrate the # subroutine declaration and calling #!/usr/bin/perl # defining subroutinesub ask_user { print "Hello Geeks!\n";} # calling subroutine# you can also use# &ask_user();ask_user(); Output: Hello Geeks! Passing parameters to subroutines: This is used to pass the values as arguments.This is done using special list array variables ‘$_’. This will assigned to the functions as $_[0], $_[1] and so on. Example: # Perl Program to demonstrate the # Passing parameters to subroutines #!/usr/bin/perl # defining subroutinesub area { # passing argument $side = $_[0]; return ($side * $side);} # calling function$totalArea = area(4); # displaying resultprintf $totalArea; Output: 16 Advantage of using subroutines: It helps us to reuse the code and makes the process of finding error and debug easy. It helps in organizing the code in structural format.Chunks of code is organized in sectional format. It increases the code readability. Perl-method Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jul, 2018" }, { "code": null, "e": 766, "s": 28, "text": "A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again. In Perl, the terms function, subroutine, and method are the same but in some programming languages, these are considered different. The word subroutines is used most in Perl programming because it is created using keyword sub. Whenever there is a call to the function, Perl stop executing all its program and jumps to the function to execute it and then returns back to the section of code that it was running earlier. One can avoid using the return statement." }, { "code": null, "e": 855, "s": 766, "text": "Defining Subroutines: The general form of defining the subroutine in Perl is as follows-" }, { "code": null, "e": 915, "s": 855, "text": "sub subroutine_name\n{\n # body of method or subroutine\n}\n" }, { "code": null, "e": 1018, "s": 915, "text": "Calling Subroutines: In Perl subroutines can be called by passing the arguments list to it as follows-" }, { "code": null, "e": 1052, "s": 1018, "text": "subroutine_name(aruguments_list);" }, { "code": null, "e": 1285, "s": 1052, "text": "The above way of calling the subroutine will only work with Perl version 5.0 and beyond. Before Perl 5.0 there was another way of calling the subroutine but it is not recommended to use because it bypasses the subroutine prototypes." }, { "code": null, "e": 1320, "s": 1285, "text": "&subroutine_name(aruguments_list);" }, { "code": null, "e": 1329, "s": 1320, "text": "Example:" }, { "code": "# Perl Program to demonstrate the # subroutine declaration and calling #!/usr/bin/perl # defining subroutinesub ask_user { print \"Hello Geeks!\\n\";} # calling subroutine# you can also use# &ask_user();ask_user();", "e": 1546, "s": 1329, "text": null }, { "code": null, "e": 1554, "s": 1546, "text": "Output:" }, { "code": null, "e": 1567, "s": 1554, "text": "Hello Geeks!" }, { "code": null, "e": 1764, "s": 1567, "text": "Passing parameters to subroutines: This is used to pass the values as arguments.This is done using special list array variables ‘$_’. This will assigned to the functions as $_[0], $_[1] and so on." }, { "code": null, "e": 1773, "s": 1764, "text": "Example:" }, { "code": "# Perl Program to demonstrate the # Passing parameters to subroutines #!/usr/bin/perl # defining subroutinesub area { # passing argument $side = $_[0]; return ($side * $side);} # calling function$totalArea = area(4); # displaying resultprintf $totalArea;", "e": 2051, "s": 1773, "text": null }, { "code": null, "e": 2059, "s": 2051, "text": "Output:" }, { "code": null, "e": 2062, "s": 2059, "text": "16" }, { "code": null, "e": 2094, "s": 2062, "text": "Advantage of using subroutines:" }, { "code": null, "e": 2179, "s": 2094, "text": "It helps us to reuse the code and makes the process of finding error and debug easy." }, { "code": null, "e": 2281, "s": 2179, "text": "It helps in organizing the code in structural format.Chunks of code is organized in sectional format." }, { "code": null, "e": 2316, "s": 2281, "text": "It increases the code readability." }, { "code": null, "e": 2328, "s": 2316, "text": "Perl-method" }, { "code": null, "e": 2333, "s": 2328, "text": "Perl" }, { "code": null, "e": 2338, "s": 2333, "text": "Perl" } ]
Movie tickets Booking management system in Python
12 Nov, 2021 In this article, we are going to code a simple program for book movie tickets. It will be very useful to the passionate beginners who wanted to work on any project. Write a program to build a simple Movie tickets Booking Management System using Python. We had used six functions as follows : t_movie() theater() timing(a) movie(theater) center() city() Approach: Below is the approach to do the above operations: 1. t_movie: This method is used to select the movie name. #this t_movie function is used to select movie name def t_movie(): global f f = f+1 print("which movie do you want to watch?") print("1,movie 1 ") print("2,movie 2 ") print("3,movie 3") print("4,back") movie = int(input("choose your movie: ")) if movie == 4: # in this it goes to center function and # from center it goes to movie function # and it comes back here and then go to theater center() theater() return 0 if f == 1: theater() 2. theater(): This method is used to select the screen. # this theater function used to select screen def theater(): print("which screen do you want to watch movie: ") print("1,SCREEN 1") print("2,SCREEN 2") print("3,SCREEN 3") a = int(input("choose your screen: ")) ticket = int(input("number of ticket do you want?: ")) timing(a) 3. timing(a): This method is used to select timing for movies. # this timing function used to select timing for movie def timing(a): time1 = { "1": "10.00-1.00", "2": "1.10-4.10", "3": "4.20-7.20", "4": "7.30-10.30" } time2 = { "1": "10.15-1.15", "2": "1.25-4.25", "3": "4.35-7.35", "4": "7.45-10.45" } time3 = { "1": "10.30-1.30", "2": "1.40-4.40", "3": "4.50-7.50", "4": "8.00-10.45" } if a == 1: print("choose your time:") print(time1) t = input("select your time:") x = time1[t] print("successful!, enjoy movie at "+x) elif a == 2: print("choose your time:") print(time2) t = input("select your time:") x = time2[t] print("successful!, enjoy movie at "+x) elif a == 3: print("choose your time:") print(time3) t = input("select your time:") x = time3[t] print("successful!, enjoy movie at "+x) return 0 4. movie(theater): This method is used to select movies accordingly to the theater. def movie(theater): if theater == 1: t_movie() elif theater == 2: t_movie() elif theater == 3: t_movie() elif theater == 4: city() else: print("wrong choice") 5. center(): This method is used to select the theater. def center(): print("which theater do you wish to see movie? ") print("1,Inox") print("2,Icon") print("3,pvp") print("4,back") a = int(input("choose your option: ")) movie(a) return 0 6. city(): This method is used to select the city. # this function is used to select city def city(): print("hi welcome to movie ticket booking: ") print("where you want to watch movie?:") print("1,city 1") print("2,city 2 ") print("3,city 3 ") place = int(input("choose your option: ")) if place == 1: center() elif place == 2: center() elif place == 3: center() else: print("wrong choice") Full implementation: Python3 global ff = 0 #this t_movie function is used to select movie namedef t_movie(): global f f = f+1 print("which movie do you want to watch?") print("1,movie 1 ") print("2,movie 2 ") print("3,movie 3") print("4,back") movie = int(input("choose your movie: ")) if movie == 4: # in this it goes to center function and from center it goes to movie function and it comes back here and then go to theater center() theater() return 0 if f == 1: theater() # this theater function used to select screendef theater(): print("which screen do you want to watch movie: ") print("1,SCREEN 1") print("2,SCREEN 2") print("3,SCREEN 3") a = int(input("choose your screen: ")) ticket = int(input("number of ticket do you want?: ")) timing(a) # this timing function used to select timing for moviedef timing(a): time1 = { "1": "10.00-1.00", "2": "1.10-4.10", "3": "4.20-7.20", "4": "7.30-10.30" } time2 = { "1": "10.15-1.15", "2": "1.25-4.25", "3": "4.35-7.35", "4": "7.45-10.45" } time3 = { "1": "10.30-1.30", "2": "1.40-4.40", "3": "4.50-7.50", "4": "8.00-10.45" } if a == 1: print("choose your time:") print(time1) t = input("select your time:") x = time1[t] print("successful!, enjoy movie at "+x) elif a == 2: print("choose your time:") print(time2) t = input("select your time:") x = time2[t] print("successful!, enjoy movie at "+x) elif a == 3: print("choose your time:") print(time3) t = input("select your time:") x = time3[t] print("successful!, enjoy movie at "+x) return 0 def movie(theater): if theater == 1: t_movie() elif theater == 2: t_movie() elif theater == 3: t_movie() elif theater == 4: city() else: print("wrong choice") def center(): print("which theater do you wish to see movie? ") print("1,Inox") print("2,Icon") print("3,pvp") print("4,back") a = int(input("choose your option: ")) movie(a) return 0 # this function is used to select citydef city(): print("Hi welcome to movie ticket booking: ") print("where you want to watch movie?:") print("1,city 1") print("2,city 2 ") print("3,city 3 ") place = int(input("choose your option: ")) if place == 1: center() elif place == 2: center() elif place == 3: center() else: print("wrong choice") city() # it calls the function city Output: Hi welcome to movie ticket booking: where you want to watch movie?: 1,city 1 2,city 2 3,city 3 choose your option: 2 which theater do you wish to see movie? 1,Inox 2,Icon 3,pvp 4,back choose your option: 1 which movie do you want to watch? 1,movie 1 2,movie 2 3,movie 3 4,back choose your movie: 3 which screen do you want to watch movie: 1,SCREEN 1 2,SCREEN 2 3,SCREEN 3 choose your screen: 1 number of ticket do you want?: 4 choose your time: {‘1’: ‘10.00-1.00’, ‘2’: ‘1.10-4.10’, ‘3’: ‘4.20-7.20’, ‘4’: ‘7.30-10.30’} select your time:2 successful!, enjoy movie at 1.10-4.10 adnanirshad158 clintra school-programming Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Nov, 2021" }, { "code": null, "e": 217, "s": 52, "text": "In this article, we are going to code a simple program for book movie tickets. It will be very useful to the passionate beginners who wanted to work on any project." }, { "code": null, "e": 306, "s": 217, "text": "Write a program to build a simple Movie tickets Booking Management System using Python." }, { "code": null, "e": 345, "s": 306, "text": "We had used six functions as follows :" }, { "code": null, "e": 355, "s": 345, "text": "t_movie()" }, { "code": null, "e": 365, "s": 355, "text": "theater()" }, { "code": null, "e": 375, "s": 365, "text": "timing(a)" }, { "code": null, "e": 390, "s": 375, "text": "movie(theater)" }, { "code": null, "e": 399, "s": 390, "text": "center()" }, { "code": null, "e": 406, "s": 399, "text": "city()" }, { "code": null, "e": 466, "s": 406, "text": "Approach: Below is the approach to do the above operations:" }, { "code": null, "e": 524, "s": 466, "text": "1. t_movie: This method is used to select the movie name." }, { "code": null, "e": 1046, "s": 524, "text": "#this t_movie function is used to select movie name \ndef t_movie():\n global f\n f = f+1\n print(\"which movie do you want to watch?\")\n print(\"1,movie 1 \")\n print(\"2,movie 2 \")\n print(\"3,movie 3\")\n print(\"4,back\")\n movie = int(input(\"choose your movie: \"))\n if movie == 4:\n # in this it goes to center function and\n # from center it goes to movie function \n # and it comes back here and then go to theater \n center()\n theater()\n return 0\n if f == 1:\n theater()" }, { "code": null, "e": 1102, "s": 1046, "text": "2. theater(): This method is used to select the screen." }, { "code": null, "e": 1407, "s": 1102, "text": "# this theater function used to select screen \ndef theater():\n print(\"which screen do you want to watch movie: \")\n print(\"1,SCREEN 1\")\n print(\"2,SCREEN 2\")\n print(\"3,SCREEN 3\")\n a = int(input(\"choose your screen: \"))\n ticket = int(input(\"number of ticket do you want?: \"))\n timing(a)" }, { "code": null, "e": 1470, "s": 1407, "text": "3. timing(a): This method is used to select timing for movies." }, { "code": null, "e": 2470, "s": 1470, "text": "# this timing function used to select timing for movie \ndef timing(a):\n time1 = {\n \"1\": \"10.00-1.00\",\n \"2\": \"1.10-4.10\",\n \"3\": \"4.20-7.20\",\n \"4\": \"7.30-10.30\"\n }\n time2 = {\n \"1\": \"10.15-1.15\",\n \"2\": \"1.25-4.25\",\n \"3\": \"4.35-7.35\",\n \"4\": \"7.45-10.45\"\n }\n time3 = {\n \"1\": \"10.30-1.30\",\n \"2\": \"1.40-4.40\",\n \"3\": \"4.50-7.50\",\n \"4\": \"8.00-10.45\"\n }\n if a == 1:\n print(\"choose your time:\")\n print(time1)\n t = input(\"select your time:\")\n x = time1[t]\n print(\"successful!, enjoy movie at \"+x)\n elif a == 2:\n print(\"choose your time:\")\n print(time2)\n t = input(\"select your time:\")\n x = time2[t]\n print(\"successful!, enjoy movie at \"+x)\n elif a == 3:\n print(\"choose your time:\")\n print(time3)\n t = input(\"select your time:\")\n x = time3[t]\n print(\"successful!, enjoy movie at \"+x)\n return 0" }, { "code": null, "e": 2554, "s": 2470, "text": "4. movie(theater): This method is used to select movies accordingly to the theater." }, { "code": null, "e": 2773, "s": 2554, "text": "def movie(theater):\n if theater == 1:\n t_movie()\n elif theater == 2:\n t_movie()\n elif theater == 3:\n t_movie()\n elif theater == 4:\n city()\n else:\n print(\"wrong choice\")" }, { "code": null, "e": 2829, "s": 2773, "text": "5. center(): This method is used to select the theater." }, { "code": null, "e": 3045, "s": 2829, "text": "def center():\n print(\"which theater do you wish to see movie? \")\n print(\"1,Inox\")\n print(\"2,Icon\")\n print(\"3,pvp\")\n print(\"4,back\")\n a = int(input(\"choose your option: \"))\n movie(a)\n return 0" }, { "code": null, "e": 3096, "s": 3045, "text": "6. city(): This method is used to select the city." }, { "code": null, "e": 3502, "s": 3096, "text": "# this function is used to select city \ndef city():\n print(\"hi welcome to movie ticket booking: \")\n print(\"where you want to watch movie?:\")\n print(\"1,city 1\")\n print(\"2,city 2 \")\n print(\"3,city 3 \")\n place = int(input(\"choose your option: \"))\n if place == 1:\n center()\n elif place == 2:\n center()\n elif place == 3:\n center()\n else:\n print(\"wrong choice\")" }, { "code": null, "e": 3523, "s": 3502, "text": "Full implementation:" }, { "code": null, "e": 3531, "s": 3523, "text": "Python3" }, { "code": "global ff = 0 #this t_movie function is used to select movie namedef t_movie(): global f f = f+1 print(\"which movie do you want to watch?\") print(\"1,movie 1 \") print(\"2,movie 2 \") print(\"3,movie 3\") print(\"4,back\") movie = int(input(\"choose your movie: \")) if movie == 4: # in this it goes to center function and from center it goes to movie function and it comes back here and then go to theater center() theater() return 0 if f == 1: theater() # this theater function used to select screendef theater(): print(\"which screen do you want to watch movie: \") print(\"1,SCREEN 1\") print(\"2,SCREEN 2\") print(\"3,SCREEN 3\") a = int(input(\"choose your screen: \")) ticket = int(input(\"number of ticket do you want?: \")) timing(a) # this timing function used to select timing for moviedef timing(a): time1 = { \"1\": \"10.00-1.00\", \"2\": \"1.10-4.10\", \"3\": \"4.20-7.20\", \"4\": \"7.30-10.30\" } time2 = { \"1\": \"10.15-1.15\", \"2\": \"1.25-4.25\", \"3\": \"4.35-7.35\", \"4\": \"7.45-10.45\" } time3 = { \"1\": \"10.30-1.30\", \"2\": \"1.40-4.40\", \"3\": \"4.50-7.50\", \"4\": \"8.00-10.45\" } if a == 1: print(\"choose your time:\") print(time1) t = input(\"select your time:\") x = time1[t] print(\"successful!, enjoy movie at \"+x) elif a == 2: print(\"choose your time:\") print(time2) t = input(\"select your time:\") x = time2[t] print(\"successful!, enjoy movie at \"+x) elif a == 3: print(\"choose your time:\") print(time3) t = input(\"select your time:\") x = time3[t] print(\"successful!, enjoy movie at \"+x) return 0 def movie(theater): if theater == 1: t_movie() elif theater == 2: t_movie() elif theater == 3: t_movie() elif theater == 4: city() else: print(\"wrong choice\") def center(): print(\"which theater do you wish to see movie? \") print(\"1,Inox\") print(\"2,Icon\") print(\"3,pvp\") print(\"4,back\") a = int(input(\"choose your option: \")) movie(a) return 0 # this function is used to select citydef city(): print(\"Hi welcome to movie ticket booking: \") print(\"where you want to watch movie?:\") print(\"1,city 1\") print(\"2,city 2 \") print(\"3,city 3 \") place = int(input(\"choose your option: \")) if place == 1: center() elif place == 2: center() elif place == 3: center() else: print(\"wrong choice\") city() # it calls the function city", "e": 6135, "s": 3531, "text": null }, { "code": null, "e": 6143, "s": 6135, "text": "Output:" }, { "code": null, "e": 6722, "s": 6143, "text": "Hi welcome to movie ticket booking: where you want to watch movie?: 1,city 1 2,city 2 3,city 3 choose your option: 2 which theater do you wish to see movie? 1,Inox 2,Icon 3,pvp 4,back choose your option: 1 which movie do you want to watch? 1,movie 1 2,movie 2 3,movie 3 4,back choose your movie: 3 which screen do you want to watch movie: 1,SCREEN 1 2,SCREEN 2 3,SCREEN 3 choose your screen: 1 number of ticket do you want?: 4 choose your time: {‘1’: ‘10.00-1.00’, ‘2’: ‘1.10-4.10’, ‘3’: ‘4.20-7.20’, ‘4’: ‘7.30-10.30’} select your time:2 successful!, enjoy movie at 1.10-4.10 " }, { "code": null, "e": 6737, "s": 6722, "text": "adnanirshad158" }, { "code": null, "e": 6745, "s": 6737, "text": "clintra" }, { "code": null, "e": 6764, "s": 6745, "text": "school-programming" }, { "code": null, "e": 6771, "s": 6764, "text": "Python" } ]
GATE | GATE CS 1996 | Question 39
01 Nov, 2017 A binary search tree is generated by inserting in order the following integers: 50, 15, 62, 5, 20, 58, 91, 3, 8, 37, 60, 24 The number of nodes in the left subtree and right subtree of the root respectively is(A) (4, 7)(B) (7, 4)(C) (8, 3)(D) (3, 8)Answer: (B)Explanation:Quiz of this QuestionPlease comment below if you find anything wrong in the above post GATE CS 1996 GATE-GATE CS 1996 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Nov, 2017" }, { "code": null, "e": 134, "s": 54, "text": "A binary search tree is generated by inserting in order the following integers:" }, { "code": null, "e": 180, "s": 134, "text": " 50, 15, 62, 5, 20, 58, 91, 3, 8, 37, 60, 24 " }, { "code": null, "e": 415, "s": 180, "text": "The number of nodes in the left subtree and right subtree of the root respectively is(A) (4, 7)(B) (7, 4)(C) (8, 3)(D) (3, 8)Answer: (B)Explanation:Quiz of this QuestionPlease comment below if you find anything wrong in the above post" }, { "code": null, "e": 428, "s": 415, "text": "GATE CS 1996" }, { "code": null, "e": 446, "s": 428, "text": "GATE-GATE CS 1996" }, { "code": null, "e": 451, "s": 446, "text": "GATE" } ]
How to create a Responsive Sidebar with dropdown menu in ReactJS?
10 Feb, 2021 A sidebar is an important element of a website’s design since it allows users to quickly visit any section within a site. A glimpse of the project: Prerequisite: npmcreate-react-appreact-router-domuseState React hooks npm create-react-app react-router-dom useState React hooks Basic Setup: You will start a new project using create-react-app so open your terminal and type: npx create-react-app react-sidebar-dropdown Now go to your react-sidebar-dropdown folder by typing the given command in the terminal: cd react-sidebar-dropdown Required module: Install the dependencies required in this project by typing the given command in the terminal. npm install react-router-dom npm install --save styled-components npm install --save react-icons Now create the components folder in src then go to the components folder and create three files Sidebar.js, SidebarData.js, and SubMenu.js. Create one more folder in src by the name pages and in pages create files by the name AboutUs.js, ContactUs.js, Events.js, Services.js, Support.js. Project Structure: The file structure in the project will look like this. Filename- Sidebar.js: Open & Close Sidebar View, that’s where the role of useState() hook comes into play. We create a state with the first element sidebar as an initial state having a value of the false and the second element as function setSidebar() for updating the state. Then a function is created by the name showSidebar() which sets the value of the sidebar opposite to its present value whenever it is called. This function is used with the menu bars icon and cross icon with the help of onClick() function. When we click on the bars icon to see the sidenav links it sets the value of the state to true, displays the sidebar and a cross icon appears in place of the bars’ icon. When we want to close the sidebar we simply click on the cross icon and it gets replaced with a bar icon after closing the sidebar because now the value of the state is set to false. Javascript import React, { useState } from "react";import styled from "styled-components";import { Link } from "react-router-dom";import * as FaIcons from "react-icons/fa";import * as AiIcons from "react-icons/ai";import { SidebarData } from "./SidebarData";import SubMenu from "./SubMenu";import { IconContext } from "react-icons/lib"; const Nav = styled.div` background: #15171c; height: 80px; display: flex; justify-content: flex-start; align-items: center;`; const NavIcon = styled(Link)` margin-left: 2rem; font-size: 2rem; height: 80px; display: flex; justify-content: flex-start; align-items: center;`; const SidebarNav = styled.nav` background: #15171c; width: 250px; height: 100vh; display: flex; justify-content: center; position: fixed; top: 0; left: ${({ sidebar }) => (sidebar ? "0" : "-100%")}; transition: 350ms; z-index: 10;`; const SidebarWrap = styled.div` width: 100%;`; const Sidebar = () => { const [sidebar, setSidebar] = useState(false); const showSidebar = () => setSidebar(!sidebar); return ( <> <IconContext.Provider value={{ color: "#fff" }}> <Nav> <NavIcon to="#"> <FaIcons.FaBars onClick={showSidebar} /> </NavIcon> <h1 style={{ textAlign: "center", marginLeft: "200px", color: "green" }} > GeeksforGeeks </h1> </Nav> <SidebarNav sidebar={sidebar}> <SidebarWrap> <NavIcon to="#"> <AiIcons.AiOutlineClose onClick={showSidebar} /> </NavIcon> {SidebarData.map((item, index) => { return <SubMenu item={item} key={index} />; })} </SidebarWrap> </SidebarNav> </IconContext.Provider> </> );}; export default Sidebar; Filename- SidebarData.js: Javascript import React from "react";import * as FaIcons from "react-icons/fa";import * as AiIcons from "react-icons/ai";import * as IoIcons from "react-icons/io";import * as RiIcons from "react-icons/ri"; export const SidebarData = [ { title: "About Us", path: "/about-us", icon: <AiIcons.AiFillHome />, iconClosed: <RiIcons.RiArrowDownSFill />, iconOpened: <RiIcons.RiArrowUpSFill />, subNav: [ { title: "Our Aim", path: "/about-us/aim", icon: <IoIcons.IoIosPaper />, }, { title: "Our Vision", path: "/about-us/vision", icon: <IoIcons.IoIosPaper />, }, ], }, { title: "Services", path: "/services", icon: <IoIcons.IoIosPaper />, iconClosed: <RiIcons.RiArrowDownSFill />, iconOpened: <RiIcons.RiArrowUpSFill />, subNav: [ { title: "Service 1", path: "/services/services1", icon: <IoIcons.IoIosPaper />, cName: "sub-nav", }, { title: "Service 2", path: "/services/services2", icon: <IoIcons.IoIosPaper />, cName: "sub-nav", }, { title: "Service 3", path: "/services/services3", icon: <IoIcons.IoIosPaper />, }, ], }, { title: "Contact", path: "/contact", icon: <FaIcons.FaPhone />, }, { title: "Events", path: "/events", icon: <FaIcons.FaEnvelopeOpenText />, iconClosed: <RiIcons.RiArrowDownSFill />, iconOpened: <RiIcons.RiArrowUpSFill />, subNav: [ { title: "Event 1", path: "/events/events1", icon: <IoIcons.IoIosPaper />, }, { title: "Event 2", path: "/events/events2", icon: <IoIcons.IoIosPaper />, }, ], }, { title: "Support", path: "/support", icon: <IoIcons.IoMdHelpCircle />, },]; Filename- SubMenu.js: The logic for Dropdown links, again done with useState() hooks. We create a state with the first element subnav as an initial state having a value of the false and the second element as function setSubnav() for updating the state. Then a function is created by the name showSubnav() which sets the value of subnav opposite to its present value whenever it is called. This function is used with the open icon and close icon. When we click on the open icon to see the dropdown links it sets the value of the state to true, displays the dropdown menu and a close icon appears in place of the open icon. When we want to close the dropdown links we simply click on the close icon and it gets replaced with an open icon after closing the dropdown menu because now the value of the state is set to false. As every sidelink is not having a dropdown menu, it first checks if a sideline has a property of subNav defined with it from the object array that we made in the SidebarData.js file. If that property exists then it executes the above logic otherwise the sidelinks appear normally without any open and close icons. Javascript import React, { useState } from "react";import { Link } from "react-router-dom";import styled from "styled-components"; const SidebarLink = styled(Link)` display: flex; color: #e1e9fc; justify-content: space-between; align-items: center; padding: 20px; list-style: none; height: 60px; text-decoration: none; font-size: 18px; &:hover { background: #252831; border-left: 4px solid green; cursor: pointer; }`; const SidebarLabel = styled.span` margin-left: 16px;`; const DropdownLink = styled(Link)` background: #252831; height: 60px; padding-left: 3rem; display: flex; align-items: center; text-decoration: none; color: #f5f5f5; font-size: 18px; &:hover { background: green; cursor: pointer; }`; const SubMenu = ({ item }) => { const [subnav, setSubnav] = useState(false); const showSubnav = () => setSubnav(!subnav); return ( <> <SidebarLink to={item.path} onClick={item.subNav && showSubnav}> <div> {item.icon} <SidebarLabel>{item.title}</SidebarLabel> </div> <div> {item.subNav && subnav ? item.iconOpened : item.subNav ? item.iconClosed : null} </div> </SidebarLink> {subnav && item.subNav.map((item, index) => { return ( <DropdownLink to={item.path} key={index}> {item.icon} <SidebarLabel>{item.title}</SidebarLabel> </DropdownLink> ); })} </> );}; export default SubMenu; Now we are completed with the components folder now we manipulate the pages. Edit various pages for the sidebar in the project in src/pages: Filename- AboutUs.js: Javascript import React from "react"; export const AboutUs = () => { return ( <div className="home"> <h1>GeeksforGeeks About us</h1> </div> );}; export const OurAim = () => { return ( <div className="home"> <h1>GeeksforGeeks Aim</h1> </div> );}; export const OurVision = () => { return ( <div className="home"> <h1>GeeksforGeeks Vision</h1> </div> );}; Filename- ContactUs.js: Javascript import React from "react"; const Contact = () => { return ( <div className="contact"> <h1>GeeksforGeeks Contact us</h1> </div> );}; export default Contact; Filename- Events.js: Javascript import React from "react"; export const Events = () => { return ( <div className="events"> <h1>GeeksForGeeks Events</h1> </div> );}; export const EventsOne = () => { return ( <div className="events"> <h1>GeeksforGeeks Event1</h1> </div> );}; export const EventsTwo = () => { return ( <div className="events"> <h1>GeeksforGeeks Event2</h1> </div> );}; Filename- Services.js: Javascript import React from "react"; export const Services = () => { return ( <div className="services"> <h1>GeeksforGeeks Services</h1> </div> );}; export const ServicesOne = () => { return ( <div className="services"> <h1>GeeksforGeeks Service1</h1> </div> );}; export const ServicesTwo = () => { return ( <div className="services"> <h1>GeeksforGeeks Service2</h1> </div> );}; export const ServicesThree = () => { return ( <div className="services"> <h1>GeeksforGeeks Service3</h1> </div> );}; Filename- Support.js: Javascript import React from "react"; const Support = () => { return ( <div className="support"> <h1>GeeksforGeeks Support us</h1> </div> );}; export default Support; All the pages and components are ready now we have to call them one by one in our App.js file. Filename- App.js: Javascript import "./App.css";import Sidebar from "./components/Sidebar";import { BrowserRouter as Router, Switch, Route } from "react-router-dom";import { AboutUs, OurAim, OurVision } from "./pages/AboutUs";import { Services, ServicesOne, ServicesTwo, ServicesThree,} from "./pages/Services";import { Events, EventsOne, EventsTwo } from "./pages/Events";import Contact from "./pages/ContactUs";import Support from "./pages/Support";function App() { return ( <Router> <Sidebar /> <Switch> <Route path="/about-us" exact component={AboutUs} /> <Route path="/about-us/aim" exact component={OurAim} /> <Route path="/about-us/vision" exact component={OurVision} /> <Route path="/services" exact component={Services} /> <Route path="/services/services1" exact component={ServicesOne} /> <Route path="/services/services2" exact component={ServicesTwo} /> <Route path="/services/services3" exact component={ServicesThree} /> <Route path="/contact" exact component={Contact} /> <Route path="/events" exact component={Events} /> <Route path="/events/events1" exact component={EventsOne} /> <Route path="/events/events2" exact component={EventsTwo} /> <Route path="/support" exact component={Support} /> </Switch> </Router> );} export default App; Filename- App.css: modify the CSS according to you. HTML * { box-sizing: border-box; margin: 0; padding: 0;}.home,.services,.reports,.contact,.events,.support { display: flex; margin-left: 260px; font-size: 2rem;} Run the Project: Save all files and start the server by using the below command. npm start Output: React-Questions Technical Scripter 2020 ReactJS Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS setState() How to pass data from one component to other component in ReactJS ? Re-rendering Components in ReactJS ReactJS defaultProps 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? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Feb, 2021" }, { "code": null, "e": 176, "s": 54, "text": "A sidebar is an important element of a website’s design since it allows users to quickly visit any section within a site." }, { "code": null, "e": 203, "s": 176, "text": "A glimpse of the project: " }, { "code": null, "e": 217, "s": 203, "text": "Prerequisite:" }, { "code": null, "e": 273, "s": 217, "text": "npmcreate-react-appreact-router-domuseState React hooks" }, { "code": null, "e": 277, "s": 273, "text": "npm" }, { "code": null, "e": 294, "s": 277, "text": "create-react-app" }, { "code": null, "e": 311, "s": 294, "text": "react-router-dom" }, { "code": null, "e": 332, "s": 311, "text": "useState React hooks" }, { "code": null, "e": 429, "s": 332, "text": "Basic Setup: You will start a new project using create-react-app so open your terminal and type:" }, { "code": null, "e": 473, "s": 429, "text": "npx create-react-app react-sidebar-dropdown" }, { "code": null, "e": 563, "s": 473, "text": "Now go to your react-sidebar-dropdown folder by typing the given command in the terminal:" }, { "code": null, "e": 589, "s": 563, "text": "cd react-sidebar-dropdown" }, { "code": null, "e": 701, "s": 589, "text": "Required module: Install the dependencies required in this project by typing the given command in the terminal." }, { "code": null, "e": 798, "s": 701, "text": "npm install react-router-dom\nnpm install --save styled-components\nnpm install --save react-icons" }, { "code": null, "e": 939, "s": 798, "text": "Now create the components folder in src then go to the components folder and create three files Sidebar.js, SidebarData.js, and SubMenu.js. " }, { "code": null, "e": 1087, "s": 939, "text": "Create one more folder in src by the name pages and in pages create files by the name AboutUs.js, ContactUs.js, Events.js, Services.js, Support.js." }, { "code": null, "e": 1161, "s": 1087, "text": "Project Structure: The file structure in the project will look like this." }, { "code": null, "e": 1268, "s": 1161, "text": "Filename- Sidebar.js: Open & Close Sidebar View, that’s where the role of useState() hook comes into play." }, { "code": null, "e": 1580, "s": 1268, "text": "We create a state with the first element sidebar as an initial state having a value of the false and the second element as function setSidebar() for updating the state. Then a function is created by the name showSidebar() which sets the value of the sidebar opposite to its present value whenever it is called. " }, { "code": null, "e": 2031, "s": 1580, "text": "This function is used with the menu bars icon and cross icon with the help of onClick() function. When we click on the bars icon to see the sidenav links it sets the value of the state to true, displays the sidebar and a cross icon appears in place of the bars’ icon. When we want to close the sidebar we simply click on the cross icon and it gets replaced with a bar icon after closing the sidebar because now the value of the state is set to false." }, { "code": null, "e": 2042, "s": 2031, "text": "Javascript" }, { "code": "import React, { useState } from \"react\";import styled from \"styled-components\";import { Link } from \"react-router-dom\";import * as FaIcons from \"react-icons/fa\";import * as AiIcons from \"react-icons/ai\";import { SidebarData } from \"./SidebarData\";import SubMenu from \"./SubMenu\";import { IconContext } from \"react-icons/lib\"; const Nav = styled.div` background: #15171c; height: 80px; display: flex; justify-content: flex-start; align-items: center;`; const NavIcon = styled(Link)` margin-left: 2rem; font-size: 2rem; height: 80px; display: flex; justify-content: flex-start; align-items: center;`; const SidebarNav = styled.nav` background: #15171c; width: 250px; height: 100vh; display: flex; justify-content: center; position: fixed; top: 0; left: ${({ sidebar }) => (sidebar ? \"0\" : \"-100%\")}; transition: 350ms; z-index: 10;`; const SidebarWrap = styled.div` width: 100%;`; const Sidebar = () => { const [sidebar, setSidebar] = useState(false); const showSidebar = () => setSidebar(!sidebar); return ( <> <IconContext.Provider value={{ color: \"#fff\" }}> <Nav> <NavIcon to=\"#\"> <FaIcons.FaBars onClick={showSidebar} /> </NavIcon> <h1 style={{ textAlign: \"center\", marginLeft: \"200px\", color: \"green\" }} > GeeksforGeeks </h1> </Nav> <SidebarNav sidebar={sidebar}> <SidebarWrap> <NavIcon to=\"#\"> <AiIcons.AiOutlineClose onClick={showSidebar} /> </NavIcon> {SidebarData.map((item, index) => { return <SubMenu item={item} key={index} />; })} </SidebarWrap> </SidebarNav> </IconContext.Provider> </> );}; export default Sidebar;", "e": 3858, "s": 2042, "text": null }, { "code": null, "e": 3884, "s": 3858, "text": "Filename- SidebarData.js:" }, { "code": null, "e": 3895, "s": 3884, "text": "Javascript" }, { "code": "import React from \"react\";import * as FaIcons from \"react-icons/fa\";import * as AiIcons from \"react-icons/ai\";import * as IoIcons from \"react-icons/io\";import * as RiIcons from \"react-icons/ri\"; export const SidebarData = [ { title: \"About Us\", path: \"/about-us\", icon: <AiIcons.AiFillHome />, iconClosed: <RiIcons.RiArrowDownSFill />, iconOpened: <RiIcons.RiArrowUpSFill />, subNav: [ { title: \"Our Aim\", path: \"/about-us/aim\", icon: <IoIcons.IoIosPaper />, }, { title: \"Our Vision\", path: \"/about-us/vision\", icon: <IoIcons.IoIosPaper />, }, ], }, { title: \"Services\", path: \"/services\", icon: <IoIcons.IoIosPaper />, iconClosed: <RiIcons.RiArrowDownSFill />, iconOpened: <RiIcons.RiArrowUpSFill />, subNav: [ { title: \"Service 1\", path: \"/services/services1\", icon: <IoIcons.IoIosPaper />, cName: \"sub-nav\", }, { title: \"Service 2\", path: \"/services/services2\", icon: <IoIcons.IoIosPaper />, cName: \"sub-nav\", }, { title: \"Service 3\", path: \"/services/services3\", icon: <IoIcons.IoIosPaper />, }, ], }, { title: \"Contact\", path: \"/contact\", icon: <FaIcons.FaPhone />, }, { title: \"Events\", path: \"/events\", icon: <FaIcons.FaEnvelopeOpenText />, iconClosed: <RiIcons.RiArrowDownSFill />, iconOpened: <RiIcons.RiArrowUpSFill />, subNav: [ { title: \"Event 1\", path: \"/events/events1\", icon: <IoIcons.IoIosPaper />, }, { title: \"Event 2\", path: \"/events/events2\", icon: <IoIcons.IoIosPaper />, }, ], }, { title: \"Support\", path: \"/support\", icon: <IoIcons.IoMdHelpCircle />, },];", "e": 5705, "s": 3895, "text": null }, { "code": null, "e": 5791, "s": 5705, "text": "Filename- SubMenu.js: The logic for Dropdown links, again done with useState() hooks." }, { "code": null, "e": 6094, "s": 5791, "text": "We create a state with the first element subnav as an initial state having a value of the false and the second element as function setSubnav() for updating the state. Then a function is created by the name showSubnav() which sets the value of subnav opposite to its present value whenever it is called." }, { "code": null, "e": 6525, "s": 6094, "text": "This function is used with the open icon and close icon. When we click on the open icon to see the dropdown links it sets the value of the state to true, displays the dropdown menu and a close icon appears in place of the open icon. When we want to close the dropdown links we simply click on the close icon and it gets replaced with an open icon after closing the dropdown menu because now the value of the state is set to false." }, { "code": null, "e": 6839, "s": 6525, "text": "As every sidelink is not having a dropdown menu, it first checks if a sideline has a property of subNav defined with it from the object array that we made in the SidebarData.js file. If that property exists then it executes the above logic otherwise the sidelinks appear normally without any open and close icons." }, { "code": null, "e": 6850, "s": 6839, "text": "Javascript" }, { "code": "import React, { useState } from \"react\";import { Link } from \"react-router-dom\";import styled from \"styled-components\"; const SidebarLink = styled(Link)` display: flex; color: #e1e9fc; justify-content: space-between; align-items: center; padding: 20px; list-style: none; height: 60px; text-decoration: none; font-size: 18px; &:hover { background: #252831; border-left: 4px solid green; cursor: pointer; }`; const SidebarLabel = styled.span` margin-left: 16px;`; const DropdownLink = styled(Link)` background: #252831; height: 60px; padding-left: 3rem; display: flex; align-items: center; text-decoration: none; color: #f5f5f5; font-size: 18px; &:hover { background: green; cursor: pointer; }`; const SubMenu = ({ item }) => { const [subnav, setSubnav] = useState(false); const showSubnav = () => setSubnav(!subnav); return ( <> <SidebarLink to={item.path} onClick={item.subNav && showSubnav}> <div> {item.icon} <SidebarLabel>{item.title}</SidebarLabel> </div> <div> {item.subNav && subnav ? item.iconOpened : item.subNav ? item.iconClosed : null} </div> </SidebarLink> {subnav && item.subNav.map((item, index) => { return ( <DropdownLink to={item.path} key={index}> {item.icon} <SidebarLabel>{item.title}</SidebarLabel> </DropdownLink> ); })} </> );}; export default SubMenu;", "e": 8386, "s": 6850, "text": null }, { "code": null, "e": 8527, "s": 8386, "text": "Now we are completed with the components folder now we manipulate the pages. Edit various pages for the sidebar in the project in src/pages:" }, { "code": null, "e": 8549, "s": 8527, "text": "Filename- AboutUs.js:" }, { "code": null, "e": 8560, "s": 8549, "text": "Javascript" }, { "code": "import React from \"react\"; export const AboutUs = () => { return ( <div className=\"home\"> <h1>GeeksforGeeks About us</h1> </div> );}; export const OurAim = () => { return ( <div className=\"home\"> <h1>GeeksforGeeks Aim</h1> </div> );}; export const OurVision = () => { return ( <div className=\"home\"> <h1>GeeksforGeeks Vision</h1> </div> );};", "e": 8944, "s": 8560, "text": null }, { "code": null, "e": 8968, "s": 8944, "text": "Filename- ContactUs.js:" }, { "code": null, "e": 8979, "s": 8968, "text": "Javascript" }, { "code": "import React from \"react\"; const Contact = () => { return ( <div className=\"contact\"> <h1>GeeksforGeeks Contact us</h1> </div> );}; export default Contact;", "e": 9150, "s": 8979, "text": null }, { "code": null, "e": 9171, "s": 9150, "text": "Filename- Events.js:" }, { "code": null, "e": 9182, "s": 9171, "text": "Javascript" }, { "code": "import React from \"react\"; export const Events = () => { return ( <div className=\"events\"> <h1>GeeksForGeeks Events</h1> </div> );}; export const EventsOne = () => { return ( <div className=\"events\"> <h1>GeeksforGeeks Event1</h1> </div> );}; export const EventsTwo = () => { return ( <div className=\"events\"> <h1>GeeksforGeeks Event2</h1> </div> );};", "e": 9575, "s": 9182, "text": null }, { "code": null, "e": 9598, "s": 9575, "text": "Filename- Services.js:" }, { "code": null, "e": 9609, "s": 9598, "text": "Javascript" }, { "code": "import React from \"react\"; export const Services = () => { return ( <div className=\"services\"> <h1>GeeksforGeeks Services</h1> </div> );}; export const ServicesOne = () => { return ( <div className=\"services\"> <h1>GeeksforGeeks Service1</h1> </div> );}; export const ServicesTwo = () => { return ( <div className=\"services\"> <h1>GeeksforGeeks Service2</h1> </div> );}; export const ServicesThree = () => { return ( <div className=\"services\"> <h1>GeeksforGeeks Service3</h1> </div> );};", "e": 10151, "s": 9609, "text": null }, { "code": null, "e": 10173, "s": 10151, "text": "Filename- Support.js:" }, { "code": null, "e": 10184, "s": 10173, "text": "Javascript" }, { "code": "import React from \"react\"; const Support = () => { return ( <div className=\"support\"> <h1>GeeksforGeeks Support us</h1> </div> );}; export default Support;", "e": 10355, "s": 10184, "text": null }, { "code": null, "e": 10450, "s": 10355, "text": "All the pages and components are ready now we have to call them one by one in our App.js file." }, { "code": null, "e": 10468, "s": 10450, "text": "Filename- App.js:" }, { "code": null, "e": 10479, "s": 10468, "text": "Javascript" }, { "code": "import \"./App.css\";import Sidebar from \"./components/Sidebar\";import { BrowserRouter as Router, Switch, Route } from \"react-router-dom\";import { AboutUs, OurAim, OurVision } from \"./pages/AboutUs\";import { Services, ServicesOne, ServicesTwo, ServicesThree,} from \"./pages/Services\";import { Events, EventsOne, EventsTwo } from \"./pages/Events\";import Contact from \"./pages/ContactUs\";import Support from \"./pages/Support\";function App() { return ( <Router> <Sidebar /> <Switch> <Route path=\"/about-us\" exact component={AboutUs} /> <Route path=\"/about-us/aim\" exact component={OurAim} /> <Route path=\"/about-us/vision\" exact component={OurVision} /> <Route path=\"/services\" exact component={Services} /> <Route path=\"/services/services1\" exact component={ServicesOne} /> <Route path=\"/services/services2\" exact component={ServicesTwo} /> <Route path=\"/services/services3\" exact component={ServicesThree} /> <Route path=\"/contact\" exact component={Contact} /> <Route path=\"/events\" exact component={Events} /> <Route path=\"/events/events1\" exact component={EventsOne} /> <Route path=\"/events/events2\" exact component={EventsTwo} /> <Route path=\"/support\" exact component={Support} /> </Switch> </Router> );} export default App;", "e": 11817, "s": 10479, "text": null }, { "code": null, "e": 11869, "s": 11817, "text": "Filename- App.css: modify the CSS according to you." }, { "code": null, "e": 11874, "s": 11869, "text": "HTML" }, { "code": "* { box-sizing: border-box; margin: 0; padding: 0;}.home,.services,.reports,.contact,.events,.support { display: flex; margin-left: 260px; font-size: 2rem;}", "e": 12037, "s": 11874, "text": null }, { "code": null, "e": 12118, "s": 12037, "text": "Run the Project: Save all files and start the server by using the below command." }, { "code": null, "e": 12128, "s": 12118, "text": "npm start" }, { "code": null, "e": 12136, "s": 12128, "text": "Output:" }, { "code": null, "e": 12152, "s": 12136, "text": "React-Questions" }, { "code": null, "e": 12176, "s": 12152, "text": "Technical Scripter 2020" }, { "code": null, "e": 12184, "s": 12176, "text": "ReactJS" }, { "code": null, "e": 12203, "s": 12184, "text": "Technical Scripter" }, { "code": null, "e": 12220, "s": 12203, "text": "Web Technologies" }, { "code": null, "e": 12318, "s": 12220, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12356, "s": 12318, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 12375, "s": 12356, "text": "ReactJS setState()" }, { "code": null, "e": 12443, "s": 12375, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 12478, "s": 12443, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 12499, "s": 12478, "text": "ReactJS defaultProps" }, { "code": null, "e": 12532, "s": 12499, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 12594, "s": 12532, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 12655, "s": 12594, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 12705, "s": 12655, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
matplotlib.pyplot.viridis() in Python
22 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. The viridis() function in pyplot module of matplotlib library is used to set the colormap to “viridis”. Syntax: matplotlib.pyplot.viridis() Parameters: This method does not accepts any parameter. Returns: This method does not return any value. Below examples illustrate the matplotlib.pyplot.viridis() function in matplotlib.pyplot: Example #1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np ang = 32rad = 10radm = 0.35radii = np.linspace(radm, 0.95, rad) angles = np.linspace(0, 1.4 * np.pi, ang)angles = np.repeat(angles[..., np.newaxis], rad, axis = 1)angles[:, 1::2] += np.pi / ang x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()z = (np.sin(4 * radii) * np.cos(4 * angles)).flatten() triang = tri.Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1), y[triang.triangles].mean(axis = 1)) < radm) tpc = plt.tripcolor(triang, z, shading ='flat')plt.colorbar(tpc)plt.viridis()plt.title('matplotlib.pyplot.viridis() function Example', fontweight ="bold")plt.show() Output: Example #2: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05x = np.arange(-3.0, 3.0, dx)y = np.arange(-3.0, 3.0, dy)X, Y = np.meshgrid(x, y) extent = np.min(x), np.max(x), np.min(y), np.max(y) Z1 = np.add.outer(range(6), range(6)) % 2plt.imshow(Z1, cmap ="binary_r", interpolation ='nearest', extent = extent, alpha = 1) def geeks(x, y): return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2)) Z2 = geeks(X, Y) plt.imshow(Z2, alpha = 0.7, interpolation ='bilinear', extent = extent)plt.viridis()plt.title('matplotlib.pyplot.viridis() function Example', fontweight ="bold") plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 223, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface." }, { "code": null, "e": 327, "s": 223, "text": "The viridis() function in pyplot module of matplotlib library is used to set the colormap to “viridis”." }, { "code": null, "e": 335, "s": 327, "text": "Syntax:" }, { "code": null, "e": 363, "s": 335, "text": "matplotlib.pyplot.viridis()" }, { "code": null, "e": 419, "s": 363, "text": "Parameters: This method does not accepts any parameter." }, { "code": null, "e": 467, "s": 419, "text": "Returns: This method does not return any value." }, { "code": null, "e": 556, "s": 467, "text": "Below examples illustrate the matplotlib.pyplot.viridis() function in matplotlib.pyplot:" }, { "code": null, "e": 568, "s": 556, "text": "Example #1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np ang = 32rad = 10radm = 0.35radii = np.linspace(radm, 0.95, rad) angles = np.linspace(0, 1.4 * np.pi, ang)angles = np.repeat(angles[..., np.newaxis], rad, axis = 1)angles[:, 1::2] += np.pi / ang x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()z = (np.sin(4 * radii) * np.cos(4 * angles)).flatten() triang = tri.Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1), y[triang.triangles].mean(axis = 1)) < radm) tpc = plt.tripcolor(triang, z, shading ='flat')plt.colorbar(tpc)plt.viridis()plt.title('matplotlib.pyplot.viridis() function Example', fontweight =\"bold\")plt.show()", "e": 1418, "s": 568, "text": null }, { "code": null, "e": 1426, "s": 1418, "text": "Output:" }, { "code": null, "e": 1438, "s": 1426, "text": "Example #2:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05x = np.arange(-3.0, 3.0, dx)y = np.arange(-3.0, 3.0, dy)X, Y = np.meshgrid(x, y) extent = np.min(x), np.max(x), np.min(y), np.max(y) Z1 = np.add.outer(range(6), range(6)) % 2plt.imshow(Z1, cmap =\"binary_r\", interpolation ='nearest', extent = extent, alpha = 1) def geeks(x, y): return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2)) Z2 = geeks(X, Y) plt.imshow(Z2, alpha = 0.7, interpolation ='bilinear', extent = extent)plt.viridis()plt.title('matplotlib.pyplot.viridis() function Example', fontweight =\"bold\") plt.show()", "e": 2250, "s": 1438, "text": null }, { "code": null, "e": 2258, "s": 2250, "text": "Output:" }, { "code": null, "e": 2276, "s": 2258, "text": "Python-matplotlib" }, { "code": null, "e": 2283, "s": 2276, "text": "Python" }, { "code": null, "e": 2381, "s": 2283, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2399, "s": 2381, "text": "Python Dictionary" }, { "code": null, "e": 2441, "s": 2399, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2463, "s": 2441, "text": "Enumerate() in Python" }, { "code": null, "e": 2498, "s": 2463, "text": "Read a file line by line in Python" }, { "code": null, "e": 2524, "s": 2498, "text": "Python String | replace()" }, { "code": null, "e": 2556, "s": 2524, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2585, "s": 2556, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2612, "s": 2585, "text": "Python Classes and Objects" }, { "code": null, "e": 2642, "s": 2612, "text": "Iterate over a list in Python" } ]
Tree View Component in ReactJS
29 Dec, 2021 Tree Views are used often to display directory trees of file systems or multiple options in a hierarchical structure. A navigator icon denotes whether an option is in an expanded state or not, then displays the items inside it in an indented section below it. It’s very prominent in sidebars of websites like Gmail to display options and sub-options together. Creating React Application And Installing Module: Step 1: Create a React application using the following command. npx create-react-app gfg Step 2: After creating your project folder i.e. gfg, move to it using the following command. cd gfg Step 3: After creating the ReactJS application, Install the material-ui modules using the following command. npm install @material-ui/core npm install @material-ui/icons npm install @material-ui/lab We’ll require the Material-UI lab module for the TreeView component and the icons module for the icons. Run the following commands in your terminal in your project directory to install these modules. Importing TreeView: You can import <TreeView /> component from @material-ui/lab using the following code. import { TreeView } from '@material-ui/lab'; Example: We’ll create a small tree view like the one in the GeeksforGeeks website sidebar. Create a new file trees.js in the src folder where we’ll define our component. Project directory: Create trees.js file. TreeView component in Material-UI: The TreeView component has some useful props: defaultCollapseIcon – To specify the icon used to collapse the node. defaultExpandIcon – To specify the icon used to expand the node. multiselect – A bool value which when true triggers multiselect upon pressing ctrl and shift. Creating the Trees Component: The GeeksforGeeks website has a sidebar menu in a tree-like structure with many sections like Home, Courses, Data Structures, Algorithms, etc. We’ll create a similar, smaller version to understand how to use the TreeView component. The <TreeView> component is the topmost component in which the entire tree structure is defined. <TreeView> </TreeView> Each node is then defined using the TreeItem component which has two major props – a unique node id and a label. The label is where you can define what element would the node be, a button, a styled div, or a list item. Here we’ll use a list item. <TreeItem nodeId="1" label={ <ListItem button component="a" href="#"> <ListItemText primary="Home" /> </ListItem>}> </TreeItem> Now each such node can be further nested as per the requirement, thus defining a tree-like structure. Example: Filename: trees.js Javascript import React, { Component } from 'react';import { makeStyles } from '@material-ui/core/styles';import clsx from 'clsx';import AppBar from '@material-ui/core/AppBar';import Toolbar from '@material-ui/core/Toolbar';import IconButton from '@material-ui/core/IconButton';import MenuIcon from '@material-ui/icons/Menu';import List from '@material-ui/core/List';import ListItem from '@material-ui/core/ListItem';import ListItemText from '@material-ui/core/ListItemText';import Drawer from '@material-ui/core/Drawer';import { useTheme } from '@material-ui/core/styles';import { TreeView } from '@material-ui/lab';import TreeItem from '@material-ui/lab/TreeItem'; const drawerWidth = 240; const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, paddingTop: 5, }, appbar: { background: 'transparent', boxShadow: 'none', }, drawerPaper: { position: 'relative', whiteSpace: 'nowrap', width: drawerWidth, transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), }, drawerPaperClose: { overflowX: 'hidden', transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), width: theme.spacing(7), [theme.breakpoints.up('sm')]: { width: theme.spacing(9), }, },})); export default function Trees() { const theme = useTheme(); const classes = useStyles(theme); const [open, setOpen] = React.useState(false); function handleDrawer() { setOpen(!open); } return ( <div className={classes.root}> {/* AppBar part - Only contains a menu icon*/} <AppBar position="static" color="primary" elevation={0}> <Toolbar variant="dense"> {/* Menu icon onclick handler should open the drawer, hence we change the state 'open' to true*/} <IconButton edge="start" style={{ color: theme.palette.secondary.icons }} aria-label="menu" onClick={() => { handleDrawer() }}> <MenuIcon /> </IconButton> </Toolbar> </AppBar> {/* Drawer (can be placed anywhere in template) */} <Drawer variant="temporary" classes={{ paper: clsx(classes.drawerPaper, !open && classes.drawerPaperClose), }} open={open}> <List> <div> {/* Tree Structure */} <TreeView> <TreeItem nodeId="1" label={ <ListItem button component="a" href="#"> <ListItemText primary="Home" /> </ListItem>}> </TreeItem> <TreeItem nodeId="2" label={ <ListItem button component="a" href="#"> <ListItemText primary="Data Structures" /> </ListItem>}> <TreeItem nodeId="6" label={ <ListItem button component="a" href="#"> <ListItemText primary="Arrays" /> </ListItem>}> </TreeItem> <TreeItem nodeId="7" label={ <ListItem button component="a" href="#"> <ListItemText primary="Linked List" /> </ListItem>}> </TreeItem> </TreeItem> <TreeItem nodeId="3" label={ <ListItem button component="a" href="#"> <ListItemText primary="Algortihms" /> </ListItem>}> <TreeItem nodeId="8" label={ <ListItem button component="a" href="#"> <ListItemText primary="Searching" /> </ListItem>}> </TreeItem> <TreeItem nodeId="9" label={ <ListItem button component="a" href="#"> <ListItemText primary="Sorting" /> </ListItem>}> </TreeItem> </TreeItem> <TreeItem nodeId="4" label={ <ListItem button component="a" href="#"> <ListItemText primary="Languages" /> </ListItem>}> <TreeItem nodeId="10" label={ <ListItem button component="a" href="#"> <ListItemText primary="C++" /> </ListItem>}> </TreeItem> <TreeItem nodeId="11" label={ <ListItem button component="a" href="#"> <ListItemText primary="Java" /> </ListItem>}> </TreeItem> <TreeItem nodeId="12" label={ <ListItem button component="a" href="#"> <ListItemText primary="Python" /> </ListItem>}> </TreeItem> <TreeItem nodeId="13" label={ <ListItem button component="a" href="#"> <ListItemText primary="JavaScript" /> </ListItem>}> </TreeItem> </TreeItem> <TreeItem nodeId="5" label={ <ListItem button component="a" href="#"> <ListItemText primary="GBlog" /> </ListItem>}></TreeItem> </TreeView> </div> </List> </Drawer> {/* End-Drawer */} </div> );} Filename: App.js Javascript import React, { Component } from 'react';import CssBaseline from '@material-ui/core/CssBaseline';import Container from '@material-ui/core/Container';import Typography from '@material-ui/core/Typography';import Trees from './trees'; class GFG extends Component { render() { return ( <React.Fragment> <CssBaseline /> <Trees></Trees> <br></br> <Container maxWidth="sm"> <Typography component="h1" variant="h1" align="center" gutterBottom> Geeks for Geeks </Typography> <br /> <Typography component="h3" variant="h3" align="center" gutterBottom> TreeView Component </Typography> </Container> </React.Fragment> ); }} export default GFG; Step to Run Application: Run the application using the following command from the root directory of the project. npm start Output: Reference Link: https://material-ui.com/components/tree-view/ ruhelaa48 simmytarika5 Material-UI React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS useNavigate() Hook How to install bootstrap in React.js ? How to create a multi-page website using React.js ? How to do crud operations in ReactJS ? 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? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Dec, 2021" }, { "code": null, "e": 388, "s": 28, "text": "Tree Views are used often to display directory trees of file systems or multiple options in a hierarchical structure. A navigator icon denotes whether an option is in an expanded state or not, then displays the items inside it in an indented section below it. It’s very prominent in sidebars of websites like Gmail to display options and sub-options together." }, { "code": null, "e": 438, "s": 388, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 502, "s": 438, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 527, "s": 502, "text": "npx create-react-app gfg" }, { "code": null, "e": 620, "s": 527, "text": "Step 2: After creating your project folder i.e. gfg, move to it using the following command." }, { "code": null, "e": 627, "s": 620, "text": "cd gfg" }, { "code": null, "e": 736, "s": 627, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command." }, { "code": null, "e": 826, "s": 736, "text": "npm install @material-ui/core\nnpm install @material-ui/icons\nnpm install @material-ui/lab" }, { "code": null, "e": 1026, "s": 826, "text": "We’ll require the Material-UI lab module for the TreeView component and the icons module for the icons. Run the following commands in your terminal in your project directory to install these modules." }, { "code": null, "e": 1132, "s": 1026, "text": "Importing TreeView: You can import <TreeView /> component from @material-ui/lab using the following code." }, { "code": null, "e": 1177, "s": 1132, "text": "import { TreeView } from '@material-ui/lab';" }, { "code": null, "e": 1347, "s": 1177, "text": "Example: We’ll create a small tree view like the one in the GeeksforGeeks website sidebar. Create a new file trees.js in the src folder where we’ll define our component." }, { "code": null, "e": 1388, "s": 1347, "text": "Project directory: Create trees.js file." }, { "code": null, "e": 1469, "s": 1388, "text": "TreeView component in Material-UI: The TreeView component has some useful props:" }, { "code": null, "e": 1538, "s": 1469, "text": "defaultCollapseIcon – To specify the icon used to collapse the node." }, { "code": null, "e": 1603, "s": 1538, "text": "defaultExpandIcon – To specify the icon used to expand the node." }, { "code": null, "e": 1697, "s": 1603, "text": "multiselect – A bool value which when true triggers multiselect upon pressing ctrl and shift." }, { "code": null, "e": 1959, "s": 1697, "text": "Creating the Trees Component: The GeeksforGeeks website has a sidebar menu in a tree-like structure with many sections like Home, Courses, Data Structures, Algorithms, etc. We’ll create a similar, smaller version to understand how to use the TreeView component." }, { "code": null, "e": 2056, "s": 1959, "text": "The <TreeView> component is the topmost component in which the entire tree structure is defined." }, { "code": null, "e": 2079, "s": 2056, "text": "<TreeView> </TreeView>" }, { "code": null, "e": 2326, "s": 2079, "text": "Each node is then defined using the TreeItem component which has two major props – a unique node id and a label. The label is where you can define what element would the node be, a button, a styled div, or a list item. Here we’ll use a list item." }, { "code": null, "e": 2470, "s": 2326, "text": "<TreeItem nodeId=\"1\" label={\n <ListItem button component=\"a\" href=\"#\">\n <ListItemText primary=\"Home\" />\n </ListItem>}>\n</TreeItem>" }, { "code": null, "e": 2572, "s": 2470, "text": "Now each such node can be further nested as per the requirement, thus defining a tree-like structure." }, { "code": null, "e": 2581, "s": 2572, "text": "Example:" }, { "code": null, "e": 2600, "s": 2581, "text": "Filename: trees.js" }, { "code": null, "e": 2611, "s": 2600, "text": "Javascript" }, { "code": "import React, { Component } from 'react';import { makeStyles } from '@material-ui/core/styles';import clsx from 'clsx';import AppBar from '@material-ui/core/AppBar';import Toolbar from '@material-ui/core/Toolbar';import IconButton from '@material-ui/core/IconButton';import MenuIcon from '@material-ui/icons/Menu';import List from '@material-ui/core/List';import ListItem from '@material-ui/core/ListItem';import ListItemText from '@material-ui/core/ListItemText';import Drawer from '@material-ui/core/Drawer';import { useTheme } from '@material-ui/core/styles';import { TreeView } from '@material-ui/lab';import TreeItem from '@material-ui/lab/TreeItem'; const drawerWidth = 240; const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, paddingTop: 5, }, appbar: { background: 'transparent', boxShadow: 'none', }, drawerPaper: { position: 'relative', whiteSpace: 'nowrap', width: drawerWidth, transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), }, drawerPaperClose: { overflowX: 'hidden', transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), width: theme.spacing(7), [theme.breakpoints.up('sm')]: { width: theme.spacing(9), }, },})); export default function Trees() { const theme = useTheme(); const classes = useStyles(theme); const [open, setOpen] = React.useState(false); function handleDrawer() { setOpen(!open); } return ( <div className={classes.root}> {/* AppBar part - Only contains a menu icon*/} <AppBar position=\"static\" color=\"primary\" elevation={0}> <Toolbar variant=\"dense\"> {/* Menu icon onclick handler should open the drawer, hence we change the state 'open' to true*/} <IconButton edge=\"start\" style={{ color: theme.palette.secondary.icons }} aria-label=\"menu\" onClick={() => { handleDrawer() }}> <MenuIcon /> </IconButton> </Toolbar> </AppBar> {/* Drawer (can be placed anywhere in template) */} <Drawer variant=\"temporary\" classes={{ paper: clsx(classes.drawerPaper, !open && classes.drawerPaperClose), }} open={open}> <List> <div> {/* Tree Structure */} <TreeView> <TreeItem nodeId=\"1\" label={ <ListItem button component=\"a\" href=\"#\"> <ListItemText primary=\"Home\" /> </ListItem>}> </TreeItem> <TreeItem nodeId=\"2\" label={ <ListItem button component=\"a\" href=\"#\"> <ListItemText primary=\"Data Structures\" /> </ListItem>}> <TreeItem nodeId=\"6\" label={ <ListItem button component=\"a\" href=\"#\"> <ListItemText primary=\"Arrays\" /> </ListItem>}> </TreeItem> <TreeItem nodeId=\"7\" label={ <ListItem button component=\"a\" href=\"#\"> <ListItemText primary=\"Linked List\" /> </ListItem>}> </TreeItem> </TreeItem> <TreeItem nodeId=\"3\" label={ <ListItem button component=\"a\" href=\"#\"> <ListItemText primary=\"Algortihms\" /> </ListItem>}> <TreeItem nodeId=\"8\" label={ <ListItem button component=\"a\" href=\"#\"> <ListItemText primary=\"Searching\" /> </ListItem>}> </TreeItem> <TreeItem nodeId=\"9\" label={ <ListItem button component=\"a\" href=\"#\"> <ListItemText primary=\"Sorting\" /> </ListItem>}> </TreeItem> </TreeItem> <TreeItem nodeId=\"4\" label={ <ListItem button component=\"a\" href=\"#\"> <ListItemText primary=\"Languages\" /> </ListItem>}> <TreeItem nodeId=\"10\" label={ <ListItem button component=\"a\" href=\"#\"> <ListItemText primary=\"C++\" /> </ListItem>}> </TreeItem> <TreeItem nodeId=\"11\" label={ <ListItem button component=\"a\" href=\"#\"> <ListItemText primary=\"Java\" /> </ListItem>}> </TreeItem> <TreeItem nodeId=\"12\" label={ <ListItem button component=\"a\" href=\"#\"> <ListItemText primary=\"Python\" /> </ListItem>}> </TreeItem> <TreeItem nodeId=\"13\" label={ <ListItem button component=\"a\" href=\"#\"> <ListItemText primary=\"JavaScript\" /> </ListItem>}> </TreeItem> </TreeItem> <TreeItem nodeId=\"5\" label={ <ListItem button component=\"a\" href=\"#\"> <ListItemText primary=\"GBlog\" /> </ListItem>}></TreeItem> </TreeView> </div> </List> </Drawer> {/* End-Drawer */} </div> );}", "e": 9364, "s": 2611, "text": null }, { "code": null, "e": 9381, "s": 9364, "text": "Filename: App.js" }, { "code": null, "e": 9392, "s": 9381, "text": "Javascript" }, { "code": "import React, { Component } from 'react';import CssBaseline from '@material-ui/core/CssBaseline';import Container from '@material-ui/core/Container';import Typography from '@material-ui/core/Typography';import Trees from './trees'; class GFG extends Component { render() { return ( <React.Fragment> <CssBaseline /> <Trees></Trees> <br></br> <Container maxWidth=\"sm\"> <Typography component=\"h1\" variant=\"h1\" align=\"center\" gutterBottom> Geeks for Geeks </Typography> <br /> <Typography component=\"h3\" variant=\"h3\" align=\"center\" gutterBottom> TreeView Component </Typography> </Container> </React.Fragment> ); }} export default GFG;", "e": 10335, "s": 9392, "text": null }, { "code": null, "e": 10448, "s": 10335, "text": "Step to Run Application: Run the application using the following command from the root directory of the project." }, { "code": null, "e": 10458, "s": 10448, "text": "npm start" }, { "code": null, "e": 10466, "s": 10458, "text": "Output:" }, { "code": null, "e": 10528, "s": 10466, "text": "Reference Link: https://material-ui.com/components/tree-view/" }, { "code": null, "e": 10538, "s": 10528, "text": "ruhelaa48" }, { "code": null, "e": 10551, "s": 10538, "text": "simmytarika5" }, { "code": null, "e": 10563, "s": 10551, "text": "Material-UI" }, { "code": null, "e": 10579, "s": 10563, "text": "React-Questions" }, { "code": null, "e": 10587, "s": 10579, "text": "ReactJS" }, { "code": null, "e": 10604, "s": 10587, "text": "Web Technologies" }, { "code": null, "e": 10702, "s": 10604, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10740, "s": 10702, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 10767, "s": 10740, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 10806, "s": 10767, "text": "How to install bootstrap in React.js ?" }, { "code": null, "e": 10858, "s": 10806, "text": "How to create a multi-page website using React.js ?" }, { "code": null, "e": 10897, "s": 10858, "text": "How to do crud operations in ReactJS ?" }, { "code": null, "e": 10930, "s": 10897, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 10992, "s": 10930, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 11053, "s": 10992, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 11103, "s": 11053, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to play audio file from the assets directory in Android?
This example demonstrates how do I play audio file from the assets directory in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/btnPlayAudio" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" Play audio" android:textStyle="italic" android:layout_centerInParent="true" /> </RelativeLayout> Step 3 − Create a asset folder, Right click on the project → New → Folder → Asset Folder.Copy and paste the audio file into the assets folder. Step 4 − Add the following code to src/MainActivity.java import android.content.res.AssetFileDescriptor; import android.media.MediaPlayer; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import java.io.IOException; public class MainActivity extends AppCompatActivity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.btnPlayAudio); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MediaPlayer mediaPlayer = new MediaPlayer(); AssetFileDescriptor afd; try { afd = getAssets().openFd("audio.mp3"); mediaPlayer.setDataSource(afd.getFileDescriptor()); mediaPlayer.prepare(); mediaPlayer.start(); } catch (IOException e) { e.printStackTrace(); } Toast.makeText(MainActivity.this, "Playing audio from Asset directory", Toast.LENGTH_SHORT).show(); } }); } } Step 5 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1276, "s": 1187, "text": "This example demonstrates how do I play audio file from the assets directory in android." }, { "code": null, "e": 1405, "s": 1276, "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": 1470, "s": 1405, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2013, "s": 1470, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/btnPlayAudio\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\" Play audio\"\n android:textStyle=\"italic\"\n android:layout_centerInParent=\"true\" />\n</RelativeLayout>" }, { "code": null, "e": 2156, "s": 2013, "text": "Step 3 − Create a asset folder, Right click on the project → New → Folder → Asset Folder.Copy and paste the audio file into the assets folder." }, { "code": null, "e": 2213, "s": 2156, "text": "Step 4 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3438, "s": 2213, "text": "import android.content.res.AssetFileDescriptor;\nimport android.media.MediaPlayer;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.Toast;\nimport java.io.IOException;\npublic class MainActivity extends AppCompatActivity {\n Button button;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n button = findViewById(R.id.btnPlayAudio);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n MediaPlayer mediaPlayer = new MediaPlayer();\n AssetFileDescriptor afd;\n try {\n afd = getAssets().openFd(\"audio.mp3\");\n mediaPlayer.setDataSource(afd.getFileDescriptor());\n mediaPlayer.prepare();\n mediaPlayer.start();\n } catch (IOException e) {\n e.printStackTrace();\n }\n Toast.makeText(MainActivity.this, \"Playing\n audio from Asset directory\",\n Toast.LENGTH_SHORT).show();\n }\n });\n }\n}" }, { "code": null, "e": 3493, "s": 3438, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4163, "s": 3493, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4510, "s": 4163, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 4551, "s": 4510, "text": "Click here to download the project code." } ]
Flutter – Circular reveal Animation
15 Feb, 2021 The Circular Reveal Animation in Flutter is inspired by ViewAnimationUtils.createCircularReveal(...). It does exactly what the name suggests, meaning it is used to reveal content generally an image circularly where the circle grows bigger and makes the image visible. In this article, we will implement a simple Circular Reveal Animation through a simple application. To build the same follow the below steps: Add the dependency to pubspec.yaml file. Create an image directory and add the images that are to be revealed in the same. Activate the assets in the pubspec.yaml file Import the dependency to main.dart file Create the root of the application by extending a StatelessWidget Design the Homepage by extending a StatefulWidget In the body of the Homepage call the CircularRevealAnimation(). Add a floatingActionButton and assign an action to it to reveal the image. Let’s look into the steps in detail. Add the circular_reveal_animation dependency into the dependencies section of the pubspec.yaml file as shown below: Dependency The images that are to be revealed using the circular reveal animation can be added to an image directory inside the assets directory as shown below: Adding Images In the pubspec.yanl file, the assets can be activated to be used in the application by adding a path to the image as shown below under the assets section: Activating Assets Use the below line of code in the main.dart file to use the circular_reveal_animation dependency: import 'package:circular_reveal_animation/circular_reveal_animation.dart'; Extend a StatelessWidget to create a root for the application as shown below: Dart class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksForGeeks', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), ); }} Extend a StatefulWidget to an appbar and a body to create a plane Homepage for the application as shown below: Dart class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin { AnimationController animationController; Animation<double> animation; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("GeeksForGeeks"), backgroundColor: Colors.green, ), body: ), In the body of the Homepage make a call to the CircularRevealAnimation() function and add the images to the same as shown below: Dart body: Padding( padding: const EdgeInsets.all(16.0), child: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ SizedBox(height: 16), CircularRevealAnimation( child: Image.asset('assets/wonderwomen.jpg'), animation: animation, centerAlignment: Alignment.centerRight, centerOffset: Offset(130, 100), minRadius: 12, maxRadius: 200, ), ], ), ), ), Add a FloatingActionButton and assign the action to it that calls the CircularRevealAnimation() from the dependency on pressed as shown below: Dart floatingActionButton: FloatingActionButton( backgroundColor: Colors.green, onPressed: () { if (animationController.status == AnimationStatus.forward || animationController.status == AnimationStatus.completed) { animationController.reverse(); } else { animationController.forward(); } }), ); Complete Source Code: Dart import 'package:circular_reveal_animation/circular_reveal_animation.dart';import 'package:flutter/material.dart'; void main() => runApp(MyApp()); // rootclass MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksForGeeks', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), ); }} // Homepageclass MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin { AnimationController animationController; Animation<double> animation; // initialize state @override void initState() { super.initState(); animationController = AnimationController( vsync: this, duration: Duration(milliseconds: 1000), ); animation = CurvedAnimation( parent: animationController, curve: Curves.easeIn, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("GeeksForGeeks"), backgroundColor: Colors.green, ), body: Padding( padding: const EdgeInsets.all(16.0), child: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ SizedBox(height: 16), CircularRevealAnimation( child: Image.asset('assets/wonderwomen.jpg'), animation: animation, centerAlignment: Alignment.centerRight, centerOffset: Offset(130, 100), minRadius: 12, maxRadius: 200, ), ], ), ), ), // button with assigned action floatingActionButton: FloatingActionButton( backgroundColor: Colors.green, onPressed: () { if (animationController.status == AnimationStatus.forward || animationController.status == AnimationStatus.completed) { animationController.reverse(); } else { animationController.forward(); } }), ); } } Output: android Flutter Flutter UI-components Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ListView Class in Flutter Flutter - Search Bar Flutter - Dialogs Flutter - FutureBuilder Widget Flutter - Flexible Widget Flutter Tutorial Flutter - Search Bar Flutter - Dialogs Flutter - FutureBuilder Widget Flutter - Flexible Widget
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Feb, 2021" }, { "code": null, "e": 296, "s": 28, "text": "The Circular Reveal Animation in Flutter is inspired by ViewAnimationUtils.createCircularReveal(...). It does exactly what the name suggests, meaning it is used to reveal content generally an image circularly where the circle grows bigger and makes the image visible." }, { "code": null, "e": 438, "s": 296, "text": "In this article, we will implement a simple Circular Reveal Animation through a simple application. To build the same follow the below steps:" }, { "code": null, "e": 479, "s": 438, "text": "Add the dependency to pubspec.yaml file." }, { "code": null, "e": 561, "s": 479, "text": "Create an image directory and add the images that are to be revealed in the same." }, { "code": null, "e": 606, "s": 561, "text": "Activate the assets in the pubspec.yaml file" }, { "code": null, "e": 646, "s": 606, "text": "Import the dependency to main.dart file" }, { "code": null, "e": 712, "s": 646, "text": "Create the root of the application by extending a StatelessWidget" }, { "code": null, "e": 762, "s": 712, "text": "Design the Homepage by extending a StatefulWidget" }, { "code": null, "e": 826, "s": 762, "text": "In the body of the Homepage call the CircularRevealAnimation()." }, { "code": null, "e": 901, "s": 826, "text": "Add a floatingActionButton and assign an action to it to reveal the image." }, { "code": null, "e": 938, "s": 901, "text": "Let’s look into the steps in detail." }, { "code": null, "e": 1054, "s": 938, "text": "Add the circular_reveal_animation dependency into the dependencies section of the pubspec.yaml file as shown below:" }, { "code": null, "e": 1065, "s": 1054, "text": "Dependency" }, { "code": null, "e": 1215, "s": 1065, "text": "The images that are to be revealed using the circular reveal animation can be added to an image directory inside the assets directory as shown below:" }, { "code": null, "e": 1229, "s": 1215, "text": "Adding Images" }, { "code": null, "e": 1384, "s": 1229, "text": "In the pubspec.yanl file, the assets can be activated to be used in the application by adding a path to the image as shown below under the assets section:" }, { "code": null, "e": 1402, "s": 1384, "text": "Activating Assets" }, { "code": null, "e": 1500, "s": 1402, "text": "Use the below line of code in the main.dart file to use the circular_reveal_animation dependency:" }, { "code": null, "e": 1576, "s": 1500, "text": "import 'package:circular_reveal_animation/circular_reveal_animation.dart';\n" }, { "code": null, "e": 1654, "s": 1576, "text": "Extend a StatelessWidget to create a root for the application as shown below:" }, { "code": null, "e": 1659, "s": 1654, "text": "Dart" }, { "code": "class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksForGeeks', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), ); }}", "e": 1899, "s": 1659, "text": null }, { "code": null, "e": 2010, "s": 1899, "text": "Extend a StatefulWidget to an appbar and a body to create a plane Homepage for the application as shown below:" }, { "code": null, "e": 2015, "s": 2010, "text": "Dart" }, { "code": "class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin { AnimationController animationController; Animation<double> animation; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(\"GeeksForGeeks\"), backgroundColor: Colors.green, ), body: ),", "e": 2482, "s": 2015, "text": null }, { "code": null, "e": 2611, "s": 2482, "text": "In the body of the Homepage make a call to the CircularRevealAnimation() function and add the images to the same as shown below:" }, { "code": null, "e": 2616, "s": 2611, "text": "Dart" }, { "code": "body: Padding( padding: const EdgeInsets.all(16.0), child: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ SizedBox(height: 16), CircularRevealAnimation( child: Image.asset('assets/wonderwomen.jpg'), animation: animation, centerAlignment: Alignment.centerRight, centerOffset: Offset(130, 100), minRadius: 12, maxRadius: 200, ), ], ), ), ),", "e": 3171, "s": 2616, "text": null }, { "code": null, "e": 3314, "s": 3171, "text": "Add a FloatingActionButton and assign the action to it that calls the CircularRevealAnimation() from the dependency on pressed as shown below:" }, { "code": null, "e": 3319, "s": 3314, "text": "Dart" }, { "code": "floatingActionButton: FloatingActionButton( backgroundColor: Colors.green, onPressed: () { if (animationController.status == AnimationStatus.forward || animationController.status == AnimationStatus.completed) { animationController.reverse(); } else { animationController.forward(); } }), );", "e": 3686, "s": 3319, "text": null }, { "code": null, "e": 3708, "s": 3686, "text": "Complete Source Code:" }, { "code": null, "e": 3713, "s": 3708, "text": "Dart" }, { "code": "import 'package:circular_reveal_animation/circular_reveal_animation.dart';import 'package:flutter/material.dart'; void main() => runApp(MyApp()); // rootclass MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksForGeeks', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), ); }} // Homepageclass MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin { AnimationController animationController; Animation<double> animation; // initialize state @override void initState() { super.initState(); animationController = AnimationController( vsync: this, duration: Duration(milliseconds: 1000), ); animation = CurvedAnimation( parent: animationController, curve: Curves.easeIn, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(\"GeeksForGeeks\"), backgroundColor: Colors.green, ), body: Padding( padding: const EdgeInsets.all(16.0), child: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ SizedBox(height: 16), CircularRevealAnimation( child: Image.asset('assets/wonderwomen.jpg'), animation: animation, centerAlignment: Alignment.centerRight, centerOffset: Offset(130, 100), minRadius: 12, maxRadius: 200, ), ], ), ), ), // button with assigned action floatingActionButton: FloatingActionButton( backgroundColor: Colors.green, onPressed: () { if (animationController.status == AnimationStatus.forward || animationController.status == AnimationStatus.completed) { animationController.reverse(); } else { animationController.forward(); } }), ); } }", "e": 5864, "s": 3713, "text": null }, { "code": null, "e": 5872, "s": 5864, "text": "Output:" }, { "code": null, "e": 5880, "s": 5872, "text": "android" }, { "code": null, "e": 5888, "s": 5880, "text": "Flutter" }, { "code": null, "e": 5910, "s": 5888, "text": "Flutter UI-components" }, { "code": null, "e": 5915, "s": 5910, "text": "Dart" }, { "code": null, "e": 5923, "s": 5915, "text": "Flutter" }, { "code": null, "e": 6021, "s": 5923, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6047, "s": 6021, "text": "ListView Class in Flutter" }, { "code": null, "e": 6068, "s": 6047, "text": "Flutter - Search Bar" }, { "code": null, "e": 6086, "s": 6068, "text": "Flutter - Dialogs" }, { "code": null, "e": 6117, "s": 6086, "text": "Flutter - FutureBuilder Widget" }, { "code": null, "e": 6143, "s": 6117, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 6160, "s": 6143, "text": "Flutter Tutorial" }, { "code": null, "e": 6181, "s": 6160, "text": "Flutter - Search Bar" }, { "code": null, "e": 6199, "s": 6181, "text": "Flutter - Dialogs" }, { "code": null, "e": 6230, "s": 6199, "text": "Flutter - FutureBuilder Widget" } ]
What is 5G Wireless Technology and How it Works?
24 Sep, 2019 According to Robert J. Topol, Intel’s General Manager for 5G Business and Technology, 5G will be the post-smartphone era. But phones are the first place to launch because they’re such an anchor in our lives from a connectivity standpoint. And indeed the applications of 5G merely begin at smartphones and then branch out to include many new devices and services in multiple industries from retail to education to entertainment! So let’s start at the beginning with an Introduction to 5G Wireless Technology as we try to understand this incredible new technology in detail. 5G Wireless Technology is the 5th generation of mobile networks and an evolution from the current 4G LTE networks. It is specially designed to fulfill the demands of current technological trends, which includes a large growth in data and almost global connectivity along with the increasing interest in the Internet of Things. In its initial stages, 5G Technology will work in conjugation with the existing 4G Technology and then move on as a fully independent entity in subsequent releases. Now let’s try to answer some of the major questions associated with 5G Wireless Technology so that we can understand it better. 5G Wireless Technology is now the latest cellular technology that will greatly increase the speed of wireless networks among other things(And who doesn’t want that?!!). So the data speed for wireless broadband connections using 5G would be at a maximum of around 20 Gbps. Contrasting that with the peak speed of 4G which is 60 Mbps, that’s a lot! Moreover, 5G will also provide more bandwidth and advanced antenna technology which will result in much more data transmitted over wireless systems. And that’s just a small sampling of the capabilities of 5G technology! It will also provide various network management features such as Network Slicing using which mobile operators will be able to create multiple virtual networks using a single physical 5G network. So in this futuristic scenario, if you are inside a self-driving car, then a virtual network with an extremely fast, low-latency connections would be required because obviously the car needs to navigate in real-time. On the other hand, if you are using any smart appliance in your home, then a virtual network with lower power and a slower connection would be fine because it’s not a life or death situation!!! There are basically 2 main components in the 5G Wireless Technology systems i.e. the Radio Access Network and the Core Network. Let’s see these in detail. 1. Radio Access Network: The Radio Access Network mainly includes 5G Small Cells and Macro Cells that form the crux of 5G Wireless Technology as well as the systems that connect the mobile devices to the Core Network. The 5G Small Cells are located in big clusters because the millimeter wave spectrum (that 5G uses for insanely high speeds!) can only travel over short distances. These Small Cells complement the Macro Cells that are used to provide more wide-area coverage.Macro Cells use MIMO (Multiple Inputs, Multiple Outputs) antennas which have multiple connections to send and receive large amounts of data simultaneously. This means that more users can connect to the network simultaneously. 2. Core Network: The Core Network manages all the data and internet connections for the 5G Wireless Technology. And a big advantage of the 5G Core Network is that it can integrate with the internet much more efficiently and it also provides additional services like cloud-based services, distributed servers that improve response times, etc. Another advanced feature of the Core Network is network slicing (Which we talked about earlier!!!). 5G Wireless Technology will not only enhance current mobile broadband services, but it will also expand the world of mobile networks to include many new devices and services in multiple industries from retail to education to entertainment with much higher performances and lower costs. It could even be said that 5G Technology as much as the emergence of automobiles or electricity ever did!!! Some of the benefits of 5G in various domains are given here: 5G will make our smartphones much smarter with faster and more uniform data rates, lower latency and cost-per-bit and this, in turn, will lead to the common acceptance of new immersive technologies like Virtual Reality or Augmented Reality. 5G will have the convenience of ultra-reliable, low latency links that will empower industries to invest in more projects which require remote control of critical infrastructure in various fields like medicine, aviation, etc. 5G will lead to an Internet of Things revolution as it has the ability to scale up or down in features like data rates, power, and mobility which is perfect for an application like connecting multiple embedded sensors in almost all devices! Details about the performance of 5G Wireless Technology according to various parameters are given here: South Korea and the U.S. became the first countries to commercially launch the 5G Wireless Technology in April 2019. China is also moving towards launching 5G by providing commercial 5G licenses to its major carriers. Japan plans to launch 5G in time for the 2020 Tokyo summer Olympics.The Central government in India has also set a target of 2020 for the commercial launch of 5G Wireless Technology, which is mostly in time with the other countries. The government already launched a three-year program in March 2018 to promote research in 5G. Also, Ericsson has created a 5G test base at IIT Delhi for developing applications that are tailor-made for the Indian scenario. In a landmark study conducted on the 5G Economy by Qualcomm, it emerged that the full economic effect of 5G Wireless Technology would appear around 2035 in a broad range of industries which would produce up to $12.3 trillion worth of goods and services that were directly enabled by 5G. It also emerged that the 5G Wireless Technology could potentially generate up to $3.5 trillion in revenue in 2035 and also directly support up to 22 million jobs. Also surprising is the fact that over time, the total contribution of 5G to the Global GDP growth could be as much as the contribution of India (Which is the seventh-largest economy in the world!!!) GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You! Geek Streak - 24 Days POTD Challenge What is Hashing | A Complete Tutorial GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge? GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa How to Learn Data Science in 10 weeks? Types of Software Testing What is Data Structure: Types, Classifications and Applications Roadmap to Learn JavaScript For Beginners
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Sep, 2019" }, { "code": null, "e": 139, "s": 53, "text": "According to Robert J. Topol, Intel’s General Manager for 5G Business and Technology," }, { "code": null, "e": 292, "s": 139, "text": "5G will be the post-smartphone era. But phones are the first place to launch because they’re such an anchor in our lives from a connectivity standpoint." }, { "code": null, "e": 626, "s": 292, "text": "And indeed the applications of 5G merely begin at smartphones and then branch out to include many new devices and services in multiple industries from retail to education to entertainment! So let’s start at the beginning with an Introduction to 5G Wireless Technology as we try to understand this incredible new technology in detail." }, { "code": null, "e": 1118, "s": 626, "text": "5G Wireless Technology is the 5th generation of mobile networks and an evolution from the current 4G LTE networks. It is specially designed to fulfill the demands of current technological trends, which includes a large growth in data and almost global connectivity along with the increasing interest in the Internet of Things. In its initial stages, 5G Technology will work in conjugation with the existing 4G Technology and then move on as a fully independent entity in subsequent releases." }, { "code": null, "e": 1246, "s": 1118, "text": "Now let’s try to answer some of the major questions associated with 5G Wireless Technology so that we can understand it better." }, { "code": null, "e": 1742, "s": 1246, "text": "5G Wireless Technology is now the latest cellular technology that will greatly increase the speed of wireless networks among other things(And who doesn’t want that?!!). So the data speed for wireless broadband connections using 5G would be at a maximum of around 20 Gbps. Contrasting that with the peak speed of 4G which is 60 Mbps, that’s a lot! Moreover, 5G will also provide more bandwidth and advanced antenna technology which will result in much more data transmitted over wireless systems." }, { "code": null, "e": 2419, "s": 1742, "text": "And that’s just a small sampling of the capabilities of 5G technology! It will also provide various network management features such as Network Slicing using which mobile operators will be able to create multiple virtual networks using a single physical 5G network. So in this futuristic scenario, if you are inside a self-driving car, then a virtual network with an extremely fast, low-latency connections would be required because obviously the car needs to navigate in real-time. On the other hand, if you are using any smart appliance in your home, then a virtual network with lower power and a slower connection would be fine because it’s not a life or death situation!!!" }, { "code": null, "e": 2574, "s": 2419, "text": "There are basically 2 main components in the 5G Wireless Technology systems i.e. the Radio Access Network and the Core Network. Let’s see these in detail." }, { "code": null, "e": 3275, "s": 2574, "text": "1. Radio Access Network: The Radio Access Network mainly includes 5G Small Cells and Macro Cells that form the crux of 5G Wireless Technology as well as the systems that connect the mobile devices to the Core Network. The 5G Small Cells are located in big clusters because the millimeter wave spectrum (that 5G uses for insanely high speeds!) can only travel over short distances. These Small Cells complement the Macro Cells that are used to provide more wide-area coverage.Macro Cells use MIMO (Multiple Inputs, Multiple Outputs) antennas which have multiple connections to send and receive large amounts of data simultaneously. This means that more users can connect to the network simultaneously." }, { "code": null, "e": 3717, "s": 3275, "text": "2. Core Network: The Core Network manages all the data and internet connections for the 5G Wireless Technology. And a big advantage of the 5G Core Network is that it can integrate with the internet much more efficiently and it also provides additional services like cloud-based services, distributed servers that improve response times, etc. Another advanced feature of the Core Network is network slicing (Which we talked about earlier!!!)." }, { "code": null, "e": 4111, "s": 3717, "text": "5G Wireless Technology will not only enhance current mobile broadband services, but it will also expand the world of mobile networks to include many new devices and services in multiple industries from retail to education to entertainment with much higher performances and lower costs. It could even be said that 5G Technology as much as the emergence of automobiles or electricity ever did!!!" }, { "code": null, "e": 4173, "s": 4111, "text": "Some of the benefits of 5G in various domains are given here:" }, { "code": null, "e": 4414, "s": 4173, "text": "5G will make our smartphones much smarter with faster and more uniform data rates, lower latency and cost-per-bit and this, in turn, will lead to the common acceptance of new immersive technologies like Virtual Reality or Augmented Reality." }, { "code": null, "e": 4640, "s": 4414, "text": "5G will have the convenience of ultra-reliable, low latency links that will empower industries to invest in more projects which require remote control of critical infrastructure in various fields like medicine, aviation, etc." }, { "code": null, "e": 4881, "s": 4640, "text": "5G will lead to an Internet of Things revolution as it has the ability to scale up or down in features like data rates, power, and mobility which is perfect for an application like connecting multiple embedded sensors in almost all devices!" }, { "code": null, "e": 4985, "s": 4881, "text": "Details about the performance of 5G Wireless Technology according to various parameters are given here:" }, { "code": null, "e": 5659, "s": 4985, "text": "South Korea and the U.S. became the first countries to commercially launch the 5G Wireless Technology in April 2019. China is also moving towards launching 5G by providing commercial 5G licenses to its major carriers. Japan plans to launch 5G in time for the 2020 Tokyo summer Olympics.The Central government in India has also set a target of 2020 for the commercial launch of 5G Wireless Technology, which is mostly in time with the other countries. The government already launched a three-year program in March 2018 to promote research in 5G. Also, Ericsson has created a 5G test base at IIT Delhi for developing applications that are tailor-made for the Indian scenario." }, { "code": null, "e": 6308, "s": 5659, "text": "In a landmark study conducted on the 5G Economy by Qualcomm, it emerged that the full economic effect of 5G Wireless Technology would appear around 2035 in a broad range of industries which would produce up to $12.3 trillion worth of goods and services that were directly enabled by 5G. It also emerged that the 5G Wireless Technology could potentially generate up to $3.5 trillion in revenue in 2035 and also directly support up to 22 million jobs. Also surprising is the fact that over time, the total contribution of 5G to the Global GDP growth could be as much as the contribution of India (Which is the seventh-largest economy in the world!!!)" }, { "code": null, "e": 6314, "s": 6308, "text": "GBlog" }, { "code": null, "e": 6412, "s": 6314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6437, "s": 6412, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 6492, "s": 6437, "text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!" }, { "code": null, "e": 6529, "s": 6492, "text": "Geek Streak - 24 Days POTD Challenge" }, { "code": null, "e": 6567, "s": 6529, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 6633, "s": 6567, "text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?" }, { "code": null, "e": 6704, "s": 6633, "text": "GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa" }, { "code": null, "e": 6743, "s": 6704, "text": "How to Learn Data Science in 10 weeks?" }, { "code": null, "e": 6769, "s": 6743, "text": "Types of Software Testing" }, { "code": null, "e": 6833, "s": 6769, "text": "What is Data Structure: Types, Classifications and Applications" } ]
How to add icon logo in title bar using HTML ?
15 Jan, 2019 Most of the websites adds icon or image logo in the title bar. The icon logo is also called as favicon. Adding favicons is also considered to be good for the SEO of the websites. The favicon is the combination of favorite icon. The link attribute is used to add the favicon. Syntax: <link rel="icon" href="icon_path" type="image/icon type"> Example: <!-- HTML code to add icon in the title bar --><!DOCTYPE html><html> <head> <meta charset = "utf-8" /> <title> GeeksforGeeks icon </title> <!-- add icon link --> <link rel = "icon" href = "https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200X200.png" type = "image/x-icon"> </head> <body> <h1 style = "color:green;"> GeeksforGeeks </h1> <p> GeeksforGeeks icon added in the title bar </p> </body></html> Output: HTML-Misc Technical Scripter 2018 Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n15 Jan, 2019" }, { "code": null, "e": 281, "s": 53, "text": "Most of the websites adds icon or image logo in the title bar. The icon logo is also called as favicon. Adding favicons is also considered to be good for the SEO of the websites. The favicon is the combination of favorite icon." }, { "code": null, "e": 328, "s": 281, "text": "The link attribute is used to add the favicon." }, { "code": null, "e": 336, "s": 328, "text": "Syntax:" }, { "code": null, "e": 394, "s": 336, "text": "<link rel=\"icon\" href=\"icon_path\" type=\"image/icon type\">" }, { "code": null, "e": 403, "s": 394, "text": "Example:" }, { "code": "<!-- HTML code to add icon in the title bar --><!DOCTYPE html><html> <head> <meta charset = \"utf-8\" /> <title> GeeksforGeeks icon </title> <!-- add icon link --> <link rel = \"icon\" href = \"https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200X200.png\" type = \"image/x-icon\"> </head> <body> <h1 style = \"color:green;\"> GeeksforGeeks </h1> <p> GeeksforGeeks icon added in the title bar </p> </body></html> ", "e": 998, "s": 403, "text": null }, { "code": null, "e": 1006, "s": 998, "text": "Output:" }, { "code": null, "e": 1016, "s": 1006, "text": "HTML-Misc" }, { "code": null, "e": 1040, "s": 1016, "text": "Technical Scripter 2018" }, { "code": null, "e": 1057, "s": 1040, "text": "Web Technologies" } ]
Popup Menu in Tkinter
26 Mar, 2020 Tkinter is Python’s standard GUI (Graphical User Interface) package. It is one of the most commonly used packages for GUI applications which comes with the Python itself. Note: For more information, refer to Python GUI – tkinter Menus are an important part of any GUI. A common use of menus is to provide convenient access to various operations such as saving or opening a file, quitting a program, or manipulating data. Toplevel menus are displayed just under the title bar of the root or any other top-level windows. Syntax: menu = Menu(master, **options) Note: For more information, refer to Python | Menu widget in Tkinter Popup menus are context menus that appear on user interaction. This menu can be shown anywhere on the client window. below is the python code to create a popup menu using Tkinter library. #creating popup menu in tkinterimport tkinter class A: #creates parent window def __init__(self): self.root = tkinter.Tk() self.root.geometry('500x500') self.frame1 = tkinter.Label(self.root, width = 400, height = 400, bg = '#AAAAAA') self.frame1.pack() #create menu def popup(self): self.popup_menu = tkinter.Menu(self.root, tearoff = 0) self.popup_menu.add_command(label = "say hi", command = lambda:self.hey("hi")) self.popup_menu.add_command(label = "say hello", command = lambda:self.hey("hello")) self.popup_menu.add_separator() self.popup_menu.add_command(label = "say bye", command = lambda:self.hey("bye")) #display menu on right click def do_popup(self,event): try: self.popup_menu.tk_popup(event.x_root, event.y_root) finally: self.popup_menu.grab_release() def hey(self,s): self.frame1.configure(text = s) def run(self): self.popup() self.root.bind("<Button-3>",self.do_popup) tkinter.mainloop() a = A()a.run() Output: The popup menu in above code appears on right-click. Functions Menu(root): creates the menu. add_command(label, command): adds the commands on the menu, the command argument calls the function hey() when that option is clicked. add_separator(): adds a separator. tk_popup(x, y): posts the menu at the position given as arguments grab_release(): releases the event grab bind(key, event): binds the mouse event. Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2020" }, { "code": null, "e": 199, "s": 28, "text": "Tkinter is Python’s standard GUI (Graphical User Interface) package. It is one of the most commonly used packages for GUI applications which comes with the Python itself." }, { "code": null, "e": 257, "s": 199, "text": "Note: For more information, refer to Python GUI – tkinter" }, { "code": null, "e": 547, "s": 257, "text": "Menus are an important part of any GUI. A common use of menus is to provide convenient access to various operations such as saving or opening a file, quitting a program, or manipulating data. Toplevel menus are displayed just under the title bar of the root or any other top-level windows." }, { "code": null, "e": 555, "s": 547, "text": "Syntax:" }, { "code": null, "e": 586, "s": 555, "text": "menu = Menu(master, **options)" }, { "code": null, "e": 655, "s": 586, "text": "Note: For more information, refer to Python | Menu widget in Tkinter" }, { "code": null, "e": 843, "s": 655, "text": "Popup menus are context menus that appear on user interaction. This menu can be shown anywhere on the client window. below is the python code to create a popup menu using Tkinter library." }, { "code": "#creating popup menu in tkinterimport tkinter class A: #creates parent window def __init__(self): self.root = tkinter.Tk() self.root.geometry('500x500') self.frame1 = tkinter.Label(self.root, width = 400, height = 400, bg = '#AAAAAA') self.frame1.pack() #create menu def popup(self): self.popup_menu = tkinter.Menu(self.root, tearoff = 0) self.popup_menu.add_command(label = \"say hi\", command = lambda:self.hey(\"hi\")) self.popup_menu.add_command(label = \"say hello\", command = lambda:self.hey(\"hello\")) self.popup_menu.add_separator() self.popup_menu.add_command(label = \"say bye\", command = lambda:self.hey(\"bye\")) #display menu on right click def do_popup(self,event): try: self.popup_menu.tk_popup(event.x_root, event.y_root) finally: self.popup_menu.grab_release() def hey(self,s): self.frame1.configure(text = s) def run(self): self.popup() self.root.bind(\"<Button-3>\",self.do_popup) tkinter.mainloop() a = A()a.run()", "e": 2261, "s": 843, "text": null }, { "code": null, "e": 2269, "s": 2261, "text": "Output:" }, { "code": null, "e": 2322, "s": 2269, "text": "The popup menu in above code appears on right-click." }, { "code": null, "e": 2332, "s": 2322, "text": "Functions" }, { "code": null, "e": 2362, "s": 2332, "text": "Menu(root): creates the menu." }, { "code": null, "e": 2497, "s": 2362, "text": "add_command(label, command): adds the commands on the menu, the command argument calls the function hey() when that option is clicked." }, { "code": null, "e": 2532, "s": 2497, "text": "add_separator(): adds a separator." }, { "code": null, "e": 2598, "s": 2532, "text": "tk_popup(x, y): posts the menu at the position given as arguments" }, { "code": null, "e": 2638, "s": 2598, "text": "grab_release(): releases the event grab" }, { "code": null, "e": 2679, "s": 2638, "text": "bind(key, event): binds the mouse event." }, { "code": null, "e": 2694, "s": 2679, "text": "Python-tkinter" }, { "code": null, "e": 2701, "s": 2694, "text": "Python" }, { "code": null, "e": 2799, "s": 2701, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2831, "s": 2799, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2858, "s": 2831, "text": "Python Classes and Objects" }, { "code": null, "e": 2879, "s": 2858, "text": "Python OOPs Concepts" }, { "code": null, "e": 2902, "s": 2879, "text": "Introduction To PYTHON" }, { "code": null, "e": 2958, "s": 2902, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2989, "s": 2958, "text": "Python | os.path.join() method" }, { "code": null, "e": 3031, "s": 2989, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3073, "s": 3031, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3112, "s": 3073, "text": "Python | datetime.timedelta() function" } ]
How to make workaround for window.location.href?
30 Aug, 2019 Given a URL, the task is to use the current address of the page and to perform an operation using this address. Example 1: This example points to the same URL and only redirects to the same address.URL = ‘https://gitstr.herokuapp.com’ <!DOCTYPE html><html lang="en"> <head> <title>Example 1:</title></head> <body bgcolor="white" ;> <div class="loginbox"> <img class="avatar"> <h1>GitStar</h1> <br> <form id="todoInputForm"> <div class="avatar"></div> <p>Username</p> <input type="text" placeholder="Enter your Github Username" class="input-username" id="login" /> <input type="submit" id="searchbtn name=" value="Search" /> <a href="https://help.github.com/en/articles/changing-your-github-username "> Forgot your Username </a> <br> <a href="https://github.com/join ">Don't have an account?</a> <br> </form> </div> <script> $(document).ready(function () { $('#todoInputForm').submit(function (e) { e.preventDefault() var input = $('#login').val() window.location.href = '/' }) }) </script></body></html> Output: Before clicking on the Search button: Search After clicking on the Search button:as you can see after clicking the search button the URL doesn’t change because of line 38: window.location.href = ‘/’. Example 2: In this example we would like to use window.location.href propertyto point to some other address, so let’s see how it works. <!DOCTYPE html><html lang="en"> <head> <title>Example 2:</title></head> <body bgcolor="white" ;> <div class="loginbox"> <img class="avatar"> <h1>GitStar</h1> <br> <form id="todoInputForm"> <div class="avatar"></div> <p>Username</p> <input type="text" placeholder="Enter your Github Username" class="input-username" id="login" /> <input type="submit" id="searchbtn name" value="Search" /> <a href="https://help.github.com/en/articles/changing-your-github-username"> Forgot your Username </a> <br> <a href="https://github.com/join ">Don't have an account?</a> <br> </form> </div> <script> $(document).ready(function () { $('#todoInputForm').submit(function (e) { e.preventDefault() var input = $('#login').val() window.location.href = '/' + input; }) }) </script> Output: Before clicking on the button: Search After clicking on the button: Searchas you can see after clicking the search button the URL does changes becauseof line 37: window.location.href = ‘/’ + input, now it refer to the default window location + input. so this was a brief example showing how I use window.location.href property in my projects, if you want to get a better understanding of the topic and how it actually works when complete backend and frontend is involved then do refer to this Github repo. Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Aug, 2019" }, { "code": null, "e": 140, "s": 28, "text": "Given a URL, the task is to use the current address of the page and to perform an operation using this address." }, { "code": null, "e": 263, "s": 140, "text": "Example 1: This example points to the same URL and only redirects to the same address.URL = ‘https://gitstr.herokuapp.com’" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Example 1:</title></head> <body bgcolor=\"white\" ;> <div class=\"loginbox\"> <img class=\"avatar\"> <h1>GitStar</h1> <br> <form id=\"todoInputForm\"> <div class=\"avatar\"></div> <p>Username</p> <input type=\"text\" placeholder=\"Enter your Github Username\" class=\"input-username\" id=\"login\" /> <input type=\"submit\" id=\"searchbtn name=\" value=\"Search\" /> <a href=\"https://help.github.com/en/articles/changing-your-github-username \"> Forgot your Username </a> <br> <a href=\"https://github.com/join \">Don't have an account?</a> <br> </form> </div> <script> $(document).ready(function () { $('#todoInputForm').submit(function (e) { e.preventDefault() var input = $('#login').val() window.location.href = '/' }) }) </script></body></html>", "e": 1279, "s": 263, "text": null }, { "code": null, "e": 1287, "s": 1279, "text": "Output:" }, { "code": null, "e": 1332, "s": 1287, "text": "Before clicking on the Search button: Search" }, { "code": null, "e": 1487, "s": 1332, "text": "After clicking on the Search button:as you can see after clicking the search button the URL doesn’t change because of line 38: window.location.href = ‘/’." }, { "code": null, "e": 1623, "s": 1487, "text": "Example 2: In this example we would like to use window.location.href propertyto point to some other address, so let’s see how it works." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Example 2:</title></head> <body bgcolor=\"white\" ;> <div class=\"loginbox\"> <img class=\"avatar\"> <h1>GitStar</h1> <br> <form id=\"todoInputForm\"> <div class=\"avatar\"></div> <p>Username</p> <input type=\"text\" placeholder=\"Enter your Github Username\" class=\"input-username\" id=\"login\" /> <input type=\"submit\" id=\"searchbtn name\" value=\"Search\" /> <a href=\"https://help.github.com/en/articles/changing-your-github-username\"> Forgot your Username </a> <br> <a href=\"https://github.com/join \">Don't have an account?</a> <br> </form> </div> <script> $(document).ready(function () { $('#todoInputForm').submit(function (e) { e.preventDefault() var input = $('#login').val() window.location.href = '/' + input; }) }) </script>", "e": 2635, "s": 1623, "text": null }, { "code": null, "e": 2643, "s": 2635, "text": "Output:" }, { "code": null, "e": 2681, "s": 2643, "text": "Before clicking on the button: Search" }, { "code": null, "e": 2894, "s": 2681, "text": "After clicking on the button: Searchas you can see after clicking the search button the URL does changes becauseof line 37: window.location.href = ‘/’ + input, now it refer to the default window location + input." }, { "code": null, "e": 3149, "s": 2894, "text": "so this was a brief example showing how I use window.location.href property in my projects, if you want to get a better understanding of the topic and how it actually works when complete backend and frontend is involved then do refer to this Github repo." }, { "code": null, "e": 3156, "s": 3149, "text": "Picked" }, { "code": null, "e": 3167, "s": 3156, "text": "JavaScript" }, { "code": null, "e": 3184, "s": 3167, "text": "Web Technologies" }, { "code": null, "e": 3211, "s": 3184, "text": "Web technologies Questions" } ]
Write a C program to read a data from file and display
How to read a series of items that are present in a file and display the data in columns or tabular form using C Programming Create a file in write mode and write some series of information in the file and close it again open and display the series of data in columns on the console. Write mode of opening the file FILE *fp; fp =fopen ("sample.txt", "w"); If the file does not exist, then a new file will be created. If the file does not exist, then a new file will be created. If the file exists, then old content gets erased & current content will be stored. If the file exists, then old content gets erased & current content will be stored. Read mode of opening the file FILE *fp fp =fopen ("sample.txt", "r"); If the file does not exist, then fopen function returns NULL value. If the file does not exist, then fopen function returns NULL value. If the file exists, then data is read from the file successfully. If the file exists, then data is read from the file successfully. The logic used to display data on the console in tabular form is − while ((ch=getc(fp))!=EOF){ if(ch == ',') printf("\t\t"); else printf("%c",ch); } Live Demo #include <stdio.h> #include<ctype.h> #include<stdlib.h> int main(){ char ch; FILE *fp; fp=fopen("std1.txt","w"); printf("enter the text.press cntrl Z:\n"); while((ch = getchar())!=EOF){ putc(ch,fp); } fclose(fp); fp=fopen("std1.txt","r"); printf("text on the file:\n"); while ((ch=getc(fp))!=EOF){ if(ch == ',') printf("\t\t"); else printf("%c",ch); } fclose(fp); return 0; } enter the text.press cntrl Z: Name,Item,Price Bhanu,1,23.4 Priya,2,45.6 ^Z text on the file: Name Item Price Bhanu 1 23.4 Priya 2 45.6
[ { "code": null, "e": 1312, "s": 1187, "text": "How to read a series of items that are present in a file and display the data in columns or tabular form using C Programming" }, { "code": null, "e": 1471, "s": 1312, "text": "Create a file in write mode and write some series of information in the file and close it again open and display the series of data in columns on the console." }, { "code": null, "e": 1502, "s": 1471, "text": "Write mode of opening the file" }, { "code": null, "e": 1543, "s": 1502, "text": "FILE *fp;\nfp =fopen (\"sample.txt\", \"w\");" }, { "code": null, "e": 1604, "s": 1543, "text": "If the file does not exist, then a new file will be created." }, { "code": null, "e": 1665, "s": 1604, "text": "If the file does not exist, then a new file will be created." }, { "code": null, "e": 1748, "s": 1665, "text": "If the file exists, then old content gets erased & current content will be stored." }, { "code": null, "e": 1831, "s": 1748, "text": "If the file exists, then old content gets erased & current content will be stored." }, { "code": null, "e": 1861, "s": 1831, "text": "Read mode of opening the file" }, { "code": null, "e": 1904, "s": 1861, "text": " FILE *fp\nfp =fopen (\"sample.txt\", \"r\");" }, { "code": null, "e": 1972, "s": 1904, "text": "If the file does not exist, then fopen function returns NULL value." }, { "code": null, "e": 2040, "s": 1972, "text": "If the file does not exist, then fopen function returns NULL value." }, { "code": null, "e": 2106, "s": 2040, "text": "If the file exists, then data is read from the file successfully." }, { "code": null, "e": 2172, "s": 2106, "text": "If the file exists, then data is read from the file successfully." }, { "code": null, "e": 2239, "s": 2172, "text": "The logic used to display data on the console in tabular form is −" }, { "code": null, "e": 2339, "s": 2239, "text": "while ((ch=getc(fp))!=EOF){\n if(ch == ',')\n printf(\"\\t\\t\");\n else\n printf(\"%c\",ch);\n}" }, { "code": null, "e": 2350, "s": 2339, "text": " Live Demo" }, { "code": null, "e": 2801, "s": 2350, "text": "#include <stdio.h>\n#include<ctype.h>\n#include<stdlib.h>\nint main(){\n char ch;\n FILE *fp;\n fp=fopen(\"std1.txt\",\"w\");\n printf(\"enter the text.press cntrl Z:\\n\");\n while((ch = getchar())!=EOF){\n putc(ch,fp);\n }\n fclose(fp);\n fp=fopen(\"std1.txt\",\"r\");\n printf(\"text on the file:\\n\");\n while ((ch=getc(fp))!=EOF){\n if(ch == ',')\n printf(\"\\t\\t\");\n else\n printf(\"%c\",ch);\n }\n fclose(fp);\n return 0;\n}" }, { "code": null, "e": 2958, "s": 2801, "text": "enter the text.press cntrl Z:\nName,Item,Price\nBhanu,1,23.4\nPriya,2,45.6\n^Z\ntext on the file:\nName Item Price\nBhanu 1 23.4\nPriya 2 45.6" } ]
Program to Convert Octal Number to Binary Number
21 Jan, 2022 Given an Octal number as input, the task is to convert that number to Binary number.Examples: Input : Octal = 345 Output : Binary = 011100101 Explanation : Equivalent binary value of 3: 011 Equivalent binary value of 4: 100 Equivalent binary value of 5: 101 Input : Octal = 120 Output : Binary = 001010000 Octal Number: An Octal number is a positional numeral system with a radix, or base, of 8 and uses eight distinct symbols.Binary Number: A Binary number is a number expressed in the base-2 binary numeral system, which uses only two symbols: which are 0 (zero) and 1 (one). To convert an Octal number to Binary, the binary equivalent of each digit of the octal number is evaluated and combined at the end to get the equivalent binary number. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to convert// Octal number to Binary #include <iostream>using namespace std; // Function to convert an// Octal to Binary Numberstring OctToBin(string octnum){ long int i = 0; string binary = ""; while (octnum[i]) { switch (octnum[i]) { case '0': binary += "000"; break; case '1': binary += "001"; break; case '2': binary += "010"; break; case '3': binary += "011"; break; case '4': binary += "100"; break; case '5': binary += "101"; break; case '6': binary += "110"; break; case '7': binary += "111"; break; default: cout << "\nInvalid Octal Digit " << octnum[i]; break; } i++; } return binary;} // Driver codeint main(){ // Get the Hexadecimal number string octnum = "345"; // Convert Octal to Binary cout << "Equivalent Binary Value = " << OctToBin(octnum); return 0;} // Java program to convert// Octal number to Binaryimport java.util.*;class Solution{ // Function to convert an// Octal to Binary Numberstatic String OctToBin(String octnum){ long i = 0; String binary = ""; while (i<octnum.length()) { char c=octnum.charAt((int)i); switch (c) { case '0': binary += "000"; break; case '1': binary += "001"; break; case '2': binary += "010"; break; case '3': binary += "011"; break; case '4': binary += "100"; break; case '5': binary += "101"; break; case '6': binary += "110"; break; case '7': binary += "111"; break; default: System.out.println( "\nInvalid Octal Digit "+ octnum.charAt((int)i)); break; } i++; } return binary;} // Driver codepublic static void main(String args[]){ // Get the Hexadecimal number String octnum = "345"; // Convert Octal to Binary System.out.println( "Equivalent Binary Value = "+ OctToBin(octnum)); } }//contributed by Arnab Kundu # Python3 program to convert# Octal number to Binary # defining a function that returns# binary equivalent of the numberdef OctToBin(octnum): binary = "" # initialising bin as String # While loop to extract each digit while octnum != 0: # extracting each digit d = int(octnum % 10) if d == 0: # concatenation of string using join function binary = "".join(["000", binary]) elif d == 1: # concatenation of string using join function binary = "".join(["001", binary]) elif d == 2: # concatenation of string using join function binary = "".join(["010", binary]) elif d == 3: # concatenation of string using join function binary = "".join(["011", binary]) elif d == 4: # concatenation of string using join function binary = "".join(["100", binary]) elif d == 5: # concatenation of string using join function binary = "".join(["101", binary]) elif d == 6: # concatenation of string using join function binary = "".join(["110",binary]) elif d == 7: # concatenation of string using join function binary = "".join(["111", binary]) else: # an option for invalid input binary = "Invalid Octal Digit" break # updating the oct for while loop octnum = int(octnum / 10) # returning the string binary that stores # binary equivalent of the number return binary # Driver Codeoctnum = 345 # value of function stored final_binfinal_bin = "" + OctToBin(octnum) # result is printedprint("Equivalent Binary Value =", final_bin) # This code is contributed by Animesh_Gupta // C# program to convert Octal number to Binary class GFG{ // Function to convert an// Octal to Binary Numberstatic string OctToBin(string octnum){ int i = 0; string binary = ""; while (i < octnum.Length) { char c = octnum[i]; switch (c) { case '0': binary += "000"; break; case '1': binary += "001"; break; case '2': binary += "010"; break; case '3': binary += "011"; break; case '4': binary += "100"; break; case '5': binary += "101"; break; case '6': binary += "110"; break; case '7': binary += "111"; break; default: System.Console.WriteLine( "\nInvalid Octal Digit "+ octnum[i]); break; } i++; } return binary;} // Driver codestatic void Main(){ // Get the Hexadecimal number string octnum = "345"; // Convert Octal to Binary System.Console.WriteLine("Equivalent Binary Value = " + OctToBin(octnum));}} // This code is contributed by mits <?php// PHP program to convert// Octal number to Binary // Function to convert an// Octal to Binary Numberfunction OctToBin($octnum){ $i = 0; $binary = (string)""; while ($i != strlen($octnum)) { switch ($octnum[$i]) { case '0': $binary.= "000"; break; case '1': $binary .= "001"; break; case '2': $binary .= "010"; break; case '3': $binary .= "011"; break; case '4': $binary .= "100"; break; case '5': $binary .= "101"; break; case '6': $binary .= "110"; break; case '7': $binary .= "111"; break; default: echo("\nInvalid Octal Digit ". $octnum[$i]); break; } $i++; } return $binary;} // Driver code // Get the Hexadecimal number$octnum = "345"; /// Convert Octal to Binaryecho("Equivalent Binary Value = " . OctToBin($octnum)); // This code is contributed// by PrinciRaj1992 <script> // JavaScript program to convert// Octal number to Binary // Function to convert an// Octal to Binary Numberfunction OctToBin(octnum){ let i = 0; let binary = ""; while (i<octnum.length) { let c=octnum[i]; switch (c) { case '0': binary += "000"; break; case '1': binary += "001"; break; case '2': binary += "010"; break; case '3': binary += "011"; break; case '4': binary += "100"; break; case '5': binary += "101"; break; case '6': binary += "110"; break; case '7': binary += "111"; break; default: document.write( "<br>Invalid Octal Digit "+ octnum[i]); break; } i++; } return binary;} // Driver code// Get the Hexadecimal numberlet octnum = "345"; // Convert Octal to Binarydocument.write( "Equivalent Binary Value = "+ OctToBin(octnum)); // This code is contributed by avanitrachhadiya2155 </script> Equivalent Binary Value = 011100101 andrew1234 Mithun Kumar princiraj1992 Animesh_Gupta anikaseth98 avanitrachhadiya2155 simmytarika5 base-conversion Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Minimum number of jumps to reach end Find minimum number of coins that make a given value The Knight's tour problem | Backtracking-1 Algorithm to solve Rubik's Cube Modulo 10^9+7 (1000000007) Modulo Operator (%) in C/C++ with Examples Program for factorial of a number
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jan, 2022" }, { "code": null, "e": 124, "s": 28, "text": "Given an Octal number as input, the task is to convert that number to Binary number.Examples: " }, { "code": null, "e": 338, "s": 124, "text": "Input : Octal = 345\nOutput : Binary = 011100101\nExplanation : \nEquivalent binary value of 3: 011\nEquivalent binary value of 4: 100\nEquivalent binary value of 5: 101\n\nInput : Octal = 120\nOutput : Binary = 001010000" }, { "code": null, "e": 613, "s": 340, "text": "Octal Number: An Octal number is a positional numeral system with a radix, or base, of 8 and uses eight distinct symbols.Binary Number: A Binary number is a number expressed in the base-2 binary numeral system, which uses only two symbols: which are 0 (zero) and 1 (one). " }, { "code": null, "e": 783, "s": 613, "text": "To convert an Octal number to Binary, the binary equivalent of each digit of the octal number is evaluated and combined at the end to get the equivalent binary number. " }, { "code": null, "e": 838, "s": 785, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 842, "s": 838, "text": "C++" }, { "code": null, "e": 847, "s": 842, "text": "Java" }, { "code": null, "e": 855, "s": 847, "text": "Python3" }, { "code": null, "e": 858, "s": 855, "text": "C#" }, { "code": null, "e": 862, "s": 858, "text": "PHP" }, { "code": null, "e": 873, "s": 862, "text": "Javascript" }, { "code": "// C++ program to convert// Octal number to Binary #include <iostream>using namespace std; // Function to convert an// Octal to Binary Numberstring OctToBin(string octnum){ long int i = 0; string binary = \"\"; while (octnum[i]) { switch (octnum[i]) { case '0': binary += \"000\"; break; case '1': binary += \"001\"; break; case '2': binary += \"010\"; break; case '3': binary += \"011\"; break; case '4': binary += \"100\"; break; case '5': binary += \"101\"; break; case '6': binary += \"110\"; break; case '7': binary += \"111\"; break; default: cout << \"\\nInvalid Octal Digit \" << octnum[i]; break; } i++; } return binary;} // Driver codeint main(){ // Get the Hexadecimal number string octnum = \"345\"; // Convert Octal to Binary cout << \"Equivalent Binary Value = \" << OctToBin(octnum); return 0;}", "e": 1999, "s": 873, "text": null }, { "code": "// Java program to convert// Octal number to Binaryimport java.util.*;class Solution{ // Function to convert an// Octal to Binary Numberstatic String OctToBin(String octnum){ long i = 0; String binary = \"\"; while (i<octnum.length()) { char c=octnum.charAt((int)i); switch (c) { case '0': binary += \"000\"; break; case '1': binary += \"001\"; break; case '2': binary += \"010\"; break; case '3': binary += \"011\"; break; case '4': binary += \"100\"; break; case '5': binary += \"101\"; break; case '6': binary += \"110\"; break; case '7': binary += \"111\"; break; default: System.out.println( \"\\nInvalid Octal Digit \"+ octnum.charAt((int)i)); break; } i++; } return binary;} // Driver codepublic static void main(String args[]){ // Get the Hexadecimal number String octnum = \"345\"; // Convert Octal to Binary System.out.println( \"Equivalent Binary Value = \"+ OctToBin(octnum)); } }//contributed by Arnab Kundu", "e": 3234, "s": 1999, "text": null }, { "code": "# Python3 program to convert# Octal number to Binary # defining a function that returns# binary equivalent of the numberdef OctToBin(octnum): binary = \"\" # initialising bin as String # While loop to extract each digit while octnum != 0: # extracting each digit d = int(octnum % 10) if d == 0: # concatenation of string using join function binary = \"\".join([\"000\", binary]) elif d == 1: # concatenation of string using join function binary = \"\".join([\"001\", binary]) elif d == 2: # concatenation of string using join function binary = \"\".join([\"010\", binary]) elif d == 3: # concatenation of string using join function binary = \"\".join([\"011\", binary]) elif d == 4: # concatenation of string using join function binary = \"\".join([\"100\", binary]) elif d == 5: # concatenation of string using join function binary = \"\".join([\"101\", binary]) elif d == 6: # concatenation of string using join function binary = \"\".join([\"110\",binary]) elif d == 7: # concatenation of string using join function binary = \"\".join([\"111\", binary]) else: # an option for invalid input binary = \"Invalid Octal Digit\" break # updating the oct for while loop octnum = int(octnum / 10) # returning the string binary that stores # binary equivalent of the number return binary # Driver Codeoctnum = 345 # value of function stored final_binfinal_bin = \"\" + OctToBin(octnum) # result is printedprint(\"Equivalent Binary Value =\", final_bin) # This code is contributed by Animesh_Gupta", "e": 5149, "s": 3234, "text": null }, { "code": "// C# program to convert Octal number to Binary class GFG{ // Function to convert an// Octal to Binary Numberstatic string OctToBin(string octnum){ int i = 0; string binary = \"\"; while (i < octnum.Length) { char c = octnum[i]; switch (c) { case '0': binary += \"000\"; break; case '1': binary += \"001\"; break; case '2': binary += \"010\"; break; case '3': binary += \"011\"; break; case '4': binary += \"100\"; break; case '5': binary += \"101\"; break; case '6': binary += \"110\"; break; case '7': binary += \"111\"; break; default: System.Console.WriteLine( \"\\nInvalid Octal Digit \"+ octnum[i]); break; } i++; } return binary;} // Driver codestatic void Main(){ // Get the Hexadecimal number string octnum = \"345\"; // Convert Octal to Binary System.Console.WriteLine(\"Equivalent Binary Value = \" + OctToBin(octnum));}} // This code is contributed by mits", "e": 6427, "s": 5149, "text": null }, { "code": "<?php// PHP program to convert// Octal number to Binary // Function to convert an// Octal to Binary Numberfunction OctToBin($octnum){ $i = 0; $binary = (string)\"\"; while ($i != strlen($octnum)) { switch ($octnum[$i]) { case '0': $binary.= \"000\"; break; case '1': $binary .= \"001\"; break; case '2': $binary .= \"010\"; break; case '3': $binary .= \"011\"; break; case '4': $binary .= \"100\"; break; case '5': $binary .= \"101\"; break; case '6': $binary .= \"110\"; break; case '7': $binary .= \"111\"; break; default: echo(\"\\nInvalid Octal Digit \". $octnum[$i]); break; } $i++; } return $binary;} // Driver code // Get the Hexadecimal number$octnum = \"345\"; /// Convert Octal to Binaryecho(\"Equivalent Binary Value = \" . OctToBin($octnum)); // This code is contributed// by PrinciRaj1992", "e": 7556, "s": 6427, "text": null }, { "code": "<script> // JavaScript program to convert// Octal number to Binary // Function to convert an// Octal to Binary Numberfunction OctToBin(octnum){ let i = 0; let binary = \"\"; while (i<octnum.length) { let c=octnum[i]; switch (c) { case '0': binary += \"000\"; break; case '1': binary += \"001\"; break; case '2': binary += \"010\"; break; case '3': binary += \"011\"; break; case '4': binary += \"100\"; break; case '5': binary += \"101\"; break; case '6': binary += \"110\"; break; case '7': binary += \"111\"; break; default: document.write( \"<br>Invalid Octal Digit \"+ octnum[i]); break; } i++; } return binary;} // Driver code// Get the Hexadecimal numberlet octnum = \"345\"; // Convert Octal to Binarydocument.write( \"Equivalent Binary Value = \"+ OctToBin(octnum)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 8695, "s": 7556, "text": null }, { "code": null, "e": 8731, "s": 8695, "text": "Equivalent Binary Value = 011100101" }, { "code": null, "e": 8744, "s": 8733, "text": "andrew1234" }, { "code": null, "e": 8757, "s": 8744, "text": "Mithun Kumar" }, { "code": null, "e": 8771, "s": 8757, "text": "princiraj1992" }, { "code": null, "e": 8785, "s": 8771, "text": "Animesh_Gupta" }, { "code": null, "e": 8797, "s": 8785, "text": "anikaseth98" }, { "code": null, "e": 8818, "s": 8797, "text": "avanitrachhadiya2155" }, { "code": null, "e": 8831, "s": 8818, "text": "simmytarika5" }, { "code": null, "e": 8847, "s": 8831, "text": "base-conversion" }, { "code": null, "e": 8860, "s": 8847, "text": "Mathematical" }, { "code": null, "e": 8873, "s": 8860, "text": "Mathematical" }, { "code": null, "e": 8971, "s": 8873, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8995, "s": 8971, "text": "Merge two sorted arrays" }, { "code": null, "e": 9016, "s": 8995, "text": "Operators in C / C++" }, { "code": null, "e": 9030, "s": 9016, "text": "Prime Numbers" }, { "code": null, "e": 9067, "s": 9030, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 9120, "s": 9067, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 9163, "s": 9120, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 9195, "s": 9163, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 9222, "s": 9195, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 9265, "s": 9222, "text": "Modulo Operator (%) in C/C++ with Examples" } ]
Wave Patterns - GeeksforGeeks
29 Oct, 2021 Given length and width, print the pattern in wave form using ‘/’ and ”.Examples : Input : wave_height = 4 wave_length = 4 Output : /\ /\ /\ /\ / \ / \ / \ / \ / \ / \ / \ / \ / \/ \/ \/ \ Input : wave_height = 2 wave_length = 3 Output : /\ /\ /\ / \/ \/ \ C++ Java Python3 C# PHP Javascript #include <iostream>using namespace std; // Function definitionvoid pattern(int wave_height, int wave_length){ int i, j, k, e, n, count, x; e = 2; x = 1; // for loop for height of wave for (i = 0; i < wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) cout << " "; // for loop for wave length for (count = 1; count <= wave_length; count++) { // checking for intermediate spaces for (n = (wave_height + wave_height - 2); n >= x; n--) cout << " "; for (k = 1; k <= e; k++) { if (k == 1) cout << "/"; else if (k == e) cout << "\\"; else cout << " "; } } // incrementing counters value by two x = x + 2; e = e + 2; cout << endl; }} // Driver codeint main(){ // change value to decrease or increase // the height of wave int wave_height = 4; // change value to decrease or increase // the length of wave int wave_length = 4; pattern(wave_height, wave_length); return 0;} import java.io.*; class GFG { // Function definition static void pattern(int wave_height, int wave_length) { int i, j, k, e, n, count, x; e = 2; x = 1; // for loop for height // of wave for (i = 0; i < wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) System.out.print(" "); // for loop for wave // length for (count = 1; count <= wave_length; count++) { // checking for intermediate // spaces for (n = (wave_height + wave_height - 2); n >= x; n--) System.out.print(" "); for (k = 1; k <= e; k++) { if (k == 1) System.out.print("/"); else if (k == e) System.out.print("\\"); else System.out.print(" "); } } // incrementing counters // value by two x = x + 2; e = e + 2; System.out.println(); } } // Driver code public static void main(String args[]) { // change value to decrease or // increase the height of wave int wave_height = 4; // change value to decrease or // increase the length of wave int wave_length = 4; pattern(wave_height, wave_length); }} // This code is contributed by Nikita Tiwari. # Function definitiondef pattern(wave_height, wave_length) : e = 2 x = 1 # for loop for height # of wave for i in range(0, wave_height) : for j in range(wave_height, wave_height + i+1) : print(" ", end ="") # for loop for wave # length for count in range(1, wave_length + 1) : # checking for intermediate spaces for n in range((wave_height + wave_height - 2), x-1, -1) : print(" ", end ="") for k in range(1, e + 1) : if (k == 1) : print("/", end ="") elif (k == e) : print("\\", end ="") else : print(" ", end ="") # incrementing counters # value by two x = x + 2 e = e + 2 print("") # Driver code # Change value to decrease or increase# the height of wavewave_height = 4 # change value to decrease or increase# the length of wavewave_length = 4 pattern(wave_height, wave_length); # This code is contributed by Nikita Tiwari. // C# code for Wave Patternsusing System; class GFG { // Function definition static void pattern(int wave_height, int wave_length) { int i, j, k, e, n, count, x; e = 2; x = 1; // for loop for height // of wave for (i = 0; i < wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) Console.Write(" "); // for loop for wave // length for (count = 1; count <= wave_length; count++) { // checking for intermediate // spaces for (n = (wave_height + wave_height - 2); n >= x; n--) Console.Write(" "); for (k = 1; k <= e; k++) { if (k == 1) Console.Write("/"); else if (k == e) Console.Write("\\"); else Console.Write(" "); } } // incrementing counters // value by two x = x + 2; e = e + 2; Console.WriteLine(); } } // Driver code public static void Main() { // change value to decrease or // increase the height of wave int wave_height = 4; // change value to decrease or // increase the length of wave int wave_length = 4; pattern(wave_height, wave_length); }} // This code is contributed by vt_m. <?php// PHP implementation to// print wave patterns // Function definitionfunction pattern($wave_height,$wave_length){ $e = 2; $x = 1; // for loop for height of wave for ($i = 0; $i < $wave_height; $i++) { for ($j = $wave_height; $j <= $wave_height + $i; $j++) echo " "; // for loop for wave length for ($count = 1; $count <= $wave_length; $count++) { // checking for intermediate // spaces for ($n = ($wave_height + $wave_height - 2); $n >= $x; $n--) echo " "; for ($k = 1; $k <= $e; $k++) { if ($k == 1) echo "/"; else if ($k == $e) echo "\\"; else echo " "; } } // incrementing counters value by two $x = $x + 2; $e = $e + 2; echo "\n"; }} // Driver code$wave_height = 4;$wave_length = 4;pattern($wave_height, $wave_length); // This code is contributed by Mithun Kumar?> <script> // Function definition function pattern( wave_height , wave_length) { let i, j, k, e, n, count, x; e = 2; x = 1; // for loop for height // of wave for (i = 0; i < wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) document.write(" "); // for loop for wave // length for (count = 1; count <= wave_length; count++) { // checking for intermediate // spaces for (n = (wave_height + wave_height - 2); n >= x; n--) document.write(" "); for (k = 1; k <= e; k++) { if (k == 1) document.write("/"); else if (k == e) document.write("\\"); else document.write(" "); } } // incrementing counters // value by two x = x + 2; e = e + 2; document.write("<br/>"); } } // Driver code // change value to decrease or // increase the height of wave let wave_height = 4; // change value to decrease or // increase the length of wave let wave_length = 4; pattern(wave_height, wave_length); // This code is contributed by todaysgaurav</script> Output : /\ /\ /\ /\ / \ / \ / \ / \ / \ / \ / \ / \ / \/ \/ \/ \ To print numbers in wave form.Examples : Input : wave_height = 4 wave_length = 4 Output : 04 05 04 05 04 05 04 05 03 06 03 06 03 06 03 06 02 07 02 07 02 07 02 07 01 08 01 08 01 08 01 08 Input : wave_height = 2 wave_length = 2 Output : 02 02 01 03 01 03 C++ Java Python3 C# PHP Javascript // C++ code to print numbers// in wave form#include <iostream>using namespace std; // Function definitionvoid pattern(int wave_height, int wave_length){ int i, j, k, e, n, count, x, n1, n2; e = 2; x = 1; n1 = wave_height; n2 = wave_height + 1; // for loop for height of wave for (i = 1; i <= wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) { cout << " "; } // for loop for wave length for (count = 1; count <= wave_length; count++) { // checking for intermediate spaces for (n = (wave_height + wave_height - 2); n >= x; n--) cout << " "; for (k = 1; k <= e; k++) { if (k == 1) cout << "0" << n1 << " "; else if (k == e) cout << "0" << n2 << " "; else cout << " "; } } // incrementing counters value by two x = x + 2; e = e + 2; n1 = wave_height - i; n2 = wave_height + 1 + i; cout << endl; }} // Driver codeint main(){ // change value to decrease or // increase the height of wave int wave_height = 4; // change value to decrease or // increase the length of wave int wave_length = 4; pattern(wave_height, wave_length); return 0;} // Java code to print numbers// in wave formimport java.io.*; class GFG { // Function definition static void pattern(int wave_height, int wave_length) { int i, j, k, e, n; int count, x, n1, n2; e = 2; x = 1; n1 = wave_height; n2 = wave_height + 1; // for loop for height // of wave for (i = 1; i <= wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) { System.out.print(" "); } // for loop for wave // length for (count = 1; count <= wave_length; count++) { // checking for intermediate // spaces for (n = (wave_height + wave_height - 2); n >= x; n--) System.out.print(" "); for (k = 1; k <= e; k++) { if (k == 1) System.out.print("0" + n1 + " "); else if (k == e) System.out.print("0" + n2 + " "); else System.out.print(" "); } } // incrementing counters // value by two x = x + 2; e = e + 2; n1 = wave_height - i; n2 = wave_height + 1 + i; System.out.println(); } } // Driver code public static void main(String args[]) { // change value to decrease or // increase the height of wave int wave_height = 4; // change value to decrease or // increase the length of wave int wave_length = 4; pattern(wave_height, wave_length); }} // This code is contributed by Nikita Tiwari. # Python 3 code to print numbers# in wave form # Function definitiondef pattern( wave_height, wave_length) : e = 2 x = 1 n1 = wave_height n2 = wave_height + 1 # for loop for height # of wave for i in range(1, wave_height + 1) : for j in range( wave_height, wave_height + i + 1) : print( " ", end ="") # for loop for wave # length for count in range(1, wave_length + 1) : # checking for intermediate # spaces for n in range((wave_height + wave_height - 2), x - 1, -1) : print( " ", end ="") for k in range(1, e + 1) : if (k == 1) : print("0", n1, " ", end ="") elif (k == e) : print("0", n2, " ", end ="") else : print(" ", end ="") # incrementing counters value # by two x = x + 2 e = e + 2 n1 = wave_height - i n2 = wave_height + 1 + i print() # Driver code # change value to decrease or# increase the height of wavewave_height = 4 # change value to decrease or# increase the length of wavewave_length = 4 pattern(wave_height, wave_length) # This code is contributed by Nikita Tiwari. // C# code to print numbers// in wave formusing System; class GFG{ // Function definition static void pattern(int wave_height, int wave_length) { int i, j, k, e, n; int count, x, n1, n2; e = 2; x = 1; n1 = wave_height; n2 = wave_height + 1; // for loop for // height of wave for (i = 1; i <= wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) { Console.Write(" "); } // for loop for // wave length for (count = 1; count <= wave_length; count++) { // checking for intermediate // spaces for (n = (wave_height + wave_height - 2); n >= x; n--) Console.Write(" "); for (k = 1; k <= e; k++) { if (k == 1) Console.Write("0" + n1 + " "); else if (k == e) Console.Write("0" + n2 + " "); else Console.Write(" "); } } // incrementing counters // value by two x = x + 2; e = e + 2; n1 = wave_height - i; n2 = wave_height + 1 + i; Console.WriteLine(); } } // Driver code static public void Main () { // change value to decrease or // increase the height of wave int wave_height = 4; // change value to decrease or // increase the length of wave int wave_length = 4; pattern(wave_height, wave_length); }} // This code is contributed by ajit. <?php// PHP implementation to print// numbers in wave form // Function definitionfunction pattern($wave_height, $wave_length){ $e = 2; $x = 1; $n1 = $wave_height; $n2 = $wave_height + 1; // for loop for height of wave for ($i = 1; $i <= $wave_height; $i++) { for ($j = $wave_height; $j <= $wave_height + $i; $j++) { echo " "; } // for loop for wave length for ($count = 1; $count <= $wave_length; $count++) { // checking for intermediate // spaces for ($n = ($wave_height + $wave_height - 2); $n >= $x; $n--) echo " "; for ($k = 1; $k <= $e; $k++) { if ($k == 1) echo "0".$n1." "; else if ($k == $e) echo "0".$n2." "; else echo " "; } } // incrementing counters value // by two $x = $x + 2; $e = $e + 2; $n1 = $wave_height - $i; $n2 = $wave_height + 1 + $i; echo "\n"; }} // Driver code$wave_height = 4;$wave_length = 4;pattern($wave_height, $wave_length); // This code is contributed by Mithun Kumar?> <script>// javascript code to print numbers// in wave form // Function definition function pattern(wave_height , wave_length) { var i, j, k, e, n; var count, x, n1, n2; e = 2; x = 1; n1 = wave_height; n2 = wave_height + 1; // for loop for height // of wave for (i = 1; i <= wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) { document.write(" "); } // for loop for wave // length for (count = 1; count <= wave_length; count++) { // checking for intermediate // spaces for (n = (wave_height + wave_height - 2); n >= x; n--) document.write(" "); for (k = 1; k <= e; k++) { if (k == 1) document.write("0" + n1 + " "); else if (k == e) document.write("0" + n2 + " "); else document.write(" "); } } // incrementing counters // value by two x = x + 2; e = e + 2; n1 = wave_height - i; n2 = wave_height + 1 + i; document.write("<br/>"); } } // Driver code // change value to decrease or // increase the height of wave var wave_height = 4; // change value to decrease or // increase the length of wave var wave_length = 4; pattern(wave_height, wave_length); // This code contributed by gauravrajput1</script> Output : 04 05 04 05 04 05 04 05 03 06 03 06 03 06 03 06 02 07 02 07 02 07 02 07 01 08 01 08 01 08 01 08 Program to print wave pattern using letters .Examples : Input : wave_height = 4 wave_length = 4 Output : D E L M T U B C C F K N S V A D B G J O R W Z E A H I P Q X Y F C++ Java Python3 C# PHP Javascript #include <iostream>using namespace std; // Function definitionvoid pattern(int wave_height, int wave_length){ int i, j, k, e, n, count, x; e = 2; x = 1; int c1 = 'A' + wave_height - 1; int c2 = 'A' + wave_height; // for loop for height of wave for (i = 1; i <= wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) { cout << " "; } // for loop for wave length for (count = 1; count <= wave_length; count++) { // checking for intermediate spaces for (n = (wave_height + wave_height - 2); n >= x; n--) cout << " "; for (k = 1; k <= e; k++) { if (k == 1) cout << (char)c1 << " "; else if (k == e) cout << (char)c2 << " "; else cout << " "; } c1 = c1 + wave_height * 2; c2 = c2 + wave_height * 2; // checking the limit if (c1 > 'Z') c1 = c1 - 26; if (c2 > 'Z') c2 = c2 - 26; } // incrementing counters value by two x = x + 2; e = e + 2; c1 = 'A' + wave_height - i - 1; c2 = 'A' + wave_height + i; cout << endl; }} // Driver codeint main(){ // change value to decrease or increase // the height of wave int wave_height = 4; // change value to decrease or increase // the length of wave int wave_length = 4; pattern(wave_height, wave_length); return 0;} // Java Program to print// wave patternimport java.io.*; class GFG { // Function definition static void pattern(int wave_height, int wave_length) { int i, j, k, e, n, count, x; e = 2; x = 1; int c1 = 'A' + wave_height - 1; int c2 = 'A' + wave_height; // for loop for height // of wave for (i = 1; i <= wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) { System.out.print(" "); } // for loop for wave // length for (count = 1; count <= wave_length; count++) { // checking for intermediate // spaces for (n = (wave_height + wave_height - 2); n >= x; n--) System.out.print(" "); for (k = 1; k <= e; k++) { if (k == 1) System.out.print((char)c1 + " "); else if (k == e) System.out.print((char)c2 + " "); else System.out.print(" "); } c1 = c1 + wave_height * 2; c2 = c2 + wave_height * 2; // checking the limit if (c1 > 'Z') c1 = c1 - 26; if (c2 > 'Z') c2 = c2 - 26; } // incrementing counters // value by two x = x + 2; e = e + 2; c1 = 'A' + wave_height - i - 1; c2 = 'A' + wave_height + i; System.out.println(); } } // Driver code public static void main(String args[]) { // change value to decrease or // increase the height of wave int wave_height = 4; // change value to decrease or // increase the length of wave int wave_length = 4; pattern(wave_height, wave_length); }} // This code is contributed by Nikita Tiwari. # Python3 program to print# the wave pattern # Function definitiondef pattern(wave_height, wave_length) : e = 2 x = 1 c1 = ord('A') + wave_height - 1 c2 = ord('A') + wave_height # for loop for height # of wave for i in range(1, wave_height + 1) : for j in range(wave_height, wave_height + i + 1 ): print( " ", end = "") # for loop for wave # length for count in range(1, wave_length + 1) : # checking for intermediate # spaces for n in range((wave_height + wave_height - 2), x - 1, -1) : print(" ", end = "") for k in range(1, e + 1) : if (k == 1) : print((chr)(c1), " ", end = "") elif (k == e) : print((chr)(c2), " ", end = "") else : print(" ", end = "") c1 = c1 + wave_height * 2 c2 = c2 + wave_height * 2 # checking the limit if (c1 > ord('Z')) : c1 = c1 - 26 if (c2 > ord('Z')) : c2 = c2 - 26 # incrementing counters # value by two x = x + 2; e = e + 2 c1 = ord('A') + wave_height - i - 1 c2 = ord('A') + wave_height + i print() # Driver code # change value to decrease or# increase the height of wavewave_height = 4 # change value to decrease or# increase the length of wavewave_length = 4 pattern(wave_height, wave_length) # This code is contributed by Nikita Tiwari. // C# Program to print// wave patternusing System; class GFG{// Function definitionstatic void pattern(int wave_height, int wave_length){ int i, j, k, e, n, count, x; e = 2; x = 1; int c1 = 'A' + wave_height - 1; int c2 = 'A' + wave_height; // for loop for height // of wave for (i = 1; i <= wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) { Console.Write(" "); } // for loop for wave // length for (count = 1; count <= wave_length; count++) { // checking for intermediate // spaces for (n = (wave_height + wave_height - 2); n >= x; n--) Console.Write(" "); for (k = 1; k <= e; k++) { if (k == 1) Console.Write((char)c1 + " "); else if (k == e) Console.Write((char)c2 + " "); else Console.Write(" "); } c1 = c1 + wave_height * 2; c2 = c2 + wave_height * 2; // checking the limit if (c1 > 'Z') c1 = c1 - 26; if (c2 > 'Z') c2 = c2 - 26; } // incrementing counters // value by two x = x + 2; e = e + 2; c1 = 'A' + wave_height - i - 1; c2 = 'A' + wave_height + i; Console.WriteLine(); }} // Driver codestatic public void Main (){ // change value to decrease or // increase the height of wave int wave_height = 4; // change value to decrease or // increase the length of wave int wave_length = 4; pattern(wave_height, wave_length);}} // This code is contributed by ajit <?php// PHP implementation to print// Wave pattern using Alphabets // Function definitionfunction pattern($wave_height, $wave_length){ $e = 2; $x = 1; //ASCII of A is 65 $c1 = 65 + $wave_height - 1; $c2 = 65 + $wave_height; // for loop for height of wave for ($i = 1; $i <= $wave_height; $i++) { for ($j = $wave_height; $j <= $wave_height + $i; $j++) { echo " "; } // for loop for wave length for ($count = 1; $count <= $wave_length; $count++) { // checking for intermediate // spaces for ($n = ($wave_height + $wave_height - 2); $n >= $x; $n--) echo " "; for ($k = 1; $k <= $e; $k++) { if ($k == 1) echo chr($c1)." "; else if ($k == $e) echo chr($c2)." "; else echo " "; } $c1 = $c1 + $wave_height * 2; $c2 = $c2 + $wave_height * 2; // checking the limit if ($c1 > 90) $c1 = $c1 - 26; if ($c2 > 90) $c2 = $c2 - 26; } // incrementing counters value // by two $x = $x + 2; $e = $e + 2; $c1 = 65 + $wave_height - $i - 1; $c2 = 65 + $wave_height + $i; echo "\n"; }} // Driver code$wave_height = 4;$wave_length = 4;pattern($wave_height, $wave_length); // This code is contributed by Mithun Kumar?> <script> // Javascript Program to print// wave pattern // Function definitionfunction pattern(wave_height, wave_length){ var i, j, k, e, n, count, x; e = 2; x = 1; var c1 = 'A'.charCodeAt(0) + wave_height - 1; var c2 = 'A'.charCodeAt(0) + wave_height; // For loop for height // of wave for(i = 1; i <= wave_height; i++) { for(j = wave_height; j <= wave_height + i; j++) { document.write(" "); } // For loop for wave // length for(count = 1; count <= wave_length; count++) { // Checking for intermediate // spaces for(n = (wave_height + wave_height - 2); n >= x; n--) document.write(" "); for(k = 1; k <= e; k++) { if (k == 1) document.write( String.fromCharCode(c1) + " "); else if (k == e) document.write( String.fromCharCode(c2) + " "); else document.write(" "); } c1 = c1 + wave_height * 2; c2 = c2 + wave_height * 2; // checking the limit if (c1 > 'Z'.charCodeAt(0)) c1 = c1 - 26; if (c2 > 'Z'.charCodeAt(0)) c2 = c2 - 26; } // Incrementing counters // value by two x = x + 2; e = e + 2; c1 = 'A'.charCodeAt(0) + wave_height - i - 1; c2 = 'A'.charCodeAt(0) + wave_height + i; document.write('<br>'); }} // Driver code // Change value to decrease or// increase the height of wavevar wave_height = 4; // Change value to decrease or// increase the length of wavevar wave_length = 4; pattern(wave_height, wave_length); // This code is contributed by Princi Singh </script> Output : D E L M T U B C C F K N S V A D B G J O R W Z E A H I P Q X Y F Mithun Kumar jit_t todaysgaurav GauravRajput1 princi singh bunnyram19 khushboogoyal499 pattern-printing School Programming pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Interfaces in Java C++ Classes and Objects Operator Overloading in C++ Constructors in C++ Copy Constructor in C++ Overriding in Java Polymorphism in C++ C++ Data Types Different ways of Reading a text file in Java Types of Operating Systems
[ { "code": null, "e": 24806, "s": 24778, "text": "\n29 Oct, 2021" }, { "code": null, "e": 24889, "s": 24806, "text": "Given length and width, print the pattern in wave form using ‘/’ and ”.Examples : " }, { "code": null, "e": 25174, "s": 24889, "text": "Input : wave_height = 4\n wave_length = 4\nOutput :\n /\\ /\\ /\\ /\\ \n / \\ / \\ / \\ / \\ \n / \\ / \\ / \\ / \\ \n/ \\/ \\/ \\/ \\ \n\nInput : wave_height = 2\n wave_length = 3\nOutput : \n /\\ /\\ /\\\n/ \\/ \\/ \\" }, { "code": null, "e": 25178, "s": 25174, "text": "C++" }, { "code": null, "e": 25183, "s": 25178, "text": "Java" }, { "code": null, "e": 25191, "s": 25183, "text": "Python3" }, { "code": null, "e": 25194, "s": 25191, "text": "C#" }, { "code": null, "e": 25198, "s": 25194, "text": "PHP" }, { "code": null, "e": 25209, "s": 25198, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; // Function definitionvoid pattern(int wave_height, int wave_length){ int i, j, k, e, n, count, x; e = 2; x = 1; // for loop for height of wave for (i = 0; i < wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) cout << \" \"; // for loop for wave length for (count = 1; count <= wave_length; count++) { // checking for intermediate spaces for (n = (wave_height + wave_height - 2); n >= x; n--) cout << \" \"; for (k = 1; k <= e; k++) { if (k == 1) cout << \"/\"; else if (k == e) cout << \"\\\\\"; else cout << \" \"; } } // incrementing counters value by two x = x + 2; e = e + 2; cout << endl; }} // Driver codeint main(){ // change value to decrease or increase // the height of wave int wave_height = 4; // change value to decrease or increase // the length of wave int wave_length = 4; pattern(wave_height, wave_length); return 0;}", "e": 26376, "s": 25209, "text": null }, { "code": "import java.io.*; class GFG { // Function definition static void pattern(int wave_height, int wave_length) { int i, j, k, e, n, count, x; e = 2; x = 1; // for loop for height // of wave for (i = 0; i < wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) System.out.print(\" \"); // for loop for wave // length for (count = 1; count <= wave_length; count++) { // checking for intermediate // spaces for (n = (wave_height + wave_height - 2); n >= x; n--) System.out.print(\" \"); for (k = 1; k <= e; k++) { if (k == 1) System.out.print(\"/\"); else if (k == e) System.out.print(\"\\\\\"); else System.out.print(\" \"); } } // incrementing counters // value by two x = x + 2; e = e + 2; System.out.println(); } } // Driver code public static void main(String args[]) { // change value to decrease or // increase the height of wave int wave_height = 4; // change value to decrease or // increase the length of wave int wave_length = 4; pattern(wave_height, wave_length); }} // This code is contributed by Nikita Tiwari.", "e": 27953, "s": 26376, "text": null }, { "code": "# Function definitiondef pattern(wave_height, wave_length) : e = 2 x = 1 # for loop for height # of wave for i in range(0, wave_height) : for j in range(wave_height, wave_height + i+1) : print(\" \", end =\"\") # for loop for wave # length for count in range(1, wave_length + 1) : # checking for intermediate spaces for n in range((wave_height + wave_height - 2), x-1, -1) : print(\" \", end =\"\") for k in range(1, e + 1) : if (k == 1) : print(\"/\", end =\"\") elif (k == e) : print(\"\\\\\", end =\"\") else : print(\" \", end =\"\") # incrementing counters # value by two x = x + 2 e = e + 2 print(\"\") # Driver code # Change value to decrease or increase# the height of wavewave_height = 4 # change value to decrease or increase# the length of wavewave_length = 4 pattern(wave_height, wave_length); # This code is contributed by Nikita Tiwari.", "e": 29080, "s": 27953, "text": null }, { "code": "// C# code for Wave Patternsusing System; class GFG { // Function definition static void pattern(int wave_height, int wave_length) { int i, j, k, e, n, count, x; e = 2; x = 1; // for loop for height // of wave for (i = 0; i < wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) Console.Write(\" \"); // for loop for wave // length for (count = 1; count <= wave_length; count++) { // checking for intermediate // spaces for (n = (wave_height + wave_height - 2); n >= x; n--) Console.Write(\" \"); for (k = 1; k <= e; k++) { if (k == 1) Console.Write(\"/\"); else if (k == e) Console.Write(\"\\\\\"); else Console.Write(\" \"); } } // incrementing counters // value by two x = x + 2; e = e + 2; Console.WriteLine(); } } // Driver code public static void Main() { // change value to decrease or // increase the height of wave int wave_height = 4; // change value to decrease or // increase the length of wave int wave_length = 4; pattern(wave_height, wave_length); }} // This code is contributed by vt_m.", "e": 30623, "s": 29080, "text": null }, { "code": "<?php// PHP implementation to// print wave patterns // Function definitionfunction pattern($wave_height,$wave_length){ $e = 2; $x = 1; // for loop for height of wave for ($i = 0; $i < $wave_height; $i++) { for ($j = $wave_height; $j <= $wave_height + $i; $j++) echo \" \"; // for loop for wave length for ($count = 1; $count <= $wave_length; $count++) { // checking for intermediate // spaces for ($n = ($wave_height + $wave_height - 2); $n >= $x; $n--) echo \" \"; for ($k = 1; $k <= $e; $k++) { if ($k == 1) echo \"/\"; else if ($k == $e) echo \"\\\\\"; else echo \" \"; } } // incrementing counters value by two $x = $x + 2; $e = $e + 2; echo \"\\n\"; }} // Driver code$wave_height = 4;$wave_length = 4;pattern($wave_height, $wave_length); // This code is contributed by Mithun Kumar?>", "e": 31786, "s": 30623, "text": null }, { "code": "<script> // Function definition function pattern( wave_height , wave_length) { let i, j, k, e, n, count, x; e = 2; x = 1; // for loop for height // of wave for (i = 0; i < wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) document.write(\" \"); // for loop for wave // length for (count = 1; count <= wave_length; count++) { // checking for intermediate // spaces for (n = (wave_height + wave_height - 2); n >= x; n--) document.write(\" \"); for (k = 1; k <= e; k++) { if (k == 1) document.write(\"/\"); else if (k == e) document.write(\"\\\\\"); else document.write(\" \"); } } // incrementing counters // value by two x = x + 2; e = e + 2; document.write(\"<br/>\"); } } // Driver code // change value to decrease or // increase the height of wave let wave_height = 4; // change value to decrease or // increase the length of wave let wave_length = 4; pattern(wave_height, wave_length); // This code is contributed by todaysgaurav</script>", "e": 33231, "s": 31786, "text": null }, { "code": null, "e": 33241, "s": 33231, "text": "Output : " }, { "code": null, "e": 33385, "s": 33241, "text": " /\\ /\\ /\\ /\\ \n / \\ / \\ / \\ / \\ \n / \\ / \\ / \\ / \\ \n/ \\/ \\/ \\/ \\\n " }, { "code": null, "e": 33427, "s": 33385, "text": "To print numbers in wave form.Examples : " }, { "code": null, "e": 33759, "s": 33427, "text": "Input : wave_height = 4\n wave_length = 4\nOutput :\n\n 04 05 04 05 04 05 04 05\n 03 06 03 06 03 06 03 06\n 02 07 02 07 02 07 02 07\n01 08 01 08 01 08 01 08 \n\nInput : wave_height = 2\n wave_length = 2 \nOutput : \n 02 02\n01 03 01 03" }, { "code": null, "e": 33763, "s": 33759, "text": "C++" }, { "code": null, "e": 33768, "s": 33763, "text": "Java" }, { "code": null, "e": 33776, "s": 33768, "text": "Python3" }, { "code": null, "e": 33779, "s": 33776, "text": "C#" }, { "code": null, "e": 33783, "s": 33779, "text": "PHP" }, { "code": null, "e": 33794, "s": 33783, "text": "Javascript" }, { "code": "// C++ code to print numbers// in wave form#include <iostream>using namespace std; // Function definitionvoid pattern(int wave_height, int wave_length){ int i, j, k, e, n, count, x, n1, n2; e = 2; x = 1; n1 = wave_height; n2 = wave_height + 1; // for loop for height of wave for (i = 1; i <= wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) { cout << \" \"; } // for loop for wave length for (count = 1; count <= wave_length; count++) { // checking for intermediate spaces for (n = (wave_height + wave_height - 2); n >= x; n--) cout << \" \"; for (k = 1; k <= e; k++) { if (k == 1) cout << \"0\" << n1 << \" \"; else if (k == e) cout << \"0\" << n2 << \" \"; else cout << \" \"; } } // incrementing counters value by two x = x + 2; e = e + 2; n1 = wave_height - i; n2 = wave_height + 1 + i; cout << endl; }} // Driver codeint main(){ // change value to decrease or // increase the height of wave int wave_height = 4; // change value to decrease or // increase the length of wave int wave_length = 4; pattern(wave_height, wave_length); return 0;}", "e": 35150, "s": 33794, "text": null }, { "code": "// Java code to print numbers// in wave formimport java.io.*; class GFG { // Function definition static void pattern(int wave_height, int wave_length) { int i, j, k, e, n; int count, x, n1, n2; e = 2; x = 1; n1 = wave_height; n2 = wave_height + 1; // for loop for height // of wave for (i = 1; i <= wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) { System.out.print(\" \"); } // for loop for wave // length for (count = 1; count <= wave_length; count++) { // checking for intermediate // spaces for (n = (wave_height + wave_height - 2); n >= x; n--) System.out.print(\" \"); for (k = 1; k <= e; k++) { if (k == 1) System.out.print(\"0\" + n1 + \" \"); else if (k == e) System.out.print(\"0\" + n2 + \" \"); else System.out.print(\" \"); } } // incrementing counters // value by two x = x + 2; e = e + 2; n1 = wave_height - i; n2 = wave_height + 1 + i; System.out.println(); } } // Driver code public static void main(String args[]) { // change value to decrease or // increase the height of wave int wave_height = 4; // change value to decrease or // increase the length of wave int wave_length = 4; pattern(wave_height, wave_length); }} // This code is contributed by Nikita Tiwari.", "e": 36972, "s": 35150, "text": null }, { "code": "# Python 3 code to print numbers# in wave form # Function definitiondef pattern( wave_height, wave_length) : e = 2 x = 1 n1 = wave_height n2 = wave_height + 1 # for loop for height # of wave for i in range(1, wave_height + 1) : for j in range( wave_height, wave_height + i + 1) : print( \" \", end =\"\") # for loop for wave # length for count in range(1, wave_length + 1) : # checking for intermediate # spaces for n in range((wave_height + wave_height - 2), x - 1, -1) : print( \" \", end =\"\") for k in range(1, e + 1) : if (k == 1) : print(\"0\", n1, \" \", end =\"\") elif (k == e) : print(\"0\", n2, \" \", end =\"\") else : print(\" \", end =\"\") # incrementing counters value # by two x = x + 2 e = e + 2 n1 = wave_height - i n2 = wave_height + 1 + i print() # Driver code # change value to decrease or# increase the height of wavewave_height = 4 # change value to decrease or# increase the length of wavewave_length = 4 pattern(wave_height, wave_length) # This code is contributed by Nikita Tiwari.", "e": 38334, "s": 36972, "text": null }, { "code": "// C# code to print numbers// in wave formusing System; class GFG{ // Function definition static void pattern(int wave_height, int wave_length) { int i, j, k, e, n; int count, x, n1, n2; e = 2; x = 1; n1 = wave_height; n2 = wave_height + 1; // for loop for // height of wave for (i = 1; i <= wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) { Console.Write(\" \"); } // for loop for // wave length for (count = 1; count <= wave_length; count++) { // checking for intermediate // spaces for (n = (wave_height + wave_height - 2); n >= x; n--) Console.Write(\" \"); for (k = 1; k <= e; k++) { if (k == 1) Console.Write(\"0\" + n1 + \" \"); else if (k == e) Console.Write(\"0\" + n2 + \" \"); else Console.Write(\" \"); } } // incrementing counters // value by two x = x + 2; e = e + 2; n1 = wave_height - i; n2 = wave_height + 1 + i; Console.WriteLine(); } } // Driver code static public void Main () { // change value to decrease or // increase the height of wave int wave_height = 4; // change value to decrease or // increase the length of wave int wave_length = 4; pattern(wave_height, wave_length); }} // This code is contributed by ajit.", "e": 40202, "s": 38334, "text": null }, { "code": "<?php// PHP implementation to print// numbers in wave form // Function definitionfunction pattern($wave_height, $wave_length){ $e = 2; $x = 1; $n1 = $wave_height; $n2 = $wave_height + 1; // for loop for height of wave for ($i = 1; $i <= $wave_height; $i++) { for ($j = $wave_height; $j <= $wave_height + $i; $j++) { echo \" \"; } // for loop for wave length for ($count = 1; $count <= $wave_length; $count++) { // checking for intermediate // spaces for ($n = ($wave_height + $wave_height - 2); $n >= $x; $n--) echo \" \"; for ($k = 1; $k <= $e; $k++) { if ($k == 1) echo \"0\".$n1.\" \"; else if ($k == $e) echo \"0\".$n2.\" \"; else echo \" \"; } } // incrementing counters value // by two $x = $x + 2; $e = $e + 2; $n1 = $wave_height - $i; $n2 = $wave_height + 1 + $i; echo \"\\n\"; }} // Driver code$wave_height = 4;$wave_length = 4;pattern($wave_height, $wave_length); // This code is contributed by Mithun Kumar?>", "e": 41562, "s": 40202, "text": null }, { "code": "<script>// javascript code to print numbers// in wave form // Function definition function pattern(wave_height , wave_length) { var i, j, k, e, n; var count, x, n1, n2; e = 2; x = 1; n1 = wave_height; n2 = wave_height + 1; // for loop for height // of wave for (i = 1; i <= wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) { document.write(\" \"); } // for loop for wave // length for (count = 1; count <= wave_length; count++) { // checking for intermediate // spaces for (n = (wave_height + wave_height - 2); n >= x; n--) document.write(\" \"); for (k = 1; k <= e; k++) { if (k == 1) document.write(\"0\" + n1 + \" \"); else if (k == e) document.write(\"0\" + n2 + \" \"); else document.write(\" \"); } } // incrementing counters // value by two x = x + 2; e = e + 2; n1 = wave_height - i; n2 = wave_height + 1 + i; document.write(\"<br/>\"); } } // Driver code // change value to decrease or // increase the height of wave var wave_height = 4; // change value to decrease or // increase the length of wave var wave_length = 4; pattern(wave_height, wave_length); // This code contributed by gauravrajput1</script>", "e": 43207, "s": 41562, "text": null }, { "code": null, "e": 43217, "s": 43207, "text": "Output : " }, { "code": null, "e": 43404, "s": 43217, "text": " 04 05 04 05 04 05 04 05\n 03 06 03 06 03 06 03 06\n 02 07 02 07 02 07 02 07\n01 08 01 08 01 08 01 08 " }, { "code": null, "e": 43462, "s": 43404, "text": "Program to print wave pattern using letters .Examples : " }, { "code": null, "e": 43684, "s": 43462, "text": "Input : wave_height = 4\n wave_length = 4\nOutput :\n\n\n D E L M T U B C \n C F K N S V A D \n B G J O R W Z E \nA H I P Q X Y F" }, { "code": null, "e": 43688, "s": 43684, "text": "C++" }, { "code": null, "e": 43693, "s": 43688, "text": "Java" }, { "code": null, "e": 43701, "s": 43693, "text": "Python3" }, { "code": null, "e": 43704, "s": 43701, "text": "C#" }, { "code": null, "e": 43708, "s": 43704, "text": "PHP" }, { "code": null, "e": 43719, "s": 43708, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; // Function definitionvoid pattern(int wave_height, int wave_length){ int i, j, k, e, n, count, x; e = 2; x = 1; int c1 = 'A' + wave_height - 1; int c2 = 'A' + wave_height; // for loop for height of wave for (i = 1; i <= wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) { cout << \" \"; } // for loop for wave length for (count = 1; count <= wave_length; count++) { // checking for intermediate spaces for (n = (wave_height + wave_height - 2); n >= x; n--) cout << \" \"; for (k = 1; k <= e; k++) { if (k == 1) cout << (char)c1 << \" \"; else if (k == e) cout << (char)c2 << \" \"; else cout << \" \"; } c1 = c1 + wave_height * 2; c2 = c2 + wave_height * 2; // checking the limit if (c1 > 'Z') c1 = c1 - 26; if (c2 > 'Z') c2 = c2 - 26; } // incrementing counters value by two x = x + 2; e = e + 2; c1 = 'A' + wave_height - i - 1; c2 = 'A' + wave_height + i; cout << endl; }} // Driver codeint main(){ // change value to decrease or increase // the height of wave int wave_height = 4; // change value to decrease or increase // the length of wave int wave_length = 4; pattern(wave_height, wave_length); return 0;}", "e": 45273, "s": 43719, "text": null }, { "code": "// Java Program to print// wave patternimport java.io.*; class GFG { // Function definition static void pattern(int wave_height, int wave_length) { int i, j, k, e, n, count, x; e = 2; x = 1; int c1 = 'A' + wave_height - 1; int c2 = 'A' + wave_height; // for loop for height // of wave for (i = 1; i <= wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) { System.out.print(\" \"); } // for loop for wave // length for (count = 1; count <= wave_length; count++) { // checking for intermediate // spaces for (n = (wave_height + wave_height - 2); n >= x; n--) System.out.print(\" \"); for (k = 1; k <= e; k++) { if (k == 1) System.out.print((char)c1 + \" \"); else if (k == e) System.out.print((char)c2 + \" \"); else System.out.print(\" \"); } c1 = c1 + wave_height * 2; c2 = c2 + wave_height * 2; // checking the limit if (c1 > 'Z') c1 = c1 - 26; if (c2 > 'Z') c2 = c2 - 26; } // incrementing counters // value by two x = x + 2; e = e + 2; c1 = 'A' + wave_height - i - 1; c2 = 'A' + wave_height + i; System.out.println(); } } // Driver code public static void main(String args[]) { // change value to decrease or // increase the height of wave int wave_height = 4; // change value to decrease or // increase the length of wave int wave_length = 4; pattern(wave_height, wave_length); }} // This code is contributed by Nikita Tiwari.", "e": 47382, "s": 45273, "text": null }, { "code": "# Python3 program to print# the wave pattern # Function definitiondef pattern(wave_height, wave_length) : e = 2 x = 1 c1 = ord('A') + wave_height - 1 c2 = ord('A') + wave_height # for loop for height # of wave for i in range(1, wave_height + 1) : for j in range(wave_height, wave_height + i + 1 ): print( \" \", end = \"\") # for loop for wave # length for count in range(1, wave_length + 1) : # checking for intermediate # spaces for n in range((wave_height + wave_height - 2), x - 1, -1) : print(\" \", end = \"\") for k in range(1, e + 1) : if (k == 1) : print((chr)(c1), \" \", end = \"\") elif (k == e) : print((chr)(c2), \" \", end = \"\") else : print(\" \", end = \"\") c1 = c1 + wave_height * 2 c2 = c2 + wave_height * 2 # checking the limit if (c1 > ord('Z')) : c1 = c1 - 26 if (c2 > ord('Z')) : c2 = c2 - 26 # incrementing counters # value by two x = x + 2; e = e + 2 c1 = ord('A') + wave_height - i - 1 c2 = ord('A') + wave_height + i print() # Driver code # change value to decrease or# increase the height of wavewave_height = 4 # change value to decrease or# increase the length of wavewave_length = 4 pattern(wave_height, wave_length) # This code is contributed by Nikita Tiwari.", "e": 49018, "s": 47382, "text": null }, { "code": "// C# Program to print// wave patternusing System; class GFG{// Function definitionstatic void pattern(int wave_height, int wave_length){ int i, j, k, e, n, count, x; e = 2; x = 1; int c1 = 'A' + wave_height - 1; int c2 = 'A' + wave_height; // for loop for height // of wave for (i = 1; i <= wave_height; i++) { for (j = wave_height; j <= wave_height + i; j++) { Console.Write(\" \"); } // for loop for wave // length for (count = 1; count <= wave_length; count++) { // checking for intermediate // spaces for (n = (wave_height + wave_height - 2); n >= x; n--) Console.Write(\" \"); for (k = 1; k <= e; k++) { if (k == 1) Console.Write((char)c1 + \" \"); else if (k == e) Console.Write((char)c2 + \" \"); else Console.Write(\" \"); } c1 = c1 + wave_height * 2; c2 = c2 + wave_height * 2; // checking the limit if (c1 > 'Z') c1 = c1 - 26; if (c2 > 'Z') c2 = c2 - 26; } // incrementing counters // value by two x = x + 2; e = e + 2; c1 = 'A' + wave_height - i - 1; c2 = 'A' + wave_height + i; Console.WriteLine(); }} // Driver codestatic public void Main (){ // change value to decrease or // increase the height of wave int wave_height = 4; // change value to decrease or // increase the length of wave int wave_length = 4; pattern(wave_height, wave_length);}} // This code is contributed by ajit", "e": 50878, "s": 49018, "text": null }, { "code": "<?php// PHP implementation to print// Wave pattern using Alphabets // Function definitionfunction pattern($wave_height, $wave_length){ $e = 2; $x = 1; //ASCII of A is 65 $c1 = 65 + $wave_height - 1; $c2 = 65 + $wave_height; // for loop for height of wave for ($i = 1; $i <= $wave_height; $i++) { for ($j = $wave_height; $j <= $wave_height + $i; $j++) { echo \" \"; } // for loop for wave length for ($count = 1; $count <= $wave_length; $count++) { // checking for intermediate // spaces for ($n = ($wave_height + $wave_height - 2); $n >= $x; $n--) echo \" \"; for ($k = 1; $k <= $e; $k++) { if ($k == 1) echo chr($c1).\" \"; else if ($k == $e) echo chr($c2).\" \"; else echo \" \"; } $c1 = $c1 + $wave_height * 2; $c2 = $c2 + $wave_height * 2; // checking the limit if ($c1 > 90) $c1 = $c1 - 26; if ($c2 > 90) $c2 = $c2 - 26; } // incrementing counters value // by two $x = $x + 2; $e = $e + 2; $c1 = 65 + $wave_height - $i - 1; $c2 = 65 + $wave_height + $i; echo \"\\n\"; }} // Driver code$wave_height = 4;$wave_length = 4;pattern($wave_height, $wave_length); // This code is contributed by Mithun Kumar?>", "e": 52565, "s": 50878, "text": null }, { "code": "<script> // Javascript Program to print// wave pattern // Function definitionfunction pattern(wave_height, wave_length){ var i, j, k, e, n, count, x; e = 2; x = 1; var c1 = 'A'.charCodeAt(0) + wave_height - 1; var c2 = 'A'.charCodeAt(0) + wave_height; // For loop for height // of wave for(i = 1; i <= wave_height; i++) { for(j = wave_height; j <= wave_height + i; j++) { document.write(\" \"); } // For loop for wave // length for(count = 1; count <= wave_length; count++) { // Checking for intermediate // spaces for(n = (wave_height + wave_height - 2); n >= x; n--) document.write(\" \"); for(k = 1; k <= e; k++) { if (k == 1) document.write( String.fromCharCode(c1) + \" \"); else if (k == e) document.write( String.fromCharCode(c2) + \" \"); else document.write(\" \"); } c1 = c1 + wave_height * 2; c2 = c2 + wave_height * 2; // checking the limit if (c1 > 'Z'.charCodeAt(0)) c1 = c1 - 26; if (c2 > 'Z'.charCodeAt(0)) c2 = c2 - 26; } // Incrementing counters // value by two x = x + 2; e = e + 2; c1 = 'A'.charCodeAt(0) + wave_height - i - 1; c2 = 'A'.charCodeAt(0) + wave_height + i; document.write('<br>'); }} // Driver code // Change value to decrease or// increase the height of wavevar wave_height = 4; // Change value to decrease or// increase the length of wavevar wave_length = 4; pattern(wave_height, wave_length); // This code is contributed by Princi Singh </script>", "e": 54483, "s": 52565, "text": null }, { "code": null, "e": 54493, "s": 54483, "text": "Output : " }, { "code": null, "e": 54656, "s": 54493, "text": " D E L M T U B C \n C F K N S V A D \n B G J O R W Z E \nA H I P Q X Y F" }, { "code": null, "e": 54671, "s": 54658, "text": "Mithun Kumar" }, { "code": null, "e": 54677, "s": 54671, "text": "jit_t" }, { "code": null, "e": 54690, "s": 54677, "text": "todaysgaurav" }, { "code": null, "e": 54704, "s": 54690, "text": "GauravRajput1" }, { "code": null, "e": 54717, "s": 54704, "text": "princi singh" }, { "code": null, "e": 54728, "s": 54717, "text": "bunnyram19" }, { "code": null, "e": 54745, "s": 54728, "text": "khushboogoyal499" }, { "code": null, "e": 54762, "s": 54745, "text": "pattern-printing" }, { "code": null, "e": 54781, "s": 54762, "text": "School Programming" }, { "code": null, "e": 54798, "s": 54781, "text": "pattern-printing" }, { "code": null, "e": 54896, "s": 54798, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 54905, "s": 54896, "text": "Comments" }, { "code": null, "e": 54918, "s": 54905, "text": "Old Comments" }, { "code": null, "e": 54937, "s": 54918, "text": "Interfaces in Java" }, { "code": null, "e": 54961, "s": 54937, "text": "C++ Classes and Objects" }, { "code": null, "e": 54989, "s": 54961, "text": "Operator Overloading in C++" }, { "code": null, "e": 55009, "s": 54989, "text": "Constructors in C++" }, { "code": null, "e": 55033, "s": 55009, "text": "Copy Constructor in C++" }, { "code": null, "e": 55052, "s": 55033, "text": "Overriding in Java" }, { "code": null, "e": 55072, "s": 55052, "text": "Polymorphism in C++" }, { "code": null, "e": 55087, "s": 55072, "text": "C++ Data Types" }, { "code": null, "e": 55133, "s": 55087, "text": "Different ways of Reading a text file in Java" } ]
Batch Script - Debugging
Debugging a batch script becomes important when you are working on a big complex batch script. Following are the ways in which you can debug the batch file. A very simple debug option is to make use of echo command in your batch script wherever possible. It will display the message in the command prompt and help you debug where things have gone wrong. Here is a simple example that displays even numbers based on the input given. The echo command is used to display the result and also if the input is not given. Similarly, the echo command can be used in place when you think that the error can happen. For example, if the input given is a negative number, less than 2, etc. @echo off if [%1] == [] ( echo input value not provided goto stop ) rem Display numbers for /l %%n in (2,2,%1) do ( echo %%n ) :stop pause C:\>test.bat 10 2 4 6 8 10 22 Press any key to continue ... Another way is to pause the batch execution when there is an error. When the script is paused, the developer can fix the issue and restart the processing. In the example below, the batch script is paused as the input value is mandatory and not provided. @echo off if [%1] == [] ( echo input value not provided goto stop ) else ( echo "Valid value" ) :stop pause C:\>test.bat input value not provided Press any key to continue.. It might get hard to debug the error just looking at a bunch of echo displayed on the command prompt. Another easy way out is to log those messages in another file and view it step by step to understand what went wrong. Here is an example, consider the following test.bat file: net statistics /Server The command given in the .bat file is wrong. Let us log the message and see what we get. Execute the following command in your command line: C:\>test.bat > testlog.txt 2> testerrors.txt The file testerrors.txt will display the error messages as shown below: The option /SERVER is unknown. The syntax of this command is: NET STATISTICS [WORKSTATION | SERVER] More help is available by typing NET HELPMSG 3506. Looking at the above file the developer can fix the program and execute again. Errorlevel returns 0 if the command executes successfully and 1 if it fails. Consider the following example: @echo off PING google.com if errorlevel 1 GOTO stop :stop echo Unable to connect to google.com pause During execution, you can see errors as well as logs: C:\>test.bat > testlog.txt testlog.txt Pinging google.com [172.217.26.238] with 32 bytes of data: Reply from 172.217.26.238: bytes=32 time=160ms TTL=111 Reply from 172.217.26.238: bytes=32 time=82ms TTL=111 Reply from 172.217.26.238: bytes=32 time=121ms TTL=111 Reply from 172.217.26.238: bytes=32 time=108ms TTL=111 Ping statistics for 172.217.26.238: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 82ms, Maximum = 160ms, Average = 117ms Connected successfully Press any key to continue . . . In case of failure, you will see the following logs inside testlog.txt. Ping request could not find host google.com. Please check the name and try again. Unable to connect to google.com Press any key to continue . . . Print Add Notes Bookmark this page
[ { "code": null, "e": 2264, "s": 2169, "text": "Debugging a batch script becomes important when you are working on a big complex batch script." }, { "code": null, "e": 2326, "s": 2264, "text": "Following are the ways in which you can debug the batch file." }, { "code": null, "e": 2523, "s": 2326, "text": "A very simple debug option is to make use of echo command in your batch script wherever possible. It will display the message in the command prompt and help you debug where things have gone wrong." }, { "code": null, "e": 2847, "s": 2523, "text": "Here is a simple example that displays even numbers based on the input given. The echo command is used to display the result and also if the input is not given. Similarly, the echo command can be used in place when you think that the error can happen. For example, if the input given is a negative number, less than 2, etc." }, { "code": null, "e": 3009, "s": 2847, "text": "@echo off \nif [%1] == [] ( \n echo input value not provided \n goto stop \n) \nrem Display numbers \nfor /l %%n in (2,2,%1) do ( \n echo %%n \n) \n:stop \npause " }, { "code": null, "e": 3078, "s": 3009, "text": "C:\\>test.bat \n10 \n2 \n4 \n6 \n8 \n10 \n22\nPress any key to continue ... \n" }, { "code": null, "e": 3233, "s": 3078, "text": "Another way is to pause the batch execution when there is an error. When the script is paused, the developer can fix the issue and restart the processing." }, { "code": null, "e": 3332, "s": 3233, "text": "In the example below, the batch script is paused as the input value is mandatory and not provided." }, { "code": null, "e": 3464, "s": 3332, "text": "@echo off \nif [%1] == [] ( \n echo input value not provided \n goto stop \n) else ( \n echo \"Valid value\" \n) \n:stop \npause " }, { "code": null, "e": 3535, "s": 3464, "text": "C:\\>test.bat \n input value not provided \nPress any key to continue.. \n" }, { "code": null, "e": 3755, "s": 3535, "text": "It might get hard to debug the error just looking at a bunch of echo displayed on the command prompt. Another easy way out is to log those messages in another file and view it step by step to understand what went wrong." }, { "code": null, "e": 3813, "s": 3755, "text": "Here is an example, consider the following test.bat file:" }, { "code": null, "e": 3838, "s": 3813, "text": "net statistics /Server \n" }, { "code": null, "e": 3927, "s": 3838, "text": "The command given in the .bat file is wrong. Let us log the message and see what we get." }, { "code": null, "e": 3979, "s": 3927, "text": "Execute the following command in your command line:" }, { "code": null, "e": 4025, "s": 3979, "text": "C:\\>test.bat > testlog.txt 2> testerrors.txt\n" }, { "code": null, "e": 4097, "s": 4025, "text": "The file testerrors.txt will display the error messages as shown below:" }, { "code": null, "e": 4256, "s": 4097, "text": "The option /SERVER is unknown. \nThe syntax of this command is: \nNET STATISTICS \n[WORKSTATION | SERVER] \nMore help is available by typing NET HELPMSG 3506.\n" }, { "code": null, "e": 4335, "s": 4256, "text": "Looking at the above file the developer can fix the program and execute again." }, { "code": null, "e": 4412, "s": 4335, "text": "Errorlevel returns 0 if the command executes successfully and 1 if it fails." }, { "code": null, "e": 4444, "s": 4412, "text": "Consider the following example:" }, { "code": null, "e": 4556, "s": 4444, "text": "@echo off \nPING google.com \nif errorlevel 1 GOTO stop \n:stop \n echo Unable to connect to google.com \npause\n" }, { "code": null, "e": 4610, "s": 4556, "text": "During execution, you can see errors as well as logs:" }, { "code": null, "e": 4638, "s": 4610, "text": "C:\\>test.bat > testlog.txt\n" }, { "code": null, "e": 4650, "s": 4638, "text": "testlog.txt" }, { "code": null, "e": 5188, "s": 4650, "text": "Pinging google.com [172.217.26.238] with 32 bytes of data: \nReply from 172.217.26.238: bytes=32 time=160ms TTL=111 \nReply from 172.217.26.238: bytes=32 time=82ms TTL=111 \nReply from 172.217.26.238: bytes=32 time=121ms TTL=111 \nReply from 172.217.26.238: bytes=32 time=108ms TTL=111 \nPing statistics for 172.217.26.238: \n Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), \nApproximate round trip times in milli-seconds: \n Minimum = 82ms, Maximum = 160ms, Average = 117ms\n Connected successfully \nPress any key to continue . . .\n" }, { "code": null, "e": 5260, "s": 5188, "text": "In case of failure, you will see the following logs inside testlog.txt." }, { "code": null, "e": 5409, "s": 5260, "text": "Ping request could not find host google.com. Please check the name and try again. \nUnable to connect to google.com \nPress any key to continue . . .\n" }, { "code": null, "e": 5416, "s": 5409, "text": " Print" }, { "code": null, "e": 5427, "s": 5416, "text": " Add Notes" } ]
Set up an Airflow Environment on AWS in Minutes | by Brent Lemieux | Towards Data Science
Apache Airflow is a powerful platform for scheduling and monitoring data pipelines, machine learning workflows, and DevOps deployments. In this post, we’ll cover how to set up an Airflow environment on AWS and start scheduling workflows in the cloud. This is part one of a series, Scheduling Machine Learning Workflows. Airflow allows you to schedule your data pulls and featuring engineering pipelines, model training, model deployment, and much more. The content in this tutorial is applicable to anyone who wants to learn how to create, schedule, and monitor their production workflows in an Amazon Airflow environment — not just machine learning engineers. Set up an Airflow Environment on AWS (this post)More coming soon... Set up an Airflow Environment on AWS (this post) More coming soon... Whether you’re an aspiring to a career in engineering or data science, the skill-set of programmatically processing data and building systems to consume that data downstream (e.g. machine learning models) will likely be vital to your success. There’s a reason why these skills are in hot demand. Airflow is one of the most commonly used tools for orchestrating ETL jobs, machine learning pipelines, and DevOps deployments. When I first started out in machine learning, my (un)management of workflows makes me cringe today. I had jobs scheduled with cron in my own environment on a large, on-premise computer. There were no alerts for when my jobs failed and no UI to monitor progress — I had to manually check the logs each day! When I was on vacation, my co-workers were subjected to this brutal process. Airflow makes your workflows much more transparent. You can track your jobs progress in the UI and easily configure alerts for when something fails. Teams can easily share an Airflow environment, so you’re not always required to be on-call for your productions jobs. Up until recently, creating and maintaining an Airflow environment was fairly complex, even for experienced engineers. The Airflow platform includes a front-end webserver, a scheduler service, executors, and a backend database — all of which must be configured. On top of this, Airflow must be connected with other services, like Amazon EMR and S3, in order to utilize them in your pipelines. When I first started using Airflow, I naively tried to standup my own implementation (this was a disaster). I quickly realized that managed Airflow was the way to go. Before Amazon launched Managed Workflows with Apache Airflow, there were some other options in the space. However, with Amazon, you have the benefit of seamlessly integrating your workflow management solution with your other resources on AWS. Plus, AWS isn’t going away anytime soon, so you don’t have to worry about the stability of your pipeline management system hinging on another company staying in business. If your interested in learning how to setup an Airflow environment to help you get a job, to me, AWS is the place to start. More companies use AWS than any other cloud provider. Amazon helps you keep your Airflow version up to date. Minor version updates and patches are handled automatically and allows you to schedule major updates. WARNING: Creating a managed Airflow environment will cost money. If you’re just doing this for your own education, I recommend setting up the environment, loading and running your DAGs, then deleting your resources. See more on pricing here. AWS account setup. Create a test DAG and upload it to S3. Write a requirements.txt file to include open source packages in your environment. Create an Airflow environment in the AWS console. Access the Airflow UI. First things first, you’ll need an AWS account if you don’t already have one. Complete steps one and four in this tutorial to setup your account with an IAM admin user and an S3 bucket. Let’s create a simple Airflow DAG to test in our soon to be created environment. # test_dag.py# This code borrows heavily from https://airflow.apache.org/docs/apache-airflow/stable/tutorial.htmlfrom datetime import timedeltaimport loggingfrom airflow import DAGfrom airflow.operators.python_operator import PythonOperatorfrom airflow.utils.dates import days_agodefault_args = { 'owner': 'airflow', 'depends_on_past': False, 'email': ['[email protected]'], 'email_on_failure': True, 'email_on_retry': False, 'retries': 1, 'retry_delay': timedelta(minutes=5),}dag = DAG( 'simple_demo', default_args=default_args, description='A simple DAG with a few Python tasks.', schedule_interval=timedelta(days=1), start_date=days_ago(2), tags=['example'],)### PYTHON FUNCTIONSdef log_context(**kwargs): for key, value in kwargs.items(): logging.info(f"Context key {key} = {value}")def compute_product(a=None, b=None): logging.info(f"Inputs: a={a}, b={b}") if a == None or b == None: return None return a * b### OPERATORSt1 = PythonOperator( task_id="task1", python_callable=log_context, dag=dag)t2 = PythonOperator( task_id="task2", python_callable=compute_product, op_kwargs={'a': 3, 'b': 5}, dag=dag)t1 >> t2 We need to upload this DAG to our S3 bucket. This is straightforward to do in the AWS console — simply search for S3 in the console, navigate to the folder you’d like to upload to, and click Upload. Alternatively, you can use the AWS CLI to upload your DAG. Let’s create this path in our bucket and and upload our test DAG there: s3://<your-bucket>/airflow/dags/<your-dag.py>. Next, we’ll make a requirements.txt file where we’ll specify the open source packages we’d like installed in our environment. # requirements.txt exampleapache-airflow[amazon]==1.10.12boto3==1.17.44 Upload your requirements file to your S3 bucket in the following location: s3://<your-bucket>/airflow/requirements.txt. Now we’re ready to create our environment! Navigate to Managed Apache Airflow in the AWS console and click Create environment. Navigate to Managed Apache Airflow in the AWS console and click Create environment. 2. Name your environment and select your Airflow version (I recommend you choose the latest version). 3. Add your S3 bucket, your DAGs path, and requirements.txt path, then click Next. 4. Set the Web server access to Public network and check Create new security group. Next, click Create MWAA VPC. 5. In the CloudFormation template, leave the defaults and click Create stack. 6. You’ll need to wait a few minutes for your VPC to be created, then select your new VPC. 7. Select your environment class. I recommend selecting mw1.small and scaling up from there if needed. 8. Configure your Monitoring, Encryption, and Airflow configuration options— if you don’t know what to choose just leave the defaults for now. 9. Unless you know what permissions you need, choose the option to Create a new role and AWS will create a role with the necessary permissions for you. 10. Click Next, review your selections, and click Create environment! It will take 20–30 minutes to spin up your environment. Once your environment is ready, simply click Open Airflow UI and watch you’re up and running! Now that you know how to set up an Airflow cluster, try your hand at creating more Airflow DAGs and testing them in your environment. In the near future I’ll be creating more Airflow tutorials, covering topics like running Spark jobs in Amazon EMR. Thank you for reading! Please let me know if you liked the article or if you have any critiques. If you found this guide useful, be sure to follow me, so you don’t miss my future articles. If you need help with a data project or want to say hi, connect with me on LinkedIn. Cheers!
[ { "code": null, "e": 423, "s": 172, "text": "Apache Airflow is a powerful platform for scheduling and monitoring data pipelines, machine learning workflows, and DevOps deployments. In this post, we’ll cover how to set up an Airflow environment on AWS and start scheduling workflows in the cloud." }, { "code": null, "e": 833, "s": 423, "text": "This is part one of a series, Scheduling Machine Learning Workflows. Airflow allows you to schedule your data pulls and featuring engineering pipelines, model training, model deployment, and much more. The content in this tutorial is applicable to anyone who wants to learn how to create, schedule, and monitor their production workflows in an Amazon Airflow environment — not just machine learning engineers." }, { "code": null, "e": 901, "s": 833, "text": "Set up an Airflow Environment on AWS (this post)More coming soon..." }, { "code": null, "e": 950, "s": 901, "text": "Set up an Airflow Environment on AWS (this post)" }, { "code": null, "e": 970, "s": 950, "text": "More coming soon..." }, { "code": null, "e": 1266, "s": 970, "text": "Whether you’re an aspiring to a career in engineering or data science, the skill-set of programmatically processing data and building systems to consume that data downstream (e.g. machine learning models) will likely be vital to your success. There’s a reason why these skills are in hot demand." }, { "code": null, "e": 1393, "s": 1266, "text": "Airflow is one of the most commonly used tools for orchestrating ETL jobs, machine learning pipelines, and DevOps deployments." }, { "code": null, "e": 1776, "s": 1393, "text": "When I first started out in machine learning, my (un)management of workflows makes me cringe today. I had jobs scheduled with cron in my own environment on a large, on-premise computer. There were no alerts for when my jobs failed and no UI to monitor progress — I had to manually check the logs each day! When I was on vacation, my co-workers were subjected to this brutal process." }, { "code": null, "e": 2043, "s": 1776, "text": "Airflow makes your workflows much more transparent. You can track your jobs progress in the UI and easily configure alerts for when something fails. Teams can easily share an Airflow environment, so you’re not always required to be on-call for your productions jobs." }, { "code": null, "e": 2436, "s": 2043, "text": "Up until recently, creating and maintaining an Airflow environment was fairly complex, even for experienced engineers. The Airflow platform includes a front-end webserver, a scheduler service, executors, and a backend database — all of which must be configured. On top of this, Airflow must be connected with other services, like Amazon EMR and S3, in order to utilize them in your pipelines." }, { "code": null, "e": 2603, "s": 2436, "text": "When I first started using Airflow, I naively tried to standup my own implementation (this was a disaster). I quickly realized that managed Airflow was the way to go." }, { "code": null, "e": 3195, "s": 2603, "text": "Before Amazon launched Managed Workflows with Apache Airflow, there were some other options in the space. However, with Amazon, you have the benefit of seamlessly integrating your workflow management solution with your other resources on AWS. Plus, AWS isn’t going away anytime soon, so you don’t have to worry about the stability of your pipeline management system hinging on another company staying in business. If your interested in learning how to setup an Airflow environment to help you get a job, to me, AWS is the place to start. More companies use AWS than any other cloud provider." }, { "code": null, "e": 3352, "s": 3195, "text": "Amazon helps you keep your Airflow version up to date. Minor version updates and patches are handled automatically and allows you to schedule major updates." }, { "code": null, "e": 3594, "s": 3352, "text": "WARNING: Creating a managed Airflow environment will cost money. If you’re just doing this for your own education, I recommend setting up the environment, loading and running your DAGs, then deleting your resources. See more on pricing here." }, { "code": null, "e": 3613, "s": 3594, "text": "AWS account setup." }, { "code": null, "e": 3652, "s": 3613, "text": "Create a test DAG and upload it to S3." }, { "code": null, "e": 3735, "s": 3652, "text": "Write a requirements.txt file to include open source packages in your environment." }, { "code": null, "e": 3785, "s": 3735, "text": "Create an Airflow environment in the AWS console." }, { "code": null, "e": 3808, "s": 3785, "text": "Access the Airflow UI." }, { "code": null, "e": 3994, "s": 3808, "text": "First things first, you’ll need an AWS account if you don’t already have one. Complete steps one and four in this tutorial to setup your account with an IAM admin user and an S3 bucket." }, { "code": null, "e": 4075, "s": 3994, "text": "Let’s create a simple Airflow DAG to test in our soon to be created environment." }, { "code": null, "e": 5283, "s": 4075, "text": "# test_dag.py# This code borrows heavily from https://airflow.apache.org/docs/apache-airflow/stable/tutorial.htmlfrom datetime import timedeltaimport loggingfrom airflow import DAGfrom airflow.operators.python_operator import PythonOperatorfrom airflow.utils.dates import days_agodefault_args = { 'owner': 'airflow', 'depends_on_past': False, 'email': ['[email protected]'], 'email_on_failure': True, 'email_on_retry': False, 'retries': 1, 'retry_delay': timedelta(minutes=5),}dag = DAG( 'simple_demo', default_args=default_args, description='A simple DAG with a few Python tasks.', schedule_interval=timedelta(days=1), start_date=days_ago(2), tags=['example'],)### PYTHON FUNCTIONSdef log_context(**kwargs): for key, value in kwargs.items(): logging.info(f\"Context key {key} = {value}\")def compute_product(a=None, b=None): logging.info(f\"Inputs: a={a}, b={b}\") if a == None or b == None: return None return a * b### OPERATORSt1 = PythonOperator( task_id=\"task1\", python_callable=log_context, dag=dag)t2 = PythonOperator( task_id=\"task2\", python_callable=compute_product, op_kwargs={'a': 3, 'b': 5}, dag=dag)t1 >> t2" }, { "code": null, "e": 5541, "s": 5283, "text": "We need to upload this DAG to our S3 bucket. This is straightforward to do in the AWS console — simply search for S3 in the console, navigate to the folder you’d like to upload to, and click Upload. Alternatively, you can use the AWS CLI to upload your DAG." }, { "code": null, "e": 5660, "s": 5541, "text": "Let’s create this path in our bucket and and upload our test DAG there: s3://<your-bucket>/airflow/dags/<your-dag.py>." }, { "code": null, "e": 5786, "s": 5660, "text": "Next, we’ll make a requirements.txt file where we’ll specify the open source packages we’d like installed in our environment." }, { "code": null, "e": 5858, "s": 5786, "text": "# requirements.txt exampleapache-airflow[amazon]==1.10.12boto3==1.17.44" }, { "code": null, "e": 5978, "s": 5858, "text": "Upload your requirements file to your S3 bucket in the following location: s3://<your-bucket>/airflow/requirements.txt." }, { "code": null, "e": 6021, "s": 5978, "text": "Now we’re ready to create our environment!" }, { "code": null, "e": 6105, "s": 6021, "text": "Navigate to Managed Apache Airflow in the AWS console and click Create environment." }, { "code": null, "e": 6189, "s": 6105, "text": "Navigate to Managed Apache Airflow in the AWS console and click Create environment." }, { "code": null, "e": 6291, "s": 6189, "text": "2. Name your environment and select your Airflow version (I recommend you choose the latest version)." }, { "code": null, "e": 6374, "s": 6291, "text": "3. Add your S3 bucket, your DAGs path, and requirements.txt path, then click Next." }, { "code": null, "e": 6487, "s": 6374, "text": "4. Set the Web server access to Public network and check Create new security group. Next, click Create MWAA VPC." }, { "code": null, "e": 6565, "s": 6487, "text": "5. In the CloudFormation template, leave the defaults and click Create stack." }, { "code": null, "e": 6656, "s": 6565, "text": "6. You’ll need to wait a few minutes for your VPC to be created, then select your new VPC." }, { "code": null, "e": 6759, "s": 6656, "text": "7. Select your environment class. I recommend selecting mw1.small and scaling up from there if needed." }, { "code": null, "e": 6902, "s": 6759, "text": "8. Configure your Monitoring, Encryption, and Airflow configuration options— if you don’t know what to choose just leave the defaults for now." }, { "code": null, "e": 7054, "s": 6902, "text": "9. Unless you know what permissions you need, choose the option to Create a new role and AWS will create a role with the necessary permissions for you." }, { "code": null, "e": 7180, "s": 7054, "text": "10. Click Next, review your selections, and click Create environment! It will take 20–30 minutes to spin up your environment." }, { "code": null, "e": 7274, "s": 7180, "text": "Once your environment is ready, simply click Open Airflow UI and watch you’re up and running!" }, { "code": null, "e": 7523, "s": 7274, "text": "Now that you know how to set up an Airflow cluster, try your hand at creating more Airflow DAGs and testing them in your environment. In the near future I’ll be creating more Airflow tutorials, covering topics like running Spark jobs in Amazon EMR." }, { "code": null, "e": 7712, "s": 7523, "text": "Thank you for reading! Please let me know if you liked the article or if you have any critiques. If you found this guide useful, be sure to follow me, so you don’t miss my future articles." } ]
Maximum Size Subarray Sum Equals k in C++
Suppose we have an array called nums and a target value k, we have to find the maximum length of a subarray that sums to k. If there is not present any, return 0 instead. So, if the input is like nums = [1, -1, 5, -2, 3], k = 3, then the output will be 4, as the subarray [1, - 1, 5, -2] sums to 3 and is the longest. To solve this, we will follow these steps − ret := 0 ret := 0 Define one map m Define one map m n := size of nums n := size of nums temp := 0, m[0] := -1 temp := 0, m[0] := -1 for initialize i := 0, when i < n, update (increase i by 1), do −temp := temp + nums[i]if (temp - k) is in m, then −ret := maximum of ret and i - m[temp - k]if temp is not in m, then −m[temp] := i for initialize i := 0, when i < n, update (increase i by 1), do − temp := temp + nums[i] temp := temp + nums[i] if (temp - k) is in m, then −ret := maximum of ret and i - m[temp - k] if (temp - k) is in m, then − ret := maximum of ret and i - m[temp - k] ret := maximum of ret and i - m[temp - k] if temp is not in m, then −m[temp] := i if temp is not in m, then − m[temp] := i m[temp] := i return ret return ret Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int maxSubArrayLen(vector<int<& nums, int k) { int ret = 0; unordered_map <int, int> m; int n = nums.size(); int temp = 0; m[0] = -1; for(int i = 0; i < n; i++){ temp += nums[i]; if(m.count(temp - k)){ ret = max(ret, i - m[temp - k]); } if(!m.count(temp)){ m[temp] = i; } } return ret; } }; main(){ Solution ob; vector<int< v = {1,-1,5,-2,3}; cout << (ob.maxSubArrayLen(v, 3)); } [1,-1,5,-2,3], 3 4
[ { "code": null, "e": 1233, "s": 1062, "text": "Suppose we have an array called nums and a target value k, we have to find the maximum length of a subarray that sums to k. If there is not present any, return 0 instead." }, { "code": null, "e": 1380, "s": 1233, "text": "So, if the input is like nums = [1, -1, 5, -2, 3], k = 3, then the output will be 4, as the subarray [1, - 1, 5, -2] sums to 3 and is the longest." }, { "code": null, "e": 1424, "s": 1380, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1433, "s": 1424, "text": "ret := 0" }, { "code": null, "e": 1442, "s": 1433, "text": "ret := 0" }, { "code": null, "e": 1459, "s": 1442, "text": "Define one map m" }, { "code": null, "e": 1476, "s": 1459, "text": "Define one map m" }, { "code": null, "e": 1494, "s": 1476, "text": "n := size of nums" }, { "code": null, "e": 1512, "s": 1494, "text": "n := size of nums" }, { "code": null, "e": 1534, "s": 1512, "text": "temp := 0, m[0] := -1" }, { "code": null, "e": 1556, "s": 1534, "text": "temp := 0, m[0] := -1" }, { "code": null, "e": 1753, "s": 1556, "text": "for initialize i := 0, when i < n, update (increase i by 1), do −temp := temp + nums[i]if (temp - k) is in m, then −ret := maximum of ret and i - m[temp - k]if temp is not in m, then −m[temp] := i" }, { "code": null, "e": 1819, "s": 1753, "text": "for initialize i := 0, when i < n, update (increase i by 1), do −" }, { "code": null, "e": 1842, "s": 1819, "text": "temp := temp + nums[i]" }, { "code": null, "e": 1865, "s": 1842, "text": "temp := temp + nums[i]" }, { "code": null, "e": 1936, "s": 1865, "text": "if (temp - k) is in m, then −ret := maximum of ret and i - m[temp - k]" }, { "code": null, "e": 1966, "s": 1936, "text": "if (temp - k) is in m, then −" }, { "code": null, "e": 2008, "s": 1966, "text": "ret := maximum of ret and i - m[temp - k]" }, { "code": null, "e": 2050, "s": 2008, "text": "ret := maximum of ret and i - m[temp - k]" }, { "code": null, "e": 2090, "s": 2050, "text": "if temp is not in m, then −m[temp] := i" }, { "code": null, "e": 2118, "s": 2090, "text": "if temp is not in m, then −" }, { "code": null, "e": 2131, "s": 2118, "text": "m[temp] := i" }, { "code": null, "e": 2144, "s": 2131, "text": "m[temp] := i" }, { "code": null, "e": 2155, "s": 2144, "text": "return ret" }, { "code": null, "e": 2166, "s": 2155, "text": "return ret" }, { "code": null, "e": 2236, "s": 2166, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2247, "s": 2236, "text": " Live Demo" }, { "code": null, "e": 2830, "s": 2247, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n int maxSubArrayLen(vector<int<& nums, int k) {\n int ret = 0;\n unordered_map <int, int> m;\n int n = nums.size();\n int temp = 0;\n m[0] = -1;\n for(int i = 0; i < n; i++){\n temp += nums[i];\n if(m.count(temp - k)){\n ret = max(ret, i - m[temp - k]);\n }\n if(!m.count(temp)){\n m[temp] = i;\n }\n }\n return ret;\n }\n};\nmain(){\n Solution ob;\n vector<int< v = {1,-1,5,-2,3};\n cout << (ob.maxSubArrayLen(v, 3));\n}" }, { "code": null, "e": 2847, "s": 2830, "text": "[1,-1,5,-2,3], 3" }, { "code": null, "e": 2849, "s": 2847, "text": "4" } ]
Python - Convert key-value String to dictionary - GeeksforGeeks
10 May, 2020 Sometimes, while working with Python strings, we can have problem in which we need to convert a string key-value pairs to dictionary. This can have applications in which we are working with string data and needs to be converted. Let’s discuss certain ways in which this task can be performed. Method #1 : Using map() + split() + loopThe combination of above functionalities can be used to perform this task. In this, we perform the conversion of key-value pair to dictionary using map and splitting key-value pairs is done using split(). # Python3 code to demonstrate working of # Convert key-value String to dictionary# Using map() + split() + loop # initializing stringtest_str = 'gfg:1, is:2, best:3' # printing original stringprint("The original string is : " + str(test_str)) # Convert key-value String to dictionary# Using map() + split() + loopres = []for sub in test_str.split(', '): if ':' in sub: res.append(map(str.strip, sub.split(':', 1)))res = dict(res) # printing result print("The converted dictionary is : " + str(res)) The original string is : gfg:1, is:2, best:3 The converted dictionary is : {'gfg': '1', 'is': '2', 'best': '3'} Method #2 : Using dict() + generator expression + split() + map()This is yet another way in which this problem can be solved. In this, we perform the task in similar way as above but in 1 liner way using dict() and generator expression. # Python3 code to demonstrate working of # Convert key-value String to dictionary# Using dict() + generator expression + split() + map() # initializing stringtest_str = 'gfg:1, is:2, best:3' # printing original stringprint("The original string is : " + str(test_str)) # Convert key-value String to dictionary# Using dict() + generator expression + split() + map()res = dict(map(str.strip, sub.split(':', 1)) for sub in test_str.split(', ') if ':' in sub) # printing result print("The converted dictionary is : " + str(res)) The original string is : gfg:1, is:2, best:3 The converted dictionary is : {'gfg': '1', 'is': '2', 'best': '3'} Python string-programs Python Python Programs 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 Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25929, "s": 25901, "text": "\n10 May, 2020" }, { "code": null, "e": 26222, "s": 25929, "text": "Sometimes, while working with Python strings, we can have problem in which we need to convert a string key-value pairs to dictionary. This can have applications in which we are working with string data and needs to be converted. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 26467, "s": 26222, "text": "Method #1 : Using map() + split() + loopThe combination of above functionalities can be used to perform this task. In this, we perform the conversion of key-value pair to dictionary using map and splitting key-value pairs is done using split()." }, { "code": "# Python3 code to demonstrate working of # Convert key-value String to dictionary# Using map() + split() + loop # initializing stringtest_str = 'gfg:1, is:2, best:3' # printing original stringprint(\"The original string is : \" + str(test_str)) # Convert key-value String to dictionary# Using map() + split() + loopres = []for sub in test_str.split(', '): if ':' in sub: res.append(map(str.strip, sub.split(':', 1)))res = dict(res) # printing result print(\"The converted dictionary is : \" + str(res)) ", "e": 26981, "s": 26467, "text": null }, { "code": null, "e": 27094, "s": 26981, "text": "The original string is : gfg:1, is:2, best:3\nThe converted dictionary is : {'gfg': '1', 'is': '2', 'best': '3'}\n" }, { "code": null, "e": 27333, "s": 27096, "text": "Method #2 : Using dict() + generator expression + split() + map()This is yet another way in which this problem can be solved. In this, we perform the task in similar way as above but in 1 liner way using dict() and generator expression." }, { "code": "# Python3 code to demonstrate working of # Convert key-value String to dictionary# Using dict() + generator expression + split() + map() # initializing stringtest_str = 'gfg:1, is:2, best:3' # printing original stringprint(\"The original string is : \" + str(test_str)) # Convert key-value String to dictionary# Using dict() + generator expression + split() + map()res = dict(map(str.strip, sub.split(':', 1)) for sub in test_str.split(', ') if ':' in sub) # printing result print(\"The converted dictionary is : \" + str(res)) ", "e": 27862, "s": 27333, "text": null }, { "code": null, "e": 27975, "s": 27862, "text": "The original string is : gfg:1, is:2, best:3\nThe converted dictionary is : {'gfg': '1', 'is': '2', 'best': '3'}\n" }, { "code": null, "e": 27998, "s": 27975, "text": "Python string-programs" }, { "code": null, "e": 28005, "s": 27998, "text": "Python" }, { "code": null, "e": 28021, "s": 28005, "text": "Python Programs" }, { "code": null, "e": 28119, "s": 28021, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28137, "s": 28119, "text": "Python Dictionary" }, { "code": null, "e": 28172, "s": 28137, "text": "Read a file line by line in Python" }, { "code": null, "e": 28204, "s": 28172, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28226, "s": 28204, "text": "Enumerate() in Python" }, { "code": null, "e": 28268, "s": 28226, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28311, "s": 28268, "text": "Python program to convert a list to string" }, { "code": null, "e": 28333, "s": 28311, "text": "Defaultdict in Python" }, { "code": null, "e": 28372, "s": 28333, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28418, "s": 28372, "text": "Python | Split string into list of characters" } ]
Python program to Find the first non-repeating character from a stream of characters?
In this section we are going to find the first unique or non-repeating character from a string or stream of characters. There are multiple ways to solve this problem. We will try to create two different program for the same stream of characters. def firstNonRepeatingChar(str1): char_order = [] counts = {} for c in str1: if c in counts: counts[c] += 1 else: counts[c] = 1 char_order.append(c) for c in char_order: if counts[c] == 1: return c return None print(firstNonRepeatingChar('PythonforallPythonMustforall')) print(firstNonRepeatingChar('tutorialspointfordeveloper')) print(firstNonRepeatingChar('AABBCC')) M u None Above program give O(n) solution. In above program we first loop through the string once. Once we find a new character, we store it in counts object with a value of 1 and append it to char_order. When we come across a repeated character, we increment the value of counts by 1. Finally, we loop through char_order until we find a character with a value of 1 in char_order and return it. s = "tutorialspointfordeveloper" while s != "": slen0 = len(s) ch = s[0] s = s.replace(ch, "") slen1 = len(s) if slen1 == slen0-1: print ("First non-repeating character is: ",ch) break; else: print ("No Unique Character Found!") First non-repeating character is: u
[ { "code": null, "e": 1308, "s": 1062, "text": "In this section we are going to find the first unique or non-repeating character from a string or stream of characters. There are multiple ways to solve this problem. We will try to create two different program for the same stream of characters." }, { "code": null, "e": 1743, "s": 1308, "text": "def firstNonRepeatingChar(str1):\n char_order = []\n counts = {}\n for c in str1:\n if c in counts:\n counts[c] += 1\n else:\n counts[c] = 1\n char_order.append(c)\n for c in char_order:\n if counts[c] == 1:\n return c\n return None\n\nprint(firstNonRepeatingChar('PythonforallPythonMustforall'))\nprint(firstNonRepeatingChar('tutorialspointfordeveloper'))\nprint(firstNonRepeatingChar('AABBCC'))" }, { "code": null, "e": 1752, "s": 1743, "text": "M\nu\nNone" }, { "code": null, "e": 2138, "s": 1752, "text": "Above program give O(n) solution. In above program we first loop through the string once. Once we find a new character, we store it in counts object with a value of 1 and append it to char_order. When we come across a repeated character, we increment the value of counts by 1. Finally, we loop through char_order until we find a character with a value of 1 in char_order and return it." }, { "code": null, "e": 2400, "s": 2138, "text": "s = \"tutorialspointfordeveloper\"\nwhile s != \"\":\n slen0 = len(s)\n ch = s[0]\n s = s.replace(ch, \"\")\n slen1 = len(s)\n if slen1 == slen0-1:\n print (\"First non-repeating character is: \",ch)\n break;\n else:\n print (\"No Unique Character Found!\")" }, { "code": null, "e": 2436, "s": 2400, "text": "First non-repeating character is: u" } ]
PyQt5 QSpinBox - Removing the arrow buttons - GeeksforGeeks
06 May, 2020 In this article we will see how we can remove the buttons of the spin box, basically there are two buttons in the spin box one for incrementing the value and second for decrementing the value. Below is the representation of how normal spin box looks like vs the spin box with no buttons looks like In order to do this we will use setButtonSymbols method. Syntax :spin_box.setButtonSymbols(QAbstractSpinBox.NoButtons)orspin_box.setButtonSymbols(2) Argument : It takes either QAbstractSpinBox object or integer value Return : None Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 150, 40) # removing the buttons self.spin.setButtonSymbols(QAbstractSpinBox.NoButtons) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt-SpinBox 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 ? Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 25731, "s": 25703, "text": "\n06 May, 2020" }, { "code": null, "e": 26029, "s": 25731, "text": "In this article we will see how we can remove the buttons of the spin box, basically there are two buttons in the spin box one for incrementing the value and second for decrementing the value. Below is the representation of how normal spin box looks like vs the spin box with no buttons looks like" }, { "code": null, "e": 26086, "s": 26029, "text": "In order to do this we will use setButtonSymbols method." }, { "code": null, "e": 26178, "s": 26086, "text": "Syntax :spin_box.setButtonSymbols(QAbstractSpinBox.NoButtons)orspin_box.setButtonSymbols(2)" }, { "code": null, "e": 26246, "s": 26178, "text": "Argument : It takes either QAbstractSpinBox object or integer value" }, { "code": null, "e": 26260, "s": 26246, "text": "Return : None" }, { "code": null, "e": 26288, "s": 26260, "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 spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 150, 40) # removing the buttons self.spin.setButtonSymbols(QAbstractSpinBox.NoButtons) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 27206, "s": 26288, "text": null }, { "code": null, "e": 27215, "s": 27206, "text": "Output :" }, { "code": null, "e": 27235, "s": 27215, "text": "Python PyQt-SpinBox" }, { "code": null, "e": 27246, "s": 27235, "text": "Python-gui" }, { "code": null, "e": 27258, "s": 27246, "text": "Python-PyQt" }, { "code": null, "e": 27265, "s": 27258, "text": "Python" }, { "code": null, "e": 27363, "s": 27265, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27381, "s": 27363, "text": "Python Dictionary" }, { "code": null, "e": 27416, "s": 27381, "text": "Read a file line by line in Python" }, { "code": null, "e": 27448, "s": 27416, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27490, "s": 27448, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27516, "s": 27490, "text": "Python String | replace()" }, { "code": null, "e": 27560, "s": 27516, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27589, "s": 27560, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27626, "s": 27589, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27668, "s": 27626, "text": "Check if element exists in list in Python" } ]
Strictly Increasing Array | Practice | GeeksforGeeks
Given an array nums[] of N positive integers. Find the minimum number of operations required to modify the array such that array elements are in strictly increasing order (A[i] < A[i+1]). Changing a number to greater or lesser than original number is counted as one operation. Example 1: Input: nums[] = [1, 2, 3, 6, 5, 4] Output: 2 Explanation: By decreasing 6 by 2 and increasing 4 by 2, arr will be like [1, 2, 3, 4, 5, 6] which is stricly increasing. Example 2: Input: nums[] = [1, 2, 3, 4] Output: 0 Explanation: Arrays is already strictly increasing. Your Task: You don't need to read or print anything. Your task is to complete the function min_opeartions() which takes the array nums[] as input parameter and returns the minimum number of opeartion needed to make the array strictly increasing. Expected Time Complexity: O(n^2) Expected Space Complexity: O(n) Constraints: 1 <= length of array <= 1000 1 <= arr[i] <= 1000000 0 lindan1234 months ago int min_operations(vector<int>nums){ int n = nums.size(); int dp[n]; for(int i=0;i<n;i++) { dp[i] =1; } int ans=1; for(int i=1;i<n;i++) { for(int j=0;j<i;j++) { if(nums[i]>nums[j] && dp[i]<dp[j]+1 && (i-j)<=nums[i]-nums[j]) { dp[i] = max(dp[i],dp[j]+1); } } ans = max(ans,dp[i]); } return n-ans; } Time Taken : 0.0 Language : Cpp 0 shivambhadani1235 months ago int min_operations(vector<int>nums){ return nums.size()-lis(nums); } int lis(vector<int>& nums) { int n = nums.size(); int dp[n]; dp[0] = 1; for(int i=1; i<n; i++) { dp[i] = 1; for(int j=i-1; j>=0; j--) { if(nums[i]<=nums[j]) continue; if(i-j<=nums[i]-nums[j]) dp[i] = max(dp[i], 1+dp[j]); } } return *max_element(dp, dp+n); } 0 rohitpendse1386 months ago class Solution { int lis(vector<int> &nums, int n) { int dp[n]; dp[0] = 1; for (int i = 1; i < n; i++) { dp[i] = 1; for (int j = 0; j < i; j++) { if (nums[j] < nums[i] && dp[i] < 1 + dp[j] && (i - j) <= nums[i] - nums[j]) { dp[i] = 1 + dp[j]; } } } int ans = 1; for (int i = 0; i < n; i++) { ans = max(ans, dp[i]); } return ans; } public: int min_operations(vector<int> &nums) { // Code here int n = nums.size(); return n - lis(nums, n); } }; 0 rezashahriari9 months ago rezashahriari C++ using DP int min_operations(vector<int>nums){ int n = nums.size(); int LIS[n]; int res=0; if(n==1) return 0; for(int i = 0 ; i < n ;i++) LIS[i]=1; for(int i =0; i < n ;i++) for(int j = 0 ; j nums[j]&&(i-j)<=(nums[i]-nums[j])) LIS[i]=max(LIS[i],LIS[j]+1); res=max(res,LIS[i]); } return n-res; } 0 Debojyoti Sinha1 year ago Debojyoti Sinha Correct Answer.Correct AnswerExecution Time:0.02 class Solution{ public: int min_operations(vector<int> arr) { int N = arr.size(); vector<int> dp(N, 1); for(int i = 1; i < N; i++) { for(int j = 0; j < i; j++) { if(arr[j] < arr[i] and (i - j) <= arr[i] - arr[j]) { dp[i] = max(dp[i], dp[j] + 1); } } } return N - *max_element(dp.begin(), dp.end()); }}; -1 raghav1 year ago raghav USING BINARY INDEX TREE NLOG SOLUTION FOR NO DULICATES ALLOWED C++ :: NOTE - IT WILL NOT PASS TEST CASE HERE THOUGH void add( int t[] , int k , int x , int N ){ while( k<= N ) { t[k] += x ; k += k&-k; }}int sum( int t[] , int k ){ int s = 0 ; while( k >= 1 ) { s += t[k] ; k -= k&-k ; } return s ; }struct ti{ public: int a , b ; };bool c( ti c , ti d ){ if( c.a == d.a )return c.b < d.b ; return c.a < d.a ; }class Solution{public:int min_operations(vector<int>A ){ int N = A.size() ; if( N == 0 || N == 1 )return 0 ; vector< ti > V(N) ; for( int i = 0 ; i < N ; i++ ) { V[i].a = A[i] ; V[i].b = i; } sort( V.begin() , V.end() , c ); for( int i = 0 ; i < N ; i++ ) { auto x = V[i] ; int in = x.b ; A[in] = i+1 ; } int t[N+1]; memset(t , 0 , sizeof t ); int cnt = 0 ; for( int i = 0 ; i < N ; i++ ) { add( t , A[i] , 1 , N ); int s = sum( t , A[i] ); if( s == i + 1)continue; else { add( t , A[i] , -1 , N ); cnt++; add( t , i + 1 , 1 , N ); } } return cnt ; }}; GFG SOLUTION EASY BUT N^2 TIME COMPLEXITYclass Solution{public:int min_operations(vector<int>A ){ int N = A.size(); int t[N]; memset( t , 0 , sizeof t ); t[0] = 1 ; for( int i = 1 ; i < N ; i++ ) { t[i] = 1 ; for( int j = 0 ; j < i ; j++ ) { if( A[i] > A[j] && A[i] - A[j] >= i -j && t[i] < t[j] + 1 ) { t[i] = t[j] + 1 ; } } } return N-*max_element( t, t+N ) ; }}; -1 aditya anand2 years ago aditya anand class Solution{public:int min_operations(vector<int>arr){ int n=arr.size(); vector<int> table(n,1); for(int i=n-1;i>=0;i--){ for(int j=i+1;j<n;j++){ if(arr[j]="">arr[i] && (arr[j]-arr[i])>=(j-i) && (1+table[j])>table[i]) table[i]=1+table[j]; } } int m=-1; for(int i=0;i<n;i++) {="" if(table[i]="">m){ m=table[i]; } } return n-m; } +1 best2 years ago best Very similar to LIS. just keep in mind not take the case 1,2,3,4 because u cant insert elements in between here and if array length is one just return 0 +1 Dnyaneshwar Ware2 years ago Dnyaneshwar Ware n^2 works here and so why big constraints like 1e6 0 Malay Pandey2 years ago Malay Pandey How does this gives an output of 4.181 3 1 6 1 2 3 6 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": 503, "s": 226, "text": "Given an array nums[] of N positive integers. Find the minimum number of operations required to modify the array such that array elements are in strictly increasing order (A[i] < A[i+1]).\nChanging a number to greater or lesser than original number is counted as one operation." }, { "code": null, "e": 515, "s": 503, "text": "\nExample 1:" }, { "code": null, "e": 684, "s": 515, "text": "Input: nums[] = [1, 2, 3, 6, 5, 4]\nOutput: 2\nExplanation: By decreasing 6 by 2 and\nincreasing 4 by 2, arr will be like\n[1, 2, 3, 4, 5, 6] which is stricly \nincreasing.\n" }, { "code": null, "e": 696, "s": 684, "text": "\nExample 2:" }, { "code": null, "e": 788, "s": 696, "text": "Input: nums[] = [1, 2, 3, 4]\nOutput: 0\nExplanation: Arrays is already strictly\nincreasing.\n" }, { "code": null, "e": 1038, "s": 790, "text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function min_opeartions() which takes the array nums[] as input parameter and returns the minimum number of opeartion needed to make the array strictly increasing.\n " }, { "code": null, "e": 1105, "s": 1038, "text": "Expected Time Complexity: O(n^2)\nExpected Space Complexity: O(n)\n " }, { "code": null, "e": 1171, "s": 1105, "text": "Constraints: \n1 <= length of array <= 1000\n1 <= arr[i] <= 1000000" }, { "code": null, "e": 1173, "s": 1171, "text": "0" }, { "code": null, "e": 1195, "s": 1173, "text": "lindan1234 months ago" }, { "code": null, "e": 1679, "s": 1195, "text": "int min_operations(vector<int>nums){\n\t\t \n\t\t int n = nums.size();\n\t\t int dp[n];\n\t\t \n\t\t for(int i=0;i<n;i++)\n\t\t {\n\t\t dp[i] =1;\n\t\t }\n\t\t int ans=1;\n\t\t for(int i=1;i<n;i++)\n\t\t {\n\t\t for(int j=0;j<i;j++)\n\t\t {\n\t\t if(nums[i]>nums[j] && dp[i]<dp[j]+1 && (i-j)<=nums[i]-nums[j])\n\t\t {\n\t\t dp[i] = max(dp[i],dp[j]+1);\n\t\t }\n\t\t }\n\t\t ans = max(ans,dp[i]);\n\t\t }\n\t\t return n-ans;\n\t\t}" }, { "code": null, "e": 1696, "s": 1679, "text": "Time Taken : 0.0" }, { "code": null, "e": 1711, "s": 1696, "text": "Language : Cpp" }, { "code": null, "e": 1713, "s": 1711, "text": "0" }, { "code": null, "e": 1742, "s": 1713, "text": "shivambhadani1235 months ago" }, { "code": null, "e": 2255, "s": 1742, "text": "\t\tint min_operations(vector<int>nums){\n\t\t return nums.size()-lis(nums);\n\t\t}\n\t\tint lis(vector<int>& nums) {\n\t\t int n = nums.size();\n\t\t int dp[n];\n dp[0] = 1;\n for(int i=1; i<n; i++) {\n dp[i] = 1;\n for(int j=i-1; j>=0; j--) {\n if(nums[i]<=nums[j]) continue;\n if(i-j<=nums[i]-nums[j])\n dp[i] = max(dp[i], 1+dp[j]);\n }\n }\n return *max_element(dp, dp+n);\n\t\t}" }, { "code": null, "e": 2257, "s": 2255, "text": "0" }, { "code": null, "e": 2284, "s": 2257, "text": "rohitpendse1386 months ago" }, { "code": null, "e": 2974, "s": 2284, "text": "class Solution {\n int lis(vector<int> &nums, int n) {\n int dp[n];\n dp[0] = 1;\n for (int i = 1; i < n; i++) {\n dp[i] = 1;\n for (int j = 0; j < i; j++) {\n if (nums[j] < nums[i] \n && dp[i] < 1 + dp[j]\n && (i - j) <= nums[i] - nums[j]) {\n dp[i] = 1 + dp[j];\n }\n }\n }\n int ans = 1;\n for (int i = 0; i < n; i++) {\n ans = max(ans, dp[i]);\n }\n return ans;\n }\n\npublic:\n\n int min_operations(vector<int> &nums) {\n // Code here\n int n = nums.size();\n return n - lis(nums, n);\n }\n};" }, { "code": null, "e": 2976, "s": 2974, "text": "0" }, { "code": null, "e": 3002, "s": 2976, "text": "rezashahriari9 months ago" }, { "code": null, "e": 3016, "s": 3002, "text": "rezashahriari" }, { "code": null, "e": 3029, "s": 3016, "text": "C++ using DP" }, { "code": null, "e": 3382, "s": 3029, "text": "int min_operations(vector<int>nums){ int n = nums.size(); int LIS[n]; int res=0; if(n==1) return 0; for(int i = 0 ; i < n ;i++) LIS[i]=1; for(int i =0; i < n ;i++) for(int j = 0 ; j nums[j]&&(i-j)<=(nums[i]-nums[j])) LIS[i]=max(LIS[i],LIS[j]+1); res=max(res,LIS[i]); } return n-res; }" }, { "code": null, "e": 3384, "s": 3382, "text": "0" }, { "code": null, "e": 3410, "s": 3384, "text": "Debojyoti Sinha1 year ago" }, { "code": null, "e": 3426, "s": 3410, "text": "Debojyoti Sinha" }, { "code": null, "e": 3475, "s": 3426, "text": "Correct Answer.Correct AnswerExecution Time:0.02" }, { "code": null, "e": 3953, "s": 3475, "text": "class Solution{ public: int min_operations(vector<int> arr) { int N = arr.size(); vector<int> dp(N, 1); for(int i = 1; i < N; i++) { for(int j = 0; j < i; j++) { if(arr[j] < arr[i] and (i - j) <= arr[i] - arr[j]) { dp[i] = max(dp[i], dp[j] + 1); } } } return N - *max_element(dp.begin(), dp.end()); }};" }, { "code": null, "e": 3956, "s": 3953, "text": "-1" }, { "code": null, "e": 3973, "s": 3956, "text": "raghav1 year ago" }, { "code": null, "e": 3980, "s": 3973, "text": "raghav" }, { "code": null, "e": 5131, "s": 3980, "text": "USING BINARY INDEX TREE NLOG SOLUTION FOR NO DULICATES ALLOWED C++ :: NOTE - IT WILL NOT PASS TEST CASE HERE THOUGH void add( int t[] , int k , int x , int N ){ while( k<= N ) { t[k] += x ; k += k&-k; }}int sum( int t[] , int k ){ int s = 0 ; while( k >= 1 ) { s += t[k] ; k -= k&-k ; } return s ; }struct ti{ public: int a , b ; };bool c( ti c , ti d ){ if( c.a == d.a )return c.b < d.b ; return c.a < d.a ; }class Solution{public:int min_operations(vector<int>A ){ int N = A.size() ; if( N == 0 || N == 1 )return 0 ; vector< ti > V(N) ; for( int i = 0 ; i < N ; i++ ) { V[i].a = A[i] ; V[i].b = i; } sort( V.begin() , V.end() , c ); for( int i = 0 ; i < N ; i++ ) { auto x = V[i] ; int in = x.b ; A[in] = i+1 ; } int t[N+1]; memset(t , 0 , sizeof t ); int cnt = 0 ; for( int i = 0 ; i < N ; i++ ) { add( t , A[i] , 1 , N ); int s = sum( t , A[i] ); if( s == i + 1)continue; else { add( t , A[i] , -1 , N ); cnt++; add( t , i + 1 , 1 , N ); } } return cnt ; }};" }, { "code": null, "e": 5589, "s": 5131, "text": "GFG SOLUTION EASY BUT N^2 TIME COMPLEXITYclass Solution{public:int min_operations(vector<int>A ){ int N = A.size(); int t[N]; memset( t , 0 , sizeof t ); t[0] = 1 ; for( int i = 1 ; i < N ; i++ ) { t[i] = 1 ; for( int j = 0 ; j < i ; j++ ) { if( A[i] > A[j] && A[i] - A[j] >= i -j && t[i] < t[j] + 1 ) { t[i] = t[j] + 1 ; } } } return N-*max_element( t, t+N ) ; }};" }, { "code": null, "e": 5592, "s": 5589, "text": "-1" }, { "code": null, "e": 5616, "s": 5592, "text": "aditya anand2 years ago" }, { "code": null, "e": 5629, "s": 5616, "text": "aditya anand" }, { "code": null, "e": 6122, "s": 5629, "text": "class Solution{public:int min_operations(vector<int>arr){ int n=arr.size(); vector<int> table(n,1); for(int i=n-1;i>=0;i--){ for(int j=i+1;j<n;j++){ if(arr[j]=\"\">arr[i] && (arr[j]-arr[i])>=(j-i) && (1+table[j])>table[i]) table[i]=1+table[j]; } } int m=-1; for(int i=0;i<n;i++) {=\"\" if(table[i]=\"\">m){ m=table[i]; } } return n-m; }" }, { "code": null, "e": 6125, "s": 6122, "text": "+1" }, { "code": null, "e": 6141, "s": 6125, "text": "best2 years ago" }, { "code": null, "e": 6146, "s": 6141, "text": "best" }, { "code": null, "e": 6299, "s": 6146, "text": "Very similar to LIS. just keep in mind not take the case 1,2,3,4 because u cant insert elements in between here and if array length is one just return 0" }, { "code": null, "e": 6302, "s": 6299, "text": "+1" }, { "code": null, "e": 6330, "s": 6302, "text": "Dnyaneshwar Ware2 years ago" }, { "code": null, "e": 6347, "s": 6330, "text": "Dnyaneshwar Ware" }, { "code": null, "e": 6398, "s": 6347, "text": "n^2 works here and so why big constraints like 1e6" }, { "code": null, "e": 6400, "s": 6398, "text": "0" }, { "code": null, "e": 6424, "s": 6400, "text": "Malay Pandey2 years ago" }, { "code": null, "e": 6437, "s": 6424, "text": "Malay Pandey" }, { "code": null, "e": 6490, "s": 6437, "text": "How does this gives an output of 4.181 3 1 6 1 2 3 6" }, { "code": null, "e": 6636, "s": 6490, "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": 6672, "s": 6636, "text": " Login to access your submissions. " }, { "code": null, "e": 6682, "s": 6672, "text": "\nProblem\n" }, { "code": null, "e": 6692, "s": 6682, "text": "\nContest\n" }, { "code": null, "e": 6755, "s": 6692, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6903, "s": 6755, "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": 7111, "s": 6903, "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": 7217, "s": 7111, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Linear search using Multi-threading - GeeksforGeeks
28 Jan, 2018 Given a large file of integers, search for a particular element in it using multi-threading. Examples: Input : 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220 Output :if key = 20 Key element found Input :1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220 Output :if key = 202 Key not present Prerequisite : Multi-threading Approach :First create n threads. Then, divide array in to four parts one section for each thread and apply linear search on individual section using multhreading and check whether the key element is present or not. Command : g++ -pthread linear_thread.cpp C++ // CPP code to search for element in a// very large file using Multithreading#include <iostream>#include <pthread.h>using namespace std; // Max size of array#define max 16 // Max number of threads to create#define thread_max 4 int a[max] = { 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220 };int key = 202; // Flag to indicate if key is found in a[]// or not.int f = 0; int current_thread = 0; // Linear search function which will// run for all the threadsvoid* ThreadSearch(void* args){ int num = current_thread++; for (int i = num * (max / 4); i < ((num + 1) * (max / 4)); i++) { if (a[i] == key) f = 1; }} // Driver Codeint main(){ pthread_t thread[thread_max]; for (int i = 0; i < thread_max; i++) { pthread_create(&thread[i], NULL, ThreadSearch, (void*)NULL); } for (int i = 0; i < thread_max; i++) { pthread_join(thread[i], NULL); } if (f == 1) cout << "Key element found" << endl; else cout << "Key not present" << endl; return 0;} Key not present Exercise: The above code divides array into four subarrays. Extend this to take a parameter that decides number of divisions (or threads). cpp-multithreading C Language Searching Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ 'this' pointer in C++ Multithreading in C Arrow operator -> in C/C++ with Examples Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search Search an element in a sorted and rotated array Find the Missing Number
[ { "code": null, "e": 25666, "s": 25638, "text": "\n28 Jan, 2018" }, { "code": null, "e": 25759, "s": 25666, "text": "Given a large file of integers, search for a particular element in it using multi-threading." }, { "code": null, "e": 25769, "s": 25759, "text": "Examples:" }, { "code": null, "e": 26002, "s": 25769, "text": "Input : 1, 5, 7, 10, 12, 14, 15, 18, 20, \n 22, 25, 27, 30, 64, 110, 220\nOutput :if key = 20\nKey element found\n\nInput :1, 5, 7, 10, 12, 14, 15, 18, 20, \n 22, 25, 27, 30, 64, 110, 220\nOutput :if key = 202\nKey not present\n" }, { "code": null, "e": 26033, "s": 26002, "text": "Prerequisite : Multi-threading" }, { "code": null, "e": 26249, "s": 26033, "text": "Approach :First create n threads. Then, divide array in to four parts one section for each thread and apply linear search on individual section using multhreading and check whether the key element is present or not." }, { "code": null, "e": 26291, "s": 26249, "text": "Command : g++ -pthread linear_thread.cpp\n" }, { "code": null, "e": 26295, "s": 26291, "text": "C++" }, { "code": "// CPP code to search for element in a// very large file using Multithreading#include <iostream>#include <pthread.h>using namespace std; // Max size of array#define max 16 // Max number of threads to create#define thread_max 4 int a[max] = { 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220 };int key = 202; // Flag to indicate if key is found in a[]// or not.int f = 0; int current_thread = 0; // Linear search function which will// run for all the threadsvoid* ThreadSearch(void* args){ int num = current_thread++; for (int i = num * (max / 4); i < ((num + 1) * (max / 4)); i++) { if (a[i] == key) f = 1; }} // Driver Codeint main(){ pthread_t thread[thread_max]; for (int i = 0; i < thread_max; i++) { pthread_create(&thread[i], NULL, ThreadSearch, (void*)NULL); } for (int i = 0; i < thread_max; i++) { pthread_join(thread[i], NULL); } if (f == 1) cout << \"Key element found\" << endl; else cout << \"Key not present\" << endl; return 0;}", "e": 27405, "s": 26295, "text": null }, { "code": null, "e": 27422, "s": 27405, "text": "Key not present\n" }, { "code": null, "e": 27561, "s": 27422, "text": "Exercise: The above code divides array into four subarrays. Extend this to take a parameter that decides number of divisions (or threads)." }, { "code": null, "e": 27580, "s": 27561, "text": "cpp-multithreading" }, { "code": null, "e": 27591, "s": 27580, "text": "C Language" }, { "code": null, "e": 27601, "s": 27591, "text": "Searching" }, { "code": null, "e": 27611, "s": 27601, "text": "Searching" }, { "code": null, "e": 27709, "s": 27611, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27747, "s": 27709, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 27773, "s": 27747, "text": "Exception Handling in C++" }, { "code": null, "e": 27795, "s": 27773, "text": "'this' pointer in C++" }, { "code": null, "e": 27815, "s": 27795, "text": "Multithreading in C" }, { "code": null, "e": 27856, "s": 27815, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 27870, "s": 27856, "text": "Binary Search" }, { "code": null, "e": 27938, "s": 27870, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 27952, "s": 27938, "text": "Linear Search" }, { "code": null, "e": 28000, "s": 27952, "text": "Search an element in a sorted and rotated array" } ]
Analyzing Census Data in Python
Census is about recording information about a given population in a systematic manner. The data captured includes various category of information like – demographic, economic, habitation details etc. This ultimately helps the government in understanding the current scenario as well as Planning for the future. In this article we will see how to leverage python to analyze the census data for Indian population. We will look at various demographic and economic aspects. Then plot charge which will project the analysis in a graphical manner. The source that is collected from kaggle. It is located here. In the below program first we acquire the data using a short python program. It just loads the data to the pandas dataframe for further analysis. The output shows some of the fields for simpler representation. import pandas as pd datainput = pd.read_csv('E:\\india-districts-census-2011.csv') #https://www.kaggle.com/danofer/india-census#india-districts-census-2011.csv print(datainput) Running the above code gives us the following result − District code ... Total_Power_Parity 0 1 ... 1119 1 2 ... 1066 2 3 ... 242 3 4 ... 214 4 5 ... 629 .. ... ... ... 635 636 ... 10027 636 637 ... 4890 637 638 ... 3151 638 639 ... 3151 639 640 ... 5782 [640 rows x 118 columns] Now that we have gathered the data we can proceed to analyze the similarities on various fronts between two States. The similarities can be on the basis of age group, computer ownership, housing availability, education level etc. In the below example we take the two states named Assam and Andhra Pradesh. Then we compare the two states using the similarity_matrix. All the data fields are compared for each possible pair of districts from both the states. The resulting heatmap indicates how closely these two are related. The darker the shade the closer they are related. import pandas as pd import matplotlib.pyplot as plot from matplotlib.colors import Normalize import seaborn as sns import math datainput = pd.read_csv('E:\\india-districts-census-2011.csv') df_ASSAM = datainput.loc[datainput['State name'] == 'ASSAM'] df_ANDHRA_PRADESH = datainput.loc[datainput['State name'] == 'ANDHRA PRADESH'] def segment(x1, x2): # Set indices for both the data frames x1.set_index('District code') x2.set_index('District code') # The similarity matrix of size len(x1) X len(x2) similarity_matrix = [] # Iterate through rows of df1 for r1 in x1.iterrows(): # Create list to hold similarity score of row1 with other rows of x2 y = [] # Iterate through rows of x2 for r2 in x2.iterrows(): # Calculate sum of squared differences n = 0 for c in list(datainput)[3:]: maximum_c = max(datainput[c]) minimum_c = min(datainput[c]) n += pow((r1[1][c] - r2[1][c]) / (maximum_c - minimum_c), 2) # Take sqrt and inverse the result y.append(1 / math.sqrt(n)) # Append similarity scores similarity_matrix.append(y) p = 0 q = 0 r = 0 for m in range(len(similarity_matrix)): for n in range(len(similarity_matrix[m])): if (similarity_matrix[m][n] > p): p = similarity_matrix[m][n] q = m r = n print("%s from ASSAM and %s from ANDHRA PRADESH are most similar" % (x1['District name'].iloc[q],x2['District name'].iloc[r])) return similarity_matrix m = segment(df_ASSAM, df_ANDHRA_PRADESH) normalization=Normalize() s = plot.axes() sns.heatmap(normalization(m), xticklabels=df_ANDHRA_PRADESH['District name'],yticklabels=df_ASSAM['District name'],linewidths=0.05,cmap='Oranges').set_title("similar districts matrix of assam AND andhra_pradesh") plot.rcParams['figure.figsize'] = (20,20) plot.show() Running the above code gives us the following result − Now we can also compare places with respect to specific parameters. In the below example we compare the availability of household computers available for the cultivator workers. We produce graph which shows the comparison between these two parameters for each of the state. import pandas as pd import matplotlib.pyplot as plot from numpy import * datainput = pd.read_csv('E:\\india-districts-census-2011.csv') z = datainput.groupby(by="State name") m = [] w = [] for k, g in z: t = 0 t1 = 0 for r in g.iterrows(): t += r[1][36] t1 += r[1][21] m.append((k, t)) w.append((k, t1)) mp= pd.DataFrame({ 'state': [x[0] for x in m], 'Households_with_Computer': [x[1] for x in m], 'Cultivator_Workers': [x[1] for x in w]}) d = arange(35) wi = 0.3 fig, f = plot.subplots() plot.xlim(0, 22000000) r1 = f.barh(d, mp['Cultivator_Workers'], wi, color='g', align='center') r2 = f.barh(d + wi, mp['Households_with_Computer'], wi, color='b', align='center') f.set_xlabel('Population') f.set_title('COMPUTER PENETRATION IN VARIOUS STATES W.R.T. Cultivator_Workers') f.set_yticks(d + wi / 2) f.set_yticklabels((x for x in mp['state'])) f.legend((r1[0], r2[0]), ('Cultivator_Workers', 'Households_with_Computer')) plot.rcParams.update({'font.size': 15}) plot.rcParams['figure.figsize'] = (15, 15) plot.show() Running the above code gives us the following result −
[ { "code": null, "e": 1667, "s": 1062, "text": "Census is about recording information about a given population in a systematic manner. The data captured includes various category of information like – demographic, economic, habitation details etc. This ultimately helps the government in understanding the current scenario as well as Planning for the future. In this article we will see how to leverage python to analyze the census data for Indian population. We will look at various demographic and economic aspects. Then plot charge which will project the analysis in a graphical manner. The source that is collected from kaggle. It is located here." }, { "code": null, "e": 1877, "s": 1667, "text": "In the below program first we acquire the data using a short python program. It just loads the data to the pandas dataframe for further analysis. The output shows some of the fields for simpler representation." }, { "code": null, "e": 2054, "s": 1877, "text": "import pandas as pd\ndatainput = pd.read_csv('E:\\\\india-districts-census-2011.csv')\n#https://www.kaggle.com/danofer/india-census#india-districts-census-2011.csv\nprint(datainput)" }, { "code": null, "e": 2109, "s": 2054, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2651, "s": 2109, "text": " District code ... Total_Power_Parity\n0 1 ... 1119\n1 2 ... 1066\n2 3 ... 242\n3 4 ... 214\n4 5 ... 629\n.. ... ... ...\n635 636 ... 10027\n636 637 ... 4890\n637 638 ... 3151\n638 639 ... 3151\n639 640 ... 5782\n\n[640 rows x 118 columns]" }, { "code": null, "e": 3225, "s": 2651, "text": "Now that we have gathered the data we can proceed to analyze the similarities on various fronts between two States. The similarities can be on the basis of age group, computer ownership, housing availability, education level etc. In the below example we take the two states named Assam and Andhra Pradesh. Then we compare the two states using the similarity_matrix. All the data fields are compared for each possible pair of districts from both the states. The resulting heatmap indicates how closely these two are related. The darker the shade the closer they are related." }, { "code": null, "e": 5130, "s": 3225, "text": "import pandas as pd\nimport matplotlib.pyplot as plot\nfrom matplotlib.colors import Normalize\nimport seaborn as sns\nimport math\ndatainput = pd.read_csv('E:\\\\india-districts-census-2011.csv')\ndf_ASSAM = datainput.loc[datainput['State name'] == 'ASSAM']\ndf_ANDHRA_PRADESH = datainput.loc[datainput['State name'] == 'ANDHRA PRADESH']\ndef segment(x1, x2):\n # Set indices for both the data frames\n x1.set_index('District code')\n x2.set_index('District code')\n # The similarity matrix of size len(x1) X len(x2)\n similarity_matrix = []\n # Iterate through rows of df1\n for r1 in x1.iterrows():\n # Create list to hold similarity score of row1 with other rows of x2\n y = []\n # Iterate through rows of x2\n for r2 in x2.iterrows():\n # Calculate sum of squared differences\n n = 0\n for c in list(datainput)[3:]:\n maximum_c = max(datainput[c])\n minimum_c = min(datainput[c])\n n += pow((r1[1][c] - r2[1][c]) / (maximum_c - minimum_c), 2)\n # Take sqrt and inverse the result\n y.append(1 / math.sqrt(n))\n # Append similarity scores\n similarity_matrix.append(y)\n p = 0\n q = 0\n r = 0\n for m in range(len(similarity_matrix)):\n for n in range(len(similarity_matrix[m])):\n if (similarity_matrix[m][n] > p):\n p = similarity_matrix[m][n]\n q = m\n r = n\n print(\"%s from ASSAM and %s from ANDHRA PRADESH are most similar\" % (x1['District name'].iloc[q],x2['District name'].iloc[r]))\n return similarity_matrix\nm = segment(df_ASSAM, df_ANDHRA_PRADESH)\nnormalization=Normalize()\ns = plot.axes()\nsns.heatmap(normalization(m), xticklabels=df_ANDHRA_PRADESH['District name'],yticklabels=df_ASSAM['District name'],linewidths=0.05,cmap='Oranges').set_title(\"similar districts matrix of assam AND andhra_pradesh\")\nplot.rcParams['figure.figsize'] = (20,20)\nplot.show()" }, { "code": null, "e": 5185, "s": 5130, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 5459, "s": 5185, "text": "Now we can also compare places with respect to specific parameters. In the below example we compare the availability of household computers available for the cultivator workers. We produce graph which shows the comparison between these two parameters for each of the state." }, { "code": null, "e": 6512, "s": 5459, "text": "import pandas as pd\nimport matplotlib.pyplot as plot\nfrom numpy import *\n\ndatainput = pd.read_csv('E:\\\\india-districts-census-2011.csv')\nz = datainput.groupby(by=\"State name\")\nm = []\nw = []\nfor k, g in z:\n t = 0\n t1 = 0\n for r in g.iterrows():\n t += r[1][36]\n t1 += r[1][21]\n m.append((k, t))\n w.append((k, t1))\nmp= pd.DataFrame({\n 'state': [x[0] for x in m],\n 'Households_with_Computer': [x[1] for x in m],\n 'Cultivator_Workers': [x[1] for x in w]})\n\nd = arange(35)\nwi = 0.3\nfig, f = plot.subplots()\nplot.xlim(0, 22000000)\nr1 = f.barh(d, mp['Cultivator_Workers'], wi, color='g', align='center')\nr2 = f.barh(d + wi, mp['Households_with_Computer'], wi, color='b', align='center')\nf.set_xlabel('Population')\nf.set_title('COMPUTER PENETRATION IN VARIOUS STATES W.R.T. Cultivator_Workers')\nf.set_yticks(d + wi / 2)\nf.set_yticklabels((x for x in mp['state']))\nf.legend((r1[0], r2[0]), ('Cultivator_Workers', 'Households_with_Computer'))\nplot.rcParams.update({'font.size': 15})\nplot.rcParams['figure.figsize'] = (15, 15)\nplot.show()" }, { "code": null, "e": 6567, "s": 6512, "text": "Running the above code gives us the following result −" } ]
Load CSV data into List and Dictionary using Python - GeeksforGeeks
21 Apr, 2020 Prerequisites: Working with csv files in Python CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format. CSV raw data is not utilizable in order to use that in our Python program it can be more beneficial if we could read and separate commas and store them in a data structure. We can convert data into lists or dictionaries or a combination of both either by using functions csv.reader and csv.dictreader or manually directlyand in this article, we will see it with the help of code. Example 1: Loading CSV to list CSV File: # importing module import csv # csv fileused id Geeks.csvfilename="Geeks.csv" # opening the file using "with"# statementwith open(filename,'r') as data: for line in csv.reader(data): print(line) # then data is read line by line # using csv.reader the printed # result will be in a list format # which is easy to interpret Output: Example 2: Loading CSV to dictionary import csv filename ="Geeks.csv" # opening the file using "with" # statementwith open(filename, 'r') as data: for line in csv.DictReader(data): print(line) Output: python-csv Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Python Dictionary Bar Plot in Matplotlib Enumerate() in Python Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Graph Plotting in Python | Set 1 Python - Call function from another file loops in python
[ { "code": null, "e": 24423, "s": 24395, "text": "\n21 Apr, 2020" }, { "code": null, "e": 24471, "s": 24423, "text": "Prerequisites: Working with csv files in Python" }, { "code": null, "e": 24845, "s": 24471, "text": "CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format." }, { "code": null, "e": 25225, "s": 24845, "text": "CSV raw data is not utilizable in order to use that in our Python program it can be more beneficial if we could read and separate commas and store them in a data structure. We can convert data into lists or dictionaries or a combination of both either by using functions csv.reader and csv.dictreader or manually directlyand in this article, we will see it with the help of code." }, { "code": null, "e": 25256, "s": 25225, "text": "Example 1: Loading CSV to list" }, { "code": null, "e": 25266, "s": 25256, "text": "CSV File:" }, { "code": "# importing module import csv # csv fileused id Geeks.csvfilename=\"Geeks.csv\" # opening the file using \"with\"# statementwith open(filename,'r') as data: for line in csv.reader(data): print(line) # then data is read line by line # using csv.reader the printed # result will be in a list format # which is easy to interpret", "e": 25613, "s": 25266, "text": null }, { "code": null, "e": 25621, "s": 25613, "text": "Output:" }, { "code": null, "e": 25658, "s": 25621, "text": "Example 2: Loading CSV to dictionary" }, { "code": "import csv filename =\"Geeks.csv\" # opening the file using \"with\" # statementwith open(filename, 'r') as data: for line in csv.DictReader(data): print(line)", "e": 25834, "s": 25658, "text": null }, { "code": null, "e": 25842, "s": 25834, "text": "Output:" }, { "code": null, "e": 25853, "s": 25842, "text": "python-csv" }, { "code": null, "e": 25860, "s": 25853, "text": "Python" }, { "code": null, "e": 25958, "s": 25860, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25967, "s": 25958, "text": "Comments" }, { "code": null, "e": 25980, "s": 25967, "text": "Old Comments" }, { "code": null, "e": 26016, "s": 25980, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 26034, "s": 26016, "text": "Python Dictionary" }, { "code": null, "e": 26057, "s": 26034, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 26079, "s": 26057, "text": "Enumerate() in Python" }, { "code": null, "e": 26118, "s": 26079, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26151, "s": 26118, "text": "Python | Convert set into a list" }, { "code": null, "e": 26200, "s": 26151, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 26233, "s": 26200, "text": "Graph Plotting in Python | Set 1" }, { "code": null, "e": 26274, "s": 26233, "text": "Python - Call function from another file" } ]
ES6 - Array Method map()
map() method creates a new array with the results of calling a provided function on every element in this array. array.map(callback[, thisObject]); callback − Function that produces an element of the new Array from an element of the current one. callback − Function that produces an element of the new Array from an element of the current one. thisObject − Object to use as this when executing callback. thisObject − Object to use as this when executing callback. Returns the created array. var numbers = [1, 4, 9]; var roots = numbers.map(Math.sqrt); console.log("roots is : " + roots ); roots is : 1,2,3 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": 2390, "s": 2277, "text": "map() method creates a new array with the results of calling a provided function on every element in this array." }, { "code": null, "e": 2429, "s": 2390, "text": "array.map(callback[, thisObject]); \n" }, { "code": null, "e": 2527, "s": 2429, "text": "callback − Function that produces an element of the new Array from an element of the current one." }, { "code": null, "e": 2625, "s": 2527, "text": "callback − Function that produces an element of the new Array from an element of the current one." }, { "code": null, "e": 2685, "s": 2625, "text": "thisObject − Object to use as this when executing callback." }, { "code": null, "e": 2745, "s": 2685, "text": "thisObject − Object to use as this when executing callback." }, { "code": null, "e": 2772, "s": 2745, "text": "Returns the created array." }, { "code": null, "e": 2876, "s": 2772, "text": "var numbers = [1, 4, 9]; \nvar roots = numbers.map(Math.sqrt); \nconsole.log(\"roots is : \" + roots ); " }, { "code": null, "e": 2895, "s": 2876, "text": "roots is : 1,2,3 \n" }, { "code": null, "e": 2930, "s": 2895, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2944, "s": 2930, "text": " Sharad Kumar" }, { "code": null, "e": 2977, "s": 2944, "text": "\n 40 Lectures \n 5 hours \n" }, { "code": null, "e": 2995, "s": 2977, "text": " Richa Maheshwari" }, { "code": null, "e": 3028, "s": 2995, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 3042, "s": 3028, "text": " Anadi Sharma" }, { "code": null, "e": 3077, "s": 3042, "text": "\n 50 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3094, "s": 3077, "text": " Gowthami Swarna" }, { "code": null, "e": 3127, "s": 3094, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 3143, "s": 3127, "text": " Deepti Trivedi" }, { "code": null, "e": 3178, "s": 3143, "text": "\n 31 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3186, "s": 3178, "text": " Shweta" }, { "code": null, "e": 3193, "s": 3186, "text": " Print" }, { "code": null, "e": 3204, "s": 3193, "text": " Add Notes" } ]
Factorial of each element in Fibonacci series - GeeksforGeeks
18 Jan, 2022 Given the upper limit, print factorials of all Fibonacci Numbers smaller than the limit.Examples : Input : limit = 20 Output : 1 1 1 2 6 120 40320 6227020800 Explanation : Fibonacci series in this range is 0, 1, 1, 2, 3, 5, 8, 13. Factorials of these numbers are output. Input : 50 Output : 1 1 1 2 6 120 40320 6227020800 51090942171709440000 295232799039604140847618609643520000000 We know simple factorial computations cause overflow very soon. Therefore, we use factorials of large numbers. One simple solution is to generate all Fibonacci numbers one by one and compute factorial of every generated number using method discussed in factorials of large numbersAn efficient solution is based on the fact that Fibonacci numbers are increasing in order. So we use the previously generated factorial to compute next factorial. C++ Java Python3 C# PHP Javascript // CPP program to find factorial of each element// of Fibonacci series#include <iostream>using namespace std; // Maximum number of digits in output#define MAX 500 // Finds and print factorial of n using// factorial of prev (stored in prevFact[// 0...size-1]void factorial(int prevFact[], int &size, int prev, int n); // Prints factorials of all fibonacci// numbers smaller than given limit.void printfibFactorials(int limit){ if (limit < 1) return; // Initialize first three Fibonacci // numbers and print factorials of // first two numbers. int a = 1, b = 1, c = 2; cout << a << " " << b << " "; // prevFact[] stores factorial of // previous fibonacci number int prevFact[MAX]; prevFact[0] = 1; // Size is current size of prevFact[] int size = 1; // Standard Fibonacci number loop while (c < limit) { factorial(prevFact, size, b, c); a = b; b = c; c = a + b; }} // Please refer below article for details of// below two functions.// https://www.geeksforgeeks.org/factorial-large-number/ // Function used to find factorialint multiply(int x, int prevFact[], int size){ int carry = 0; for (int i = 0; i < size; i++) { int prod = prevFact[i] * x + carry; prevFact[i] = prod % 10; carry = prod / 10; } // Put carry in res and increase // result size while (carry) { prevFact[size] = carry % 10; carry = carry / 10; size++; } return size;} // Finds factorial of n using factorial// "prev" stored in prevFact[]. size is// size of prevFact[]void factorial(int prevFact[], int &size, int prev, int n){ for (int x = prev+1; x <= n; x++) size = multiply(x, prevFact, size); for (int i = size - 1; i >= 0; i--) cout << prevFact[i]; cout << " ";} // Driver functionint main(){ int limit = 20; printfibFactorials(limit); return 0;} // Java program to find// factorial of each element// of Fibonacci seriesimport java.io.*; class GFG{ // Maximum number of // digits in output static int MAX = 500; static int size = 1; // Finds and print factorial // of n using factorial of // prev (stored in prevFact[ // 0...size-1] // Finds factorial of n // using factorial "prev" // stored in prevFact[]. size // is size of prevFact[] static void factorial(int []prevFact, int prev, int n) { for (int x = prev + 1; x <= n; x++) size = multiply(x, prevFact, size); for (int i = size - 1; i >= 0; i--) System.out.print(prevFact[i]); System.out.print(" "); } // Prints factorials of all // fibonacci numbers smaller // than given limit. static void printfibFactorials(int limit) { if (limit < 1) return; // Initialize first three // Fibonacci numbers and // print factorials of // first two numbers. int a = 1, b = 1, c = 2; System.out.print(a + " " + b + " "); // prevFact[] stores factorial // of previous fibonacci number int []prevFact = new int[MAX]; prevFact[0] = 1; // Standard Fibonacci // number loop while (c < limit) { factorial(prevFact, b, c); a = b; b = c; c = a + b; } } // Please refer below // article for details of // below two functions. // https://www.geeksforgeeks.org/factorial-large-number/ // Function used to // find factorial static int multiply(int x, int []prevFact, int size) { int carry = 0; for (int i = 0; i < size; i++) { int prod = prevFact[i] * x + carry; prevFact[i] = prod % 10; carry = prod / 10; } // Put carry in // res and increase // result size while (carry != 0) { prevFact[size] = carry % 10; carry = carry / 10; size++; } return size; } // Driver Code public static void main(String args[]) { int limit = 20; printfibFactorials(limit); }} // This code is contributed by// Manish Shaw(manishshaw1) # Python3 program to find# factorial of each element# of Fibonacci series # Maximum number of# digits in outputMAX = 500size = 1 # Finds and print factorial# of n using factorial of# prev (stored in prevFact[# 0...size-1]# Finds factorial of n# using factorial "prev"# stored in prevFact[]. size# is size of prevFact[]def factorial(prevFact, prev,n) : global size for x in range((prev + 1), n + 1) : size = multiply(x, prevFact, size) for i in range((size - 1), -1, -1) : print(prevFact[i], end = "") print(end = " ") # Prints factorials of all# fibonacci numbers smaller# than given limit.def printfibFactorials(limit) : if (limit < 1) : return # Initialize first three # Fibonacci numbers and # print factorials of # first two numbers. a = 1 b = 1 c = 2 print(a,b , end = " ") # prevFact[] stores factorial # of previous fibonacci number prevFact = [0] * MAX prevFact[0] = 1 # Standard Fibonacci # number loop while (c < limit) : factorial(prevFact, b, c) a = b b = c c = a + b # Please refer below# article for details of# below two functions.# https://www.geeksforgeeks.org/factorial-large-number/ # Function used to# find factorialdef multiply(x,prevFact,size) : carry = 0 for i in range(0, size) : prod = prevFact[i] *x + carry prevFact[i] = prod % 10 carry = prod // 10 # Put carry in # res and increase # result size while (carry != 0) : prevFact[size] = carry % 10 carry = carry // 10 size = size + 1 return size # Driver Codelimit = 20printfibFactorials(limit) # This code is contributed by Nikita Tiwari. // C# program to find// factorial of each element// of Fibonacci seriesusing System; class GFG{ // Maximum number of // digits in output static int MAX = 500; // Finds and print factorial // of n using factorial of // prev (stored in prevFact[ // 0...size-1] // Finds factorial of n // using factorial "prev" // stored in prevFact[]. size // is size of prevFact[] static void factorial(int []prevFact, ref int size, int prev, int n) { for (int x = prev + 1; x <= n; x++) size = multiply(x, prevFact, size); for (int i = size - 1; i >= 0; i--) Console.Write(prevFact[i]); Console.Write(" "); } // Prints factorials of all fibonacci // numbers smaller than given limit. static void printfibFactorials(int limit) { if (limit < 1) return; // Initialize first three Fibonacci // numbers and print factorials of // first two numbers. int a = 1, b = 1, c = 2; Console.Write(a + " " + b + " "); // prevFact[] stores factorial of // previous fibonacci number int []prevFact = new int[MAX]; prevFact[0] = 1; // Size is current size // of prevFact[] int size = 1; // Standard Fibonacci // number loop while (c < limit) { factorial(prevFact, ref size, b, c); a = b; b = c; c = a + b; } } // Please refer below // article for details of // below two functions. // https://www.geeksforgeeks.org/factorial-large-number/ // Function used to find factorial static int multiply(int x, int []prevFact, int size) { int carry = 0; for (int i = 0; i < size; i++) { int prod = prevFact[i] * x + carry; prevFact[i] = prod % 10; carry = prod / 10; } // Put carry in // res and increase // result size while (carry != 0) { prevFact[size] = carry % 10; carry = carry / 10; size++; } return size; } // Driver Code static void Main() { int limit = 20; printfibFactorials(limit); }} // This code is contributed by// Manish Shaw(manishshaw1) <?php// PHP program to find// factorial of each element// of Fibonacci series // Maximum number of// digits in output$MAX = 500;$size = 1;$prevFact = $prevFact = array_fill(0, $MAX, 0); // Finds and print factorial// of n using factorial of// prev (stored in prevFact[// 0...size-1]// Finds factorial of n// using factorial "prev"// stored in prevFact[]. size// is size of prevFact[]function factorial($prev, $n) { global $size, $prevFact; for ($x = $prev + 1; $x <= $n; $x++) $size = multiply($x, $size); for ($i = $size - 1; $i >= 0; $i--) echo $prevFact[$i]; echo " "; } // Prints factorials of all// fibonacci numbers smaller// than given limit.function printfibFactorials($limit) { global $MAX, $prevFact; if ($limit < 1) return; // Initialize first three // Fibonacci numbers and // print factorials of // first two numbers. $a = 1; $b = 1; $c = 2; echo $a . " " . $b . " "; // prevFact[] stores factorial // of previous fibonacci number $prevFact[0] = 1; // Standard Fibonacci // number loop while ($c < $limit) { factorial($b, $c); $a = $b; $b = $c; $c = $a + $b; } } // Function used to// find factorialfunction multiply($x,$size) { global $prevFact; $carry = 0; for ($i = 0; $i < $size; $i++) { $prod = $prevFact[$i] * $x + $carry; $prevFact[$i] = $prod % 10; $carry = (int)($prod / 10); } // Put carry in // res and increase // result size while ($carry != 0) { $prevFact[$size] = $carry % 10; $carry = (int)($carry / 10); $size++; } return $size; } // Driver Code$limit = 20;printfibFactorials($limit); // This code is contributed// by mits?> <script> // Javascript program to find// factorial of each element// of Fibonacci series // Maximum number of // digits in output var MAX = 500; var size = 1; // Finds and print factorial // of n using factorial of // prev (stored in prevFact[ // 0...size-1] // Finds factorial of n // using factorial "prev" // stored in prevFact. size // is size of prevFact function factorial(prevFact , prev , n) { for (x = prev + 1; x <= n; x++) size = multiply(x, prevFact, size); for (i = size - 1; i >= 0; i--) document.write(prevFact[i]); document.write(" "); } // Prints factorials of all // fibonacci numbers smaller // than given limit. function printfibFactorials(limit) { if (limit < 1) return; // Initialize first three // Fibonacci numbers and // print factorials of // first two numbers. var a = 1, b = 1, c = 2; document.write(a + " " + b + " "); // prevFact stores factorial // of previous fibonacci number var prevFact = Array(MAX).fill(0); prevFact[0] = 1; // Standard Fibonacci // number loop while (c < limit) { factorial(prevFact, b, c); a = b; b = c; c = a + b; } } // Please refer below // article for details of // below two functions. // https://www.geeksforgeeks.org/factorial-large-number/ // Function used to // find factorial function multiply(x, prevFact , size) { var carry = 0; for (i = 0; i < size; i++) { var prod = prevFact[i] * x + carry; prevFact[i] = prod % 10; carry = parseInt(prod / 10); } // Put carry in // res and increase // result size while (carry != 0) { prevFact[size] = carry % 10; carry = parseInt(carry / 10); size++; } return size; } // Driver Code var limit = 20; printfibFactorials(limit); // This code is contributed by todaysgaurav </script> Output : 1 1 2 6 120 40320 6227020800 manishshaw1 Mithun Kumar Nikita tiwari todaysgaurav simranarora5sos factorial Fibonacci series Mathematical Mathematical series Fibonacci factorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Find all factors of a natural number | Set 1 Check if a number is Palindrome Program to print prime numbers from 1 to N. Program to add two binary strings Program to multiply two matrices Fizz Buzz Implementation Find pair with maximum GCD in an array Find Union and Intersection of two unsorted arrays Count all possible paths from top left to bottom right of a mXn matrix Count ways to reach the n'th stair
[ { "code": null, "e": 24325, "s": 24297, "text": "\n18 Jan, 2022" }, { "code": null, "e": 24426, "s": 24325, "text": "Given the upper limit, print factorials of all Fibonacci Numbers smaller than the limit.Examples : " }, { "code": null, "e": 24733, "s": 24426, "text": "Input : limit = 20\nOutput : 1 1 1 2 6 120 40320 6227020800\nExplanation : \nFibonacci series in this range is 0, 1, 1, 2, \n3, 5, 8, 13. Factorials of these numbers are \noutput.\n\nInput : 50\nOutput : 1 1 1 2 6 120 40320 6227020800\n 51090942171709440000 \n 295232799039604140847618609643520000000" }, { "code": null, "e": 25179, "s": 24735, "text": "We know simple factorial computations cause overflow very soon. Therefore, we use factorials of large numbers. One simple solution is to generate all Fibonacci numbers one by one and compute factorial of every generated number using method discussed in factorials of large numbersAn efficient solution is based on the fact that Fibonacci numbers are increasing in order. So we use the previously generated factorial to compute next factorial. " }, { "code": null, "e": 25183, "s": 25179, "text": "C++" }, { "code": null, "e": 25188, "s": 25183, "text": "Java" }, { "code": null, "e": 25196, "s": 25188, "text": "Python3" }, { "code": null, "e": 25199, "s": 25196, "text": "C#" }, { "code": null, "e": 25203, "s": 25199, "text": "PHP" }, { "code": null, "e": 25214, "s": 25203, "text": "Javascript" }, { "code": "// CPP program to find factorial of each element// of Fibonacci series#include <iostream>using namespace std; // Maximum number of digits in output#define MAX 500 // Finds and print factorial of n using// factorial of prev (stored in prevFact[// 0...size-1]void factorial(int prevFact[], int &size, int prev, int n); // Prints factorials of all fibonacci// numbers smaller than given limit.void printfibFactorials(int limit){ if (limit < 1) return; // Initialize first three Fibonacci // numbers and print factorials of // first two numbers. int a = 1, b = 1, c = 2; cout << a << \" \" << b << \" \"; // prevFact[] stores factorial of // previous fibonacci number int prevFact[MAX]; prevFact[0] = 1; // Size is current size of prevFact[] int size = 1; // Standard Fibonacci number loop while (c < limit) { factorial(prevFact, size, b, c); a = b; b = c; c = a + b; }} // Please refer below article for details of// below two functions.// https://www.geeksforgeeks.org/factorial-large-number/ // Function used to find factorialint multiply(int x, int prevFact[], int size){ int carry = 0; for (int i = 0; i < size; i++) { int prod = prevFact[i] * x + carry; prevFact[i] = prod % 10; carry = prod / 10; } // Put carry in res and increase // result size while (carry) { prevFact[size] = carry % 10; carry = carry / 10; size++; } return size;} // Finds factorial of n using factorial// \"prev\" stored in prevFact[]. size is// size of prevFact[]void factorial(int prevFact[], int &size, int prev, int n){ for (int x = prev+1; x <= n; x++) size = multiply(x, prevFact, size); for (int i = size - 1; i >= 0; i--) cout << prevFact[i]; cout << \" \";} // Driver functionint main(){ int limit = 20; printfibFactorials(limit); return 0;}", "e": 27144, "s": 25214, "text": null }, { "code": "// Java program to find// factorial of each element// of Fibonacci seriesimport java.io.*; class GFG{ // Maximum number of // digits in output static int MAX = 500; static int size = 1; // Finds and print factorial // of n using factorial of // prev (stored in prevFact[ // 0...size-1] // Finds factorial of n // using factorial \"prev\" // stored in prevFact[]. size // is size of prevFact[] static void factorial(int []prevFact, int prev, int n) { for (int x = prev + 1; x <= n; x++) size = multiply(x, prevFact, size); for (int i = size - 1; i >= 0; i--) System.out.print(prevFact[i]); System.out.print(\" \"); } // Prints factorials of all // fibonacci numbers smaller // than given limit. static void printfibFactorials(int limit) { if (limit < 1) return; // Initialize first three // Fibonacci numbers and // print factorials of // first two numbers. int a = 1, b = 1, c = 2; System.out.print(a + \" \" + b + \" \"); // prevFact[] stores factorial // of previous fibonacci number int []prevFact = new int[MAX]; prevFact[0] = 1; // Standard Fibonacci // number loop while (c < limit) { factorial(prevFact, b, c); a = b; b = c; c = a + b; } } // Please refer below // article for details of // below two functions. // https://www.geeksforgeeks.org/factorial-large-number/ // Function used to // find factorial static int multiply(int x, int []prevFact, int size) { int carry = 0; for (int i = 0; i < size; i++) { int prod = prevFact[i] * x + carry; prevFact[i] = prod % 10; carry = prod / 10; } // Put carry in // res and increase // result size while (carry != 0) { prevFact[size] = carry % 10; carry = carry / 10; size++; } return size; } // Driver Code public static void main(String args[]) { int limit = 20; printfibFactorials(limit); }} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 29610, "s": 27144, "text": null }, { "code": "# Python3 program to find# factorial of each element# of Fibonacci series # Maximum number of# digits in outputMAX = 500size = 1 # Finds and print factorial# of n using factorial of# prev (stored in prevFact[# 0...size-1]# Finds factorial of n# using factorial \"prev\"# stored in prevFact[]. size# is size of prevFact[]def factorial(prevFact, prev,n) : global size for x in range((prev + 1), n + 1) : size = multiply(x, prevFact, size) for i in range((size - 1), -1, -1) : print(prevFact[i], end = \"\") print(end = \" \") # Prints factorials of all# fibonacci numbers smaller# than given limit.def printfibFactorials(limit) : if (limit < 1) : return # Initialize first three # Fibonacci numbers and # print factorials of # first two numbers. a = 1 b = 1 c = 2 print(a,b , end = \" \") # prevFact[] stores factorial # of previous fibonacci number prevFact = [0] * MAX prevFact[0] = 1 # Standard Fibonacci # number loop while (c < limit) : factorial(prevFact, b, c) a = b b = c c = a + b # Please refer below# article for details of# below two functions.# https://www.geeksforgeeks.org/factorial-large-number/ # Function used to# find factorialdef multiply(x,prevFact,size) : carry = 0 for i in range(0, size) : prod = prevFact[i] *x + carry prevFact[i] = prod % 10 carry = prod // 10 # Put carry in # res and increase # result size while (carry != 0) : prevFact[size] = carry % 10 carry = carry // 10 size = size + 1 return size # Driver Codelimit = 20printfibFactorials(limit) # This code is contributed by Nikita Tiwari.", "e": 31350, "s": 29610, "text": null }, { "code": "// C# program to find// factorial of each element// of Fibonacci seriesusing System; class GFG{ // Maximum number of // digits in output static int MAX = 500; // Finds and print factorial // of n using factorial of // prev (stored in prevFact[ // 0...size-1] // Finds factorial of n // using factorial \"prev\" // stored in prevFact[]. size // is size of prevFact[] static void factorial(int []prevFact, ref int size, int prev, int n) { for (int x = prev + 1; x <= n; x++) size = multiply(x, prevFact, size); for (int i = size - 1; i >= 0; i--) Console.Write(prevFact[i]); Console.Write(\" \"); } // Prints factorials of all fibonacci // numbers smaller than given limit. static void printfibFactorials(int limit) { if (limit < 1) return; // Initialize first three Fibonacci // numbers and print factorials of // first two numbers. int a = 1, b = 1, c = 2; Console.Write(a + \" \" + b + \" \"); // prevFact[] stores factorial of // previous fibonacci number int []prevFact = new int[MAX]; prevFact[0] = 1; // Size is current size // of prevFact[] int size = 1; // Standard Fibonacci // number loop while (c < limit) { factorial(prevFact, ref size, b, c); a = b; b = c; c = a + b; } } // Please refer below // article for details of // below two functions. // https://www.geeksforgeeks.org/factorial-large-number/ // Function used to find factorial static int multiply(int x, int []prevFact, int size) { int carry = 0; for (int i = 0; i < size; i++) { int prod = prevFact[i] * x + carry; prevFact[i] = prod % 10; carry = prod / 10; } // Put carry in // res and increase // result size while (carry != 0) { prevFact[size] = carry % 10; carry = carry / 10; size++; } return size; } // Driver Code static void Main() { int limit = 20; printfibFactorials(limit); }} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 33692, "s": 31350, "text": null }, { "code": "<?php// PHP program to find// factorial of each element// of Fibonacci series // Maximum number of// digits in output$MAX = 500;$size = 1;$prevFact = $prevFact = array_fill(0, $MAX, 0); // Finds and print factorial// of n using factorial of// prev (stored in prevFact[// 0...size-1]// Finds factorial of n// using factorial \"prev\"// stored in prevFact[]. size// is size of prevFact[]function factorial($prev, $n) { global $size, $prevFact; for ($x = $prev + 1; $x <= $n; $x++) $size = multiply($x, $size); for ($i = $size - 1; $i >= 0; $i--) echo $prevFact[$i]; echo \" \"; } // Prints factorials of all// fibonacci numbers smaller// than given limit.function printfibFactorials($limit) { global $MAX, $prevFact; if ($limit < 1) return; // Initialize first three // Fibonacci numbers and // print factorials of // first two numbers. $a = 1; $b = 1; $c = 2; echo $a . \" \" . $b . \" \"; // prevFact[] stores factorial // of previous fibonacci number $prevFact[0] = 1; // Standard Fibonacci // number loop while ($c < $limit) { factorial($b, $c); $a = $b; $b = $c; $c = $a + $b; } } // Function used to// find factorialfunction multiply($x,$size) { global $prevFact; $carry = 0; for ($i = 0; $i < $size; $i++) { $prod = $prevFact[$i] * $x + $carry; $prevFact[$i] = $prod % 10; $carry = (int)($prod / 10); } // Put carry in // res and increase // result size while ($carry != 0) { $prevFact[$size] = $carry % 10; $carry = (int)($carry / 10); $size++; } return $size; } // Driver Code$limit = 20;printfibFactorials($limit); // This code is contributed// by mits?>", "e": 35741, "s": 33692, "text": null }, { "code": "<script> // Javascript program to find// factorial of each element// of Fibonacci series // Maximum number of // digits in output var MAX = 500; var size = 1; // Finds and print factorial // of n using factorial of // prev (stored in prevFact[ // 0...size-1] // Finds factorial of n // using factorial \"prev\" // stored in prevFact. size // is size of prevFact function factorial(prevFact , prev , n) { for (x = prev + 1; x <= n; x++) size = multiply(x, prevFact, size); for (i = size - 1; i >= 0; i--) document.write(prevFact[i]); document.write(\" \"); } // Prints factorials of all // fibonacci numbers smaller // than given limit. function printfibFactorials(limit) { if (limit < 1) return; // Initialize first three // Fibonacci numbers and // print factorials of // first two numbers. var a = 1, b = 1, c = 2; document.write(a + \" \" + b + \" \"); // prevFact stores factorial // of previous fibonacci number var prevFact = Array(MAX).fill(0); prevFact[0] = 1; // Standard Fibonacci // number loop while (c < limit) { factorial(prevFact, b, c); a = b; b = c; c = a + b; } } // Please refer below // article for details of // below two functions. // https://www.geeksforgeeks.org/factorial-large-number/ // Function used to // find factorial function multiply(x, prevFact , size) { var carry = 0; for (i = 0; i < size; i++) { var prod = prevFact[i] * x + carry; prevFact[i] = prod % 10; carry = parseInt(prod / 10); } // Put carry in // res and increase // result size while (carry != 0) { prevFact[size] = carry % 10; carry = parseInt(carry / 10); size++; } return size; } // Driver Code var limit = 20; printfibFactorials(limit); // This code is contributed by todaysgaurav </script>", "e": 37873, "s": 35741, "text": null }, { "code": null, "e": 37884, "s": 37873, "text": "Output : " }, { "code": null, "e": 37913, "s": 37884, "text": "1 1 2 6 120 40320 6227020800" }, { "code": null, "e": 37927, "s": 37915, "text": "manishshaw1" }, { "code": null, "e": 37940, "s": 37927, "text": "Mithun Kumar" }, { "code": null, "e": 37954, "s": 37940, "text": "Nikita tiwari" }, { "code": null, "e": 37967, "s": 37954, "text": "todaysgaurav" }, { "code": null, "e": 37983, "s": 37967, "text": "simranarora5sos" }, { "code": null, "e": 37993, "s": 37983, "text": "factorial" }, { "code": null, "e": 38003, "s": 37993, "text": "Fibonacci" }, { "code": null, "e": 38010, "s": 38003, "text": "series" }, { "code": null, "e": 38023, "s": 38010, "text": "Mathematical" }, { "code": null, "e": 38036, "s": 38023, "text": "Mathematical" }, { "code": null, "e": 38043, "s": 38036, "text": "series" }, { "code": null, "e": 38053, "s": 38043, "text": "Fibonacci" }, { "code": null, "e": 38063, "s": 38053, "text": "factorial" }, { "code": null, "e": 38161, "s": 38063, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38170, "s": 38161, "text": "Comments" }, { "code": null, "e": 38183, "s": 38170, "text": "Old Comments" }, { "code": null, "e": 38228, "s": 38183, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 38260, "s": 38228, "text": "Check if a number is Palindrome" }, { "code": null, "e": 38304, "s": 38260, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 38338, "s": 38304, "text": "Program to add two binary strings" }, { "code": null, "e": 38371, "s": 38338, "text": "Program to multiply two matrices" }, { "code": null, "e": 38396, "s": 38371, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 38435, "s": 38396, "text": "Find pair with maximum GCD in an array" }, { "code": null, "e": 38486, "s": 38435, "text": "Find Union and Intersection of two unsorted arrays" }, { "code": null, "e": 38557, "s": 38486, "text": "Count all possible paths from top left to bottom right of a mXn matrix" } ]
Reasons to Choose gRPC over REST and How to Adopt It into Your Python APIs | by Dimitris Poulopoulos | Towards Data Science
For a long time now, we’ve had REST (REpresentational State Transfer). REST APIs are cozy, warm, friendly, and very flexible. And if I’m permitted to be a bit abrupt here, thank God I don’t have to use SOAP anymore! So why on earth do we want to change everything again? Why do we keep inventing new, shiny stuff to replace tools that work so well? What is this gRPC thing now? Well, the simple answer is, “there is no one size that fits all.” If you were to deliver a letter reliably and as fast as possible, how would you do it? The first idea that pops into my mind is that I would do it myself. Hop into my car, drive to the destination and ring the bell with my own fingers. But maybe I don’t have the time to do it myself. So, I would probably call an Uber and use the corresponding service. Wait now; this becomes way too expensive. Also, what if the destination is on the other side of the world? Express mail service is the way to go in the end. Different solutions to the same problem. In any case, knowing the many benefits and downsides of using one form of message passing technique over the other is crucial when designing the communication APIs between microservices. In this story, we see when to choose gRPC over REST and implement a gRPC service in Python. Learning Rate is a newsletter for those who are curious about the world of AI and MLOps. You’ll hear from me every Friday with updates and thoughts on the latest AI news and articles. Subscribe here! As we’ve already seen, REST stands for “REpresentational State Transfer.” It provides a set of guidelines on how to create web APIs. But that’s it, a set of guidelines. It does not try to enforce anything. To return to our mail delivery analogy, there are some guidelines for writing a letter. You may start with the date, the info and the recipient’s address, and then a salutation. In the end, you may close the letter with your personal signature. However, is there someone or something to enforce those rules? Would the mailman deny the delivery of a letter that does not conform to these guidelines? No! You could even draw a picture inside if you wanted to. After all, they say that a picture is worth a thousand words. So what exactly are the properties of REST? Client-Server: A client makes a request and receives a response from the server. The client doesn’t need to know how the server is implemented. It also doesn't need to know if the server is sending back cached responses or if its request went through one hundred layers before getting a response.Statelessness: Each request is self-contained, and it includes all the information necessary to process it. The server does not keep track of any context.Uniform Interface: The API interface should be consistent, documenting the message format, the endpoints, and the message headers. Client-Server: A client makes a request and receives a response from the server. The client doesn’t need to know how the server is implemented. It also doesn't need to know if the server is sending back cached responses or if its request went through one hundred layers before getting a response. Statelessness: Each request is self-contained, and it includes all the information necessary to process it. The server does not keep track of any context. Uniform Interface: The API interface should be consistent, documenting the message format, the endpoints, and the message headers. Designing a REST API in Python is really straightforward but out of the scope of this story. If you want to see how it’s done, refer to Python’s Flask documentation. gRPC is a message-passing technique developed by Google. But the “g” in gRPC does not mean “google”; it’s actually pretty random. For example, the “g” in gRPC 1.12 stands for “glorious.” gRPC is programming-language agnostic, and it seems to be the new trend in the microservices communication world. Compared to REST, gRPC provides greater performance at the expense of less flexibility. So, gRPC does not provide a set of guidelines on how to create web APIs; it enforces rules. This time, the mailman would be very angry if you didn’t start the letter with a proper salutation! That is its main advantage over REST: gRPC, in most cases, is way faster and more robust, as it defines a specific set of rules each request and response should adhere to. Let’s now build a gRPC server in Python. The first step we should take is to define our message structure as a protobuf file. In this example, we assume that we are a bookstore, and we would like to get the books we have in our catalog and add new ones. This file (i.e., book.proto) defines a new message, BookMessage, that must contain an ISBN code, a title, an author, a description, a price and a condition, and in that order. Then, it defines a new service (i.e., BookService), which can create a new book or get all the existing ones. Next, implementing gRPC with Python involves two libraries: grpcio to run client and server code grpcio-tools to generate definition code You can install both of them with the following command: pip install grpcio grpcio-tools After installing these libraries, use the grpcio-tools one to generate the code you’ll need to build your gRPC server and client. Run the following command: python -m grpc_tools.protoc -I./ --python_out=./ --grpc_python_out=./ book.proto This command should produce two files: book_pb2.py book_pb2_grpc.py It’s not a good idea to edit those files directly. If you need to change anything, change the .proto file and rerun the command to re-generate the two Python files. We can now use these files to create our gRPC service: Finally, let’s create a client to test our service: The client creates a new BookMessage object and submits it to the server. From there, we assume that the server stores this new book inside the store’s catalog. gRPC seems to be the new, cool kid in town, but it is not here to replace REST. In general, REST has wider adoption. On the other hand, gRPC is more structured and usually faster out-of-the-box. Suppose you need speed or structure, use gRPC. So, a good use case for gRPC would be the internal communications of your microservices. On the other hand, it’s better to provide a REST endpoint to the outside world, as REST is something everybody uses. My name is Dimitris Poulopoulos, and I’m a machine learning engineer working for Arrikto. I have designed and implemented AI and software solutions for major clients such as the European Commission, Eurostat, IMF, the European Central Bank, OECD, and IKEA. If you are interested in reading more posts about Machine Learning, Deep Learning, Data Science, and DataOps, follow me on Medium, LinkedIn, or @james2pl on Twitter. Opinions expressed are solely my own and do not express the views or opinions of my employer.
[ { "code": null, "e": 387, "s": 171, "text": "For a long time now, we’ve had REST (REpresentational State Transfer). REST APIs are cozy, warm, friendly, and very flexible. And if I’m permitted to be a bit abrupt here, thank God I don’t have to use SOAP anymore!" }, { "code": null, "e": 549, "s": 387, "text": "So why on earth do we want to change everything again? Why do we keep inventing new, shiny stuff to replace tools that work so well? What is this gRPC thing now?" }, { "code": null, "e": 851, "s": 549, "text": "Well, the simple answer is, “there is no one size that fits all.” If you were to deliver a letter reliably and as fast as possible, how would you do it? The first idea that pops into my mind is that I would do it myself. Hop into my car, drive to the destination and ring the bell with my own fingers." }, { "code": null, "e": 1167, "s": 851, "text": "But maybe I don’t have the time to do it myself. So, I would probably call an Uber and use the corresponding service. Wait now; this becomes way too expensive. Also, what if the destination is on the other side of the world? Express mail service is the way to go in the end. Different solutions to the same problem." }, { "code": null, "e": 1446, "s": 1167, "text": "In any case, knowing the many benefits and downsides of using one form of message passing technique over the other is crucial when designing the communication APIs between microservices. In this story, we see when to choose gRPC over REST and implement a gRPC service in Python." }, { "code": null, "e": 1646, "s": 1446, "text": "Learning Rate is a newsletter for those who are curious about the world of AI and MLOps. You’ll hear from me every Friday with updates and thoughts on the latest AI news and articles. Subscribe here!" }, { "code": null, "e": 1852, "s": 1646, "text": "As we’ve already seen, REST stands for “REpresentational State Transfer.” It provides a set of guidelines on how to create web APIs. But that’s it, a set of guidelines. It does not try to enforce anything." }, { "code": null, "e": 2097, "s": 1852, "text": "To return to our mail delivery analogy, there are some guidelines for writing a letter. You may start with the date, the info and the recipient’s address, and then a salutation. In the end, you may close the letter with your personal signature." }, { "code": null, "e": 2372, "s": 2097, "text": "However, is there someone or something to enforce those rules? Would the mailman deny the delivery of a letter that does not conform to these guidelines? No! You could even draw a picture inside if you wanted to. After all, they say that a picture is worth a thousand words." }, { "code": null, "e": 2416, "s": 2372, "text": "So what exactly are the properties of REST?" }, { "code": null, "e": 2997, "s": 2416, "text": "Client-Server: A client makes a request and receives a response from the server. The client doesn’t need to know how the server is implemented. It also doesn't need to know if the server is sending back cached responses or if its request went through one hundred layers before getting a response.Statelessness: Each request is self-contained, and it includes all the information necessary to process it. The server does not keep track of any context.Uniform Interface: The API interface should be consistent, documenting the message format, the endpoints, and the message headers." }, { "code": null, "e": 3294, "s": 2997, "text": "Client-Server: A client makes a request and receives a response from the server. The client doesn’t need to know how the server is implemented. It also doesn't need to know if the server is sending back cached responses or if its request went through one hundred layers before getting a response." }, { "code": null, "e": 3449, "s": 3294, "text": "Statelessness: Each request is self-contained, and it includes all the information necessary to process it. The server does not keep track of any context." }, { "code": null, "e": 3580, "s": 3449, "text": "Uniform Interface: The API interface should be consistent, documenting the message format, the endpoints, and the message headers." }, { "code": null, "e": 3746, "s": 3580, "text": "Designing a REST API in Python is really straightforward but out of the scope of this story. If you want to see how it’s done, refer to Python’s Flask documentation." }, { "code": null, "e": 3933, "s": 3746, "text": "gRPC is a message-passing technique developed by Google. But the “g” in gRPC does not mean “google”; it’s actually pretty random. For example, the “g” in gRPC 1.12 stands for “glorious.”" }, { "code": null, "e": 4135, "s": 3933, "text": "gRPC is programming-language agnostic, and it seems to be the new trend in the microservices communication world. Compared to REST, gRPC provides greater performance at the expense of less flexibility." }, { "code": null, "e": 4327, "s": 4135, "text": "So, gRPC does not provide a set of guidelines on how to create web APIs; it enforces rules. This time, the mailman would be very angry if you didn’t start the letter with a proper salutation!" }, { "code": null, "e": 4499, "s": 4327, "text": "That is its main advantage over REST: gRPC, in most cases, is way faster and more robust, as it defines a specific set of rules each request and response should adhere to." }, { "code": null, "e": 4753, "s": 4499, "text": "Let’s now build a gRPC server in Python. The first step we should take is to define our message structure as a protobuf file. In this example, we assume that we are a bookstore, and we would like to get the books we have in our catalog and add new ones." }, { "code": null, "e": 4929, "s": 4753, "text": "This file (i.e., book.proto) defines a new message, BookMessage, that must contain an ISBN code, a title, an author, a description, a price and a condition, and in that order." }, { "code": null, "e": 5039, "s": 4929, "text": "Then, it defines a new service (i.e., BookService), which can create a new book or get all the existing ones." }, { "code": null, "e": 5099, "s": 5039, "text": "Next, implementing gRPC with Python involves two libraries:" }, { "code": null, "e": 5136, "s": 5099, "text": "grpcio to run client and server code" }, { "code": null, "e": 5177, "s": 5136, "text": "grpcio-tools to generate definition code" }, { "code": null, "e": 5234, "s": 5177, "text": "You can install both of them with the following command:" }, { "code": null, "e": 5266, "s": 5234, "text": "pip install grpcio grpcio-tools" }, { "code": null, "e": 5423, "s": 5266, "text": "After installing these libraries, use the grpcio-tools one to generate the code you’ll need to build your gRPC server and client. Run the following command:" }, { "code": null, "e": 5504, "s": 5423, "text": "python -m grpc_tools.protoc -I./ --python_out=./ --grpc_python_out=./ book.proto" }, { "code": null, "e": 5543, "s": 5504, "text": "This command should produce two files:" }, { "code": null, "e": 5555, "s": 5543, "text": "book_pb2.py" }, { "code": null, "e": 5572, "s": 5555, "text": "book_pb2_grpc.py" }, { "code": null, "e": 5737, "s": 5572, "text": "It’s not a good idea to edit those files directly. If you need to change anything, change the .proto file and rerun the command to re-generate the two Python files." }, { "code": null, "e": 5792, "s": 5737, "text": "We can now use these files to create our gRPC service:" }, { "code": null, "e": 5844, "s": 5792, "text": "Finally, let’s create a client to test our service:" }, { "code": null, "e": 6005, "s": 5844, "text": "The client creates a new BookMessage object and submits it to the server. From there, we assume that the server stores this new book inside the store’s catalog." }, { "code": null, "e": 6200, "s": 6005, "text": "gRPC seems to be the new, cool kid in town, but it is not here to replace REST. In general, REST has wider adoption. On the other hand, gRPC is more structured and usually faster out-of-the-box." }, { "code": null, "e": 6453, "s": 6200, "text": "Suppose you need speed or structure, use gRPC. So, a good use case for gRPC would be the internal communications of your microservices. On the other hand, it’s better to provide a REST endpoint to the outside world, as REST is something everybody uses." }, { "code": null, "e": 6710, "s": 6453, "text": "My name is Dimitris Poulopoulos, and I’m a machine learning engineer working for Arrikto. I have designed and implemented AI and software solutions for major clients such as the European Commission, Eurostat, IMF, the European Central Bank, OECD, and IKEA." }, { "code": null, "e": 6876, "s": 6710, "text": "If you are interested in reading more posts about Machine Learning, Deep Learning, Data Science, and DataOps, follow me on Medium, LinkedIn, or @james2pl on Twitter." } ]
Program to find the maximum element in a Matrix - GeeksforGeeks
07 May, 2021 Given a NxM matrix. The task is to find the maximum element in this matrix.Examples: Input: mat[4][4] = {{1, 2, 3, 4}, {25, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; Output: 25 Input: mat[3][4] = {{9, 8, 7, 6}, {5, 4, 3, 2}, {1, 0, 12, 45}}; Output: 45 Approach: The idea is to traverse the matrix using two nested loops, one for rows and one for columns and find the maximum element. Initialize a variable maxElement with a minimum value and traverse the matrix and compare every time if the current element is greater than a maxElement. If yes then update maxElement with the current element.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // CPP code to find max element in a matrix#include <bits/stdc++.h>using namespace std; #define N 4#define M 4 // Function to find max element// mat[][] : 2D array to find max elementint findMax(int mat[N][M]){ // Initializing max element as INT_MIN int maxElement = INT_MIN; // checking each element of matrix // if it is greater than maxElement, // update maxElement for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (mat[i][j] > maxElement) { maxElement = mat[i][j]; } } } // finally return maxElement return maxElement;} // Driver codeint main(){ // matrix int mat[N][M] = { { 1, 2, 3, 4 }, { 25, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; cout << findMax(mat) << endl; return 0;} // Java code to find max element in a matrix public class GFG { final static int N = 4; final static int M = 4 ; // Function to find max element // mat[][] : 2D array to find max element static int findMax(int mat[][]) { // Initializing max element as INT_MIN int maxElement = Integer.MIN_VALUE; // checking each element of matrix // if it is greater than maxElement, // update maxElement for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (mat[i][j] > maxElement) { maxElement = mat[i][j]; } } } // finally return maxElement return maxElement; } // Driver code public static void main(String args[]) { // matrix int mat[][] = { { 1, 2, 3, 4 }, { 25, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; System.out.println(findMax(mat)) ; } // This Code is contributed by ANKITRAI1} # Python 3 code to find max element# in a matriximport sysN = 4M = 4 # Function to find max element# mat[][] : 2D array to find max elementdef findMax(mat): # Initializing max element as INT_MIN maxElement = -sys.maxsize - 1 # checking each element of matrix # if it is greater than maxElement, # update maxElement for i in range(N): for j in range(M): if (mat[i][j] > maxElement): maxElement = mat[i][j] # finally return maxElement return maxElement # Driver codeif __name__ == '__main__': # matrix mat = [[1, 2, 3, 4], [25, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] print(findMax(mat)) # This code is contributed by# Surendra_Gangwar // C# code to find max element in a matrixusing System; class GFG { static int N = 4; static int M = 4 ; // Function to find max element // mat[,] : 2D array to find max element static int findMax(int[,] mat) { // Initializing max element as INT_MIN int maxElement = int.MinValue; // checking each element of matrix // if it is greater than maxElement, // update maxElement for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (mat[i,j] > maxElement) { maxElement = mat[i,j]; } } } // finally return maxElement return maxElement; } // Driver code public static void Main() { // matrix int[,]mat = {{ 1, 2, 3, 4}, {25, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; Console.Write(findMax(mat)) ; } } // This code is contributed by ChitraNayal <?php// PHP code to find max element in a matrix // Function to find max element// mat[][] : 2D array to find max elementfunction findMax($mat){ // Initializing max element as INT_MIN $maxElement = PHP_INT_MIN; // checking each element of matrix // if it is greater than maxElement, // update maxElement for ($i = 0; $i < 4; $i++) { for ($j = 0; $j < 4; $j++) { if ($mat[$i][$j] > $maxElement) { $maxElement = $mat[$i][$j]; } } } // finally return maxElement return $maxElement;} // Driver code$mat = array(array(1, 2, 3, 4), array(25, 6, 7, 8), array(9, 10, 11, 12), array(13, 14, 15, 16)); echo findMax($mat) . "\n"; // This code is contributed// by Akanksha Rai?> <script>// Java script code to find max element in a matrix let N = 4; let M = 4 ; // Function to find max element // mat[][] : 2D array to find max element function findMax(mat) { // Initializing max element as INT_MIN let maxElement = Number.MIN_VALUE; // checking each element of matrix // if it is greater than maxElement, // update maxElement for (let i = 0; i < N; i++) { for (let j = 0; j < M; j++) { if (mat[i][j] > maxElement) { maxElement = mat[i][j]; } } } // finally return maxElement return maxElement; } // Driver code // matrix let mat = [[ 1, 2, 3, 4 ], [ 25, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ]]; document.write(findMax(mat)) ; // This code is contributed by manoj</script> 25 Time Complexity: O(N*M) ankthon ukasp SURENDRA_GANGWAR Akanksha_Rai manojkumarreddymallidi Matrix School Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sudoku | Backtracking-7 Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Count all possible paths from top left to bottom right of a mXn matrix Program to multiply two matrices Min Cost Path | DP-6 Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26171, "s": 26143, "text": "\n07 May, 2021" }, { "code": null, "e": 26258, "s": 26171, "text": "Given a NxM matrix. The task is to find the maximum element in this matrix.Examples: " }, { "code": null, "e": 26531, "s": 26258, "text": "Input: mat[4][4] = {{1, 2, 3, 4},\n {25, 6, 7, 8},\n {9, 10, 11, 12},\n {13, 14, 15, 16}};\nOutput: 25\n\nInput: mat[3][4] = {{9, 8, 7, 6},\n {5, 4, 3, 2},\n {1, 0, 12, 45}};\nOutput: 45" }, { "code": null, "e": 26927, "s": 26533, "text": "Approach: The idea is to traverse the matrix using two nested loops, one for rows and one for columns and find the maximum element. Initialize a variable maxElement with a minimum value and traverse the matrix and compare every time if the current element is greater than a maxElement. If yes then update maxElement with the current element.Below is the implementation of the above approach: " }, { "code": null, "e": 26931, "s": 26927, "text": "C++" }, { "code": null, "e": 26936, "s": 26931, "text": "Java" }, { "code": null, "e": 26944, "s": 26936, "text": "Python3" }, { "code": null, "e": 26947, "s": 26944, "text": "C#" }, { "code": null, "e": 26951, "s": 26947, "text": "PHP" }, { "code": null, "e": 26962, "s": 26951, "text": "Javascript" }, { "code": "// CPP code to find max element in a matrix#include <bits/stdc++.h>using namespace std; #define N 4#define M 4 // Function to find max element// mat[][] : 2D array to find max elementint findMax(int mat[N][M]){ // Initializing max element as INT_MIN int maxElement = INT_MIN; // checking each element of matrix // if it is greater than maxElement, // update maxElement for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (mat[i][j] > maxElement) { maxElement = mat[i][j]; } } } // finally return maxElement return maxElement;} // Driver codeint main(){ // matrix int mat[N][M] = { { 1, 2, 3, 4 }, { 25, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; cout << findMax(mat) << endl; return 0;}", "e": 27828, "s": 26962, "text": null }, { "code": "// Java code to find max element in a matrix public class GFG { final static int N = 4; final static int M = 4 ; // Function to find max element // mat[][] : 2D array to find max element static int findMax(int mat[][]) { // Initializing max element as INT_MIN int maxElement = Integer.MIN_VALUE; // checking each element of matrix // if it is greater than maxElement, // update maxElement for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (mat[i][j] > maxElement) { maxElement = mat[i][j]; } } } // finally return maxElement return maxElement; } // Driver code public static void main(String args[]) { // matrix int mat[][] = { { 1, 2, 3, 4 }, { 25, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; System.out.println(findMax(mat)) ; } // This Code is contributed by ANKITRAI1}", "e": 28911, "s": 27828, "text": null }, { "code": "# Python 3 code to find max element# in a matriximport sysN = 4M = 4 # Function to find max element# mat[][] : 2D array to find max elementdef findMax(mat): # Initializing max element as INT_MIN maxElement = -sys.maxsize - 1 # checking each element of matrix # if it is greater than maxElement, # update maxElement for i in range(N): for j in range(M): if (mat[i][j] > maxElement): maxElement = mat[i][j] # finally return maxElement return maxElement # Driver codeif __name__ == '__main__': # matrix mat = [[1, 2, 3, 4], [25, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] print(findMax(mat)) # This code is contributed by# Surendra_Gangwar", "e": 29666, "s": 28911, "text": null }, { "code": "// C# code to find max element in a matrixusing System; class GFG { static int N = 4; static int M = 4 ; // Function to find max element // mat[,] : 2D array to find max element static int findMax(int[,] mat) { // Initializing max element as INT_MIN int maxElement = int.MinValue; // checking each element of matrix // if it is greater than maxElement, // update maxElement for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (mat[i,j] > maxElement) { maxElement = mat[i,j]; } } } // finally return maxElement return maxElement; } // Driver code public static void Main() { // matrix int[,]mat = {{ 1, 2, 3, 4}, {25, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; Console.Write(findMax(mat)) ; } } // This code is contributed by ChitraNayal", "e": 30745, "s": 29666, "text": null }, { "code": "<?php// PHP code to find max element in a matrix // Function to find max element// mat[][] : 2D array to find max elementfunction findMax($mat){ // Initializing max element as INT_MIN $maxElement = PHP_INT_MIN; // checking each element of matrix // if it is greater than maxElement, // update maxElement for ($i = 0; $i < 4; $i++) { for ($j = 0; $j < 4; $j++) { if ($mat[$i][$j] > $maxElement) { $maxElement = $mat[$i][$j]; } } } // finally return maxElement return $maxElement;} // Driver code$mat = array(array(1, 2, 3, 4), array(25, 6, 7, 8), array(9, 10, 11, 12), array(13, 14, 15, 16)); echo findMax($mat) . \"\\n\"; // This code is contributed// by Akanksha Rai?>", "e": 31550, "s": 30745, "text": null }, { "code": "<script>// Java script code to find max element in a matrix let N = 4; let M = 4 ; // Function to find max element // mat[][] : 2D array to find max element function findMax(mat) { // Initializing max element as INT_MIN let maxElement = Number.MIN_VALUE; // checking each element of matrix // if it is greater than maxElement, // update maxElement for (let i = 0; i < N; i++) { for (let j = 0; j < M; j++) { if (mat[i][j] > maxElement) { maxElement = mat[i][j]; } } } // finally return maxElement return maxElement; } // Driver code // matrix let mat = [[ 1, 2, 3, 4 ], [ 25, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ]]; document.write(findMax(mat)) ; // This code is contributed by manoj</script>", "e": 32515, "s": 31550, "text": null }, { "code": null, "e": 32518, "s": 32515, "text": "25" }, { "code": null, "e": 32545, "s": 32520, "text": "Time Complexity: O(N*M) " }, { "code": null, "e": 32553, "s": 32545, "text": "ankthon" }, { "code": null, "e": 32559, "s": 32553, "text": "ukasp" }, { "code": null, "e": 32576, "s": 32559, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 32589, "s": 32576, "text": "Akanksha_Rai" }, { "code": null, "e": 32612, "s": 32589, "text": "manojkumarreddymallidi" }, { "code": null, "e": 32619, "s": 32612, "text": "Matrix" }, { "code": null, "e": 32638, "s": 32619, "text": "School Programming" }, { "code": null, "e": 32645, "s": 32638, "text": "Matrix" }, { "code": null, "e": 32743, "s": 32645, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32767, "s": 32743, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 32829, "s": 32767, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 32900, "s": 32829, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 32933, "s": 32900, "text": "Program to multiply two matrices" }, { "code": null, "e": 32954, "s": 32933, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 32972, "s": 32954, "text": "Python Dictionary" }, { "code": null, "e": 32988, "s": 32972, "text": "Arrays in C/C++" }, { "code": null, "e": 33007, "s": 32988, "text": "Inheritance in C++" }, { "code": null, "e": 33032, "s": 33007, "text": "Reverse a string in Java" } ]
Cartesian tree from inorder traversal | Segment Tree - GeeksforGeeks
04 Oct, 2021 Given an in-order traversal of a cartesian tree, the task is to build the entire tree from it. Examples: Input: arr[] = {1, 5, 3} Output: 1 5 3 5 / \ 1 3 Input: arr[] = {3, 7, 4, 8} Output: 3 7 4 8 8 / 7 / \ 3 4 Approach: We have already seen an algorithm here that takes O(NlogN) time on an average but can get to O(N2) in the worst case.In this article, we will see how to build the cartesian in worst case running time of O(Nlog(N)). For this, we will use segment-tree to answer range-max queries. Below will be our recursive algorithm on range {L, R}: Find the maximum in this range {L, R} using range-max query on the segment-tree. Let’s say ‘M’ is index the maximum in the range.Pick up ‘arr[M]’ as the value for current node and create a node with this value.Solve for range {L, M-1} and {M+1, R}.Set the node returned by {L, M-1} as the left child of current node and {M+1, R} as the right child. Find the maximum in this range {L, R} using range-max query on the segment-tree. Let’s say ‘M’ is index the maximum in the range. Pick up ‘arr[M]’ as the value for current node and create a node with this value. Solve for range {L, M-1} and {M+1, R}. Set the node returned by {L, M-1} as the left child of current node and {M+1, R} as the right child. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define maxLen 30 // Node of the BSTstruct node { int data; node* left; node* right; node(int data) { left = NULL; right = NULL; this->data = data; }}; // Array to store segment treeint segtree[maxLen * 4]; // Function to create segment-tree to answer// range-max queryint buildTree(int l, int r, int i, int* arr){ // Base case if (l == r) { segtree[i] = l; return l; } // Maximum index in left range int l1 = buildTree(l, (l + r) / 2, 2 * i + 1, arr); // Maximum index in right range int r1 = buildTree((l + r) / 2 + 1, r, 2 * i + 2, arr); // If value at l1 > r1 if (arr[l1] > arr[r1]) segtree[i] = l1; // Else else segtree[i] = r1; // Returning the maximum in range return segtree[i];} // Function to answer range max queryint rangeMax(int l, int r, int rl, int rr, int i, int* arr){ // Base cases if (r < rl || l > rr) return -1; if (l >= rl and r <= rr) return segtree[i]; // Maximum in left range int l1 = rangeMax(l, (l + r) / 2, rl, rr, 2 * i + 1, arr); // Maximum in right range int r1 = rangeMax((l + r) / 2 + 1, r, rl, rr, 2 * i + 2, arr); // l1 = -1 means left range // was out-side required range if (l1 == -1) return r1; if (r1 == -1) return l1; // Returning the maximum // among two ranges if (arr[l1] > arr[r1]) return l1; else return r1;} // Function to print the inorder// traversal of the binary treevoid inorder(node* curr){ // Base case if (curr == NULL) return; // Traversing the left sub-tree inorder(curr->left); // Printing current node cout << curr->data << " "; // Traversing the right sub-tree inorder(curr->right);} // Function to build cartesian treenode* createCartesianTree(int l, int r, int* arr, int n){ // Base case if (r < l) return NULL; // Maximum in the range int m = rangeMax(0, n - 1, l, r, 0, arr); // Creating current node node* curr = new node(arr[m]); // Creating left sub-tree curr->left = createCartesianTree(l, m - 1, arr, n); // Creating right sub-tree curr->right = createCartesianTree(m + 1, r, arr, n); // Returning current node return curr;} // Driver codeint main(){ // In-order traversal of cartesian tree int arr[] = { 8, 11, 21, 100, 5, 70, 55 }; // Size of the array int n = sizeof(arr) / sizeof(int); // Building the segment tree buildTree(0, n - 1, 0, arr); // Building and printing cartesian tree inorder(createCartesianTree(0, n - 1, arr, n));} // Java implementation of the approachimport java.util.*; class GFG{static int maxLen = 30; // Node of the BSTstatic class node{ int data; node left; node right; node(int data) { left = null; right = null; this.data = data; }}; // Array to store segment treestatic int segtree[] = new int[maxLen * 4]; // Function to create segment-tree to answer// range-max querystatic int buildTree(int l, int r, int i, int[] arr){ // Base case if (l == r) { segtree[i] = l; return l; } // Maximum index in left range int l1 = buildTree(l, (l + r) / 2, 2 * i + 1, arr); // Maximum index in right range int r1 = buildTree((l + r) / 2 + 1, r, 2 * i + 2, arr); // If value at l1 > r1 if (arr[l1] > arr[r1]) segtree[i] = l1; // Else else segtree[i] = r1; // Returning the maximum in range return segtree[i];} // Function to answer range max querystatic int rangeMax(int l, int r, int rl, int rr, int i, int[] arr){ // Base cases if (r < rl || l > rr) return -1; if (l >= rl && r <= rr) return segtree[i]; // Maximum in left range int l1 = rangeMax(l, (l + r) / 2, rl, rr, 2 * i + 1, arr); // Maximum in right range int r1 = rangeMax((l + r) / 2 + 1, r, rl, rr, 2 * i + 2, arr); // l1 = -1 means left range // was out-side required range if (l1 == -1) return r1; if (r1 == -1) return l1; // Returning the maximum // among two ranges if (arr[l1] > arr[r1]) return l1; else return r1;} // Function to print the inorder// traversal of the binary treestatic void inorder(node curr){ // Base case if (curr == null) return; // Traversing the left sub-tree inorder(curr.left); // Printing current node System.out.print(curr.data + " "); // Traversing the right sub-tree inorder(curr.right);} // Function to build cartesian treestatic node createCartesianTree(int l, int r, int[] arr, int n){ // Base case if (r < l) return null; // Maximum in the range int m = rangeMax(0, n - 1, l, r, 0, arr); // Creating current node node curr = new node(arr[m]); // Creating left sub-tree curr.left = createCartesianTree(l, m - 1, arr, n); // Creating right sub-tree curr.right = createCartesianTree(m + 1, r, arr, n); // Returning current node return curr;} // Driver codepublic static void main(String args[]){ // In-order traversal of cartesian tree int arr[] = { 8, 11, 21, 100, 5, 70, 55 }; // Size of the array int n = arr.length; // Building the segment tree buildTree(0, n - 1, 0, arr); // Building && printing cartesian tree inorder(createCartesianTree(0, n - 1, arr, n));}} // This code is contributed by Arnab Kundu # Python3 implementation of the approach # Node of a linked listclass Node: def __init__(self, data = None, left = None, right = None ): self.data = data self.right = right self.left = left maxLen = 30 # Array to store segment treesegtree = [0]*(maxLen * 4) # Function to create segment-tree to answer# range-max querydef buildTree(l , r ,i , arr): global segtree global maxLen # Base case if (l == r) : segtree[i] = l return l # Maximum index in left range l1 = buildTree(l, int((l + r) / 2), 2 * i + 1, arr) # Maximum index in right range r1 = buildTree(int((l + r) / 2) + 1,r, 2 * i + 2, arr) # If value at l1 > r1 if (arr[l1] > arr[r1]): segtree[i] = l1 # Else else: segtree[i] = r1 # Returning the maximum in range return segtree[i] # Function to answer range max querydef rangeMax(l, r, rl, rr, i, arr): global segtree global maxLen # Base cases if (r < rl or l > rr): return -1 if (l >= rl and r <= rr): return segtree[i] # Maximum in left range l1 = rangeMax(l, int((l + r) / 2), rl, rr, 2 * i + 1, arr) # Maximum in right range r1 = rangeMax(int((l + r) / 2) + 1, r, rl, rr, 2 * i + 2, arr) # l1 = -1 means left range # was out-side required range if (l1 == -1): return r1 if (r1 == -1): return l1 # Returning the maximum # among two ranges if (arr[l1] > arr[r1]): return l1 else: return r1 # Function to print the inorder# traversal of the binary treedef inorder(curr): # Base case if (curr == None): return # Traversing the left sub-tree inorder(curr.left) # Printing current node print(curr.data, end= " ") # Traversing the right sub-tree inorder(curr.right) # Function to build cartesian treedef createCartesianTree(l , r , arr, n): # Base case if (r < l): return None # Maximum in the range m = rangeMax(0, n - 1, l, r, 0, arr) # Creating current node curr = Node(arr[m]) # Creating left sub-tree curr.left = createCartesianTree(l, m - 1, arr, n) # Creating right sub-tree curr.right = createCartesianTree(m + 1, r, arr, n) # Returning current node return curr # Driver code # In-order traversal of cartesian treearr = [ 8, 11, 21, 100, 5, 70, 55 ] # Size of the arrayn = len(arr) # Building the segment treebuildTree(0, n - 1, 0, arr) # Building && printing cartesian treeinorder(createCartesianTree(0, n - 1, arr, n)) # This code is contributed by Arnab Kundu // C# implementation of the approachusing System; class GFG{ static int maxLen = 30; // Node of the BST public class node { public int data; public node left; public node right; public node(int data) { left = null; right = null; this.data = data; } }; // Array to store segment tree static int []segtree = new int[maxLen * 4]; // Function to create segment-tree to answer // range-max query static int buildTree(int l, int r, int i, int[] arr) { // Base case if (l == r) { segtree[i] = l; return l; } // Maximum index in left range int l1 = buildTree(l, (l + r) / 2, 2 * i + 1, arr); // Maximum index in right range int r1 = buildTree((l + r) / 2 + 1, r, 2 * i + 2, arr); // If value at l1 > r1 if (arr[l1] > arr[r1]) segtree[i] = l1; // Else else segtree[i] = r1; // Returning the maximum in range return segtree[i]; } // Function to answer range max query static int rangeMax(int l, int r, int rl, int rr, int i, int[] arr) { // Base cases if (r < rl || l > rr) return -1; if (l >= rl && r <= rr) return segtree[i]; // Maximum in left range int l1 = rangeMax(l, (l + r) / 2, rl, rr, 2 * i + 1, arr); // Maximum in right range int r1 = rangeMax((l + r) / 2 + 1, r, rl, rr, 2 * i + 2, arr); // l1 = -1 means left range // was out-side required range if (l1 == -1) return r1; if (r1 == -1) return l1; // Returning the maximum // among two ranges if (arr[l1] > arr[r1]) return l1; else return r1; } // Function to print the inorder // traversal of the binary tree static void inorder(node curr) { // Base case if (curr == null) return; // Traversing the left sub-tree inorder(curr.left); // Printing current node Console.Write(curr.data + " "); // Traversing the right sub-tree inorder(curr.right); } // Function to build cartesian tree static node createCartesianTree(int l, int r, int[] arr, int n) { // Base case if (r < l) return null; // Maximum in the range int m = rangeMax(0, n - 1, l, r, 0, arr); // Creating current node node curr = new node(arr[m]); // Creating left sub-tree curr.left = createCartesianTree(l, m - 1, arr, n); // Creating right sub-tree curr.right = createCartesianTree(m + 1, r, arr, n); // Returning current node return curr; } // Driver code public static void Main() { // In-order traversal of cartesian tree int []arr = { 8, 11, 21, 100, 5, 70, 55 }; // Size of the array int n = arr.Length; // Building the segment tree buildTree(0, n - 1, 0, arr); // Building && printing cartesian tree inorder(createCartesianTree(0, n - 1, arr, n)); }} // This code is contributed by AnkitRai01 <script> // Javascript implementation of the approachvar maxLen = 30; // Node of the BSTclass node{ constructor(data) { this.data = data; this.left = null; this.right = null; }}; // Array to store segment treevar segtree = Array(maxLen * 4).fill(0); // Function to create segment-tree to answer// range-max queryfunction buildTree(l, r, i, arr){ // Base case if (l == r) { segtree[i] = l; return l; } // Maximum index in left range var l1 = buildTree(l, parseInt((l + r) / 2), 2 * i + 1, arr); // Maximum index in right range var r1 = buildTree(parseInt((l + r) / 2) + 1, r, 2 * i + 2, arr); // If value at l1 > r1 if (arr[l1] > arr[r1]) segtree[i] = l1; // Else else segtree[i] = r1; // Returning the maximum in range return segtree[i];} // Function to answer range max queryfunction rangeMax(l, r, rl, rr, i, arr){ // Base cases if (r < rl || l > rr) return -1; if (l >= rl && r <= rr) return segtree[i]; // Maximum in left range var l1 = rangeMax(l, parseInt((l + r) / 2), rl, rr, 2 * i + 1, arr); // Maximum in right range var r1 = rangeMax(parseInt((l + r) / 2) + 1, r, rl, rr, 2 * i + 2, arr); // l1 = -1 means left range // was out-side required range if (l1 == -1) return r1; if (r1 == -1) return l1; // Returning the maximum // among two ranges if (arr[l1] > arr[r1]) return l1; else return r1;} // Function to print the inorder// traversal of the binary treefunction inorder(curr){ // Base case if (curr == null) return; // Traversing the left sub-tree inorder(curr.left); // Printing current node document.write(curr.data + " "); // Traversing the right sub-tree inorder(curr.right);} // Function to build cartesian treefunction createCartesianTree(l, r, arr, n){ // Base case if (r < l) return null; // Maximum in the range var m = rangeMax(0, n - 1, l, r, 0, arr); // Creating current node var curr = new node(arr[m]); // Creating left sub-tree curr.left = createCartesianTree(l, m - 1, arr, n); // Creating right sub-tree curr.right = createCartesianTree(m + 1, r, arr, n); // Returning current node return curr;} // Driver code // In-order traversal of cartesian treevar arr = [ 8, 11, 21, 100, 5, 70, 55 ]; // Size of the arrayvar n = arr.length; // Building the segment treebuildTree(0, n - 1, 0, arr); // Building && printing cartesian treeinorder(createCartesianTree(0, n - 1, arr, n)); // This code is contributed by noob2000 </script> 8 11 21 100 5 70 55 Time complexity: O(N+logN)Auxiliary Space: O(N). andrew1234 ankthon noob2000 pankajsharmagfg ashutoshsinghgeeksforgeeks Segment-Tree Algorithms Data Structures Divide and Conquer Recursion Tree Data Structures Recursion Divide and Conquer Tree Segment-Tree Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? K means Clustering - Introduction Difference between Algorithm, Pseudocode and Program Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete DSA Sheet by Love Babbar Doubly Linked List | Set 1 (Introduction and Insertion) How to Start Learning DSA? Abstract Data Types Implementing a Linked List in Java using Class
[ { "code": null, "e": 25943, "s": 25915, "text": "\n04 Oct, 2021" }, { "code": null, "e": 26038, "s": 25943, "text": "Given an in-order traversal of a cartesian tree, the task is to build the entire tree from it." }, { "code": null, "e": 26049, "s": 26038, "text": "Examples: " }, { "code": null, "e": 26179, "s": 26049, "text": "Input: arr[] = {1, 5, 3}\nOutput: 1 5 3\n 5\n / \\\n1 3\n\nInput: arr[] = {3, 7, 4, 8}\nOutput: 3 7 4 8\n 8\n /\n 7\n / \\\n 3 4" }, { "code": null, "e": 26468, "s": 26179, "text": "Approach: We have already seen an algorithm here that takes O(NlogN) time on an average but can get to O(N2) in the worst case.In this article, we will see how to build the cartesian in worst case running time of O(Nlog(N)). For this, we will use segment-tree to answer range-max queries." }, { "code": null, "e": 26525, "s": 26468, "text": "Below will be our recursive algorithm on range {L, R}: " }, { "code": null, "e": 26874, "s": 26525, "text": "Find the maximum in this range {L, R} using range-max query on the segment-tree. Let’s say ‘M’ is index the maximum in the range.Pick up ‘arr[M]’ as the value for current node and create a node with this value.Solve for range {L, M-1} and {M+1, R}.Set the node returned by {L, M-1} as the left child of current node and {M+1, R} as the right child." }, { "code": null, "e": 27004, "s": 26874, "text": "Find the maximum in this range {L, R} using range-max query on the segment-tree. Let’s say ‘M’ is index the maximum in the range." }, { "code": null, "e": 27086, "s": 27004, "text": "Pick up ‘arr[M]’ as the value for current node and create a node with this value." }, { "code": null, "e": 27125, "s": 27086, "text": "Solve for range {L, M-1} and {M+1, R}." }, { "code": null, "e": 27226, "s": 27125, "text": "Set the node returned by {L, M-1} as the left child of current node and {M+1, R} as the right child." }, { "code": null, "e": 27279, "s": 27226, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27283, "s": 27279, "text": "C++" }, { "code": null, "e": 27288, "s": 27283, "text": "Java" }, { "code": null, "e": 27296, "s": 27288, "text": "Python3" }, { "code": null, "e": 27299, "s": 27296, "text": "C#" }, { "code": null, "e": 27310, "s": 27299, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define maxLen 30 // Node of the BSTstruct node { int data; node* left; node* right; node(int data) { left = NULL; right = NULL; this->data = data; }}; // Array to store segment treeint segtree[maxLen * 4]; // Function to create segment-tree to answer// range-max queryint buildTree(int l, int r, int i, int* arr){ // Base case if (l == r) { segtree[i] = l; return l; } // Maximum index in left range int l1 = buildTree(l, (l + r) / 2, 2 * i + 1, arr); // Maximum index in right range int r1 = buildTree((l + r) / 2 + 1, r, 2 * i + 2, arr); // If value at l1 > r1 if (arr[l1] > arr[r1]) segtree[i] = l1; // Else else segtree[i] = r1; // Returning the maximum in range return segtree[i];} // Function to answer range max queryint rangeMax(int l, int r, int rl, int rr, int i, int* arr){ // Base cases if (r < rl || l > rr) return -1; if (l >= rl and r <= rr) return segtree[i]; // Maximum in left range int l1 = rangeMax(l, (l + r) / 2, rl, rr, 2 * i + 1, arr); // Maximum in right range int r1 = rangeMax((l + r) / 2 + 1, r, rl, rr, 2 * i + 2, arr); // l1 = -1 means left range // was out-side required range if (l1 == -1) return r1; if (r1 == -1) return l1; // Returning the maximum // among two ranges if (arr[l1] > arr[r1]) return l1; else return r1;} // Function to print the inorder// traversal of the binary treevoid inorder(node* curr){ // Base case if (curr == NULL) return; // Traversing the left sub-tree inorder(curr->left); // Printing current node cout << curr->data << \" \"; // Traversing the right sub-tree inorder(curr->right);} // Function to build cartesian treenode* createCartesianTree(int l, int r, int* arr, int n){ // Base case if (r < l) return NULL; // Maximum in the range int m = rangeMax(0, n - 1, l, r, 0, arr); // Creating current node node* curr = new node(arr[m]); // Creating left sub-tree curr->left = createCartesianTree(l, m - 1, arr, n); // Creating right sub-tree curr->right = createCartesianTree(m + 1, r, arr, n); // Returning current node return curr;} // Driver codeint main(){ // In-order traversal of cartesian tree int arr[] = { 8, 11, 21, 100, 5, 70, 55 }; // Size of the array int n = sizeof(arr) / sizeof(int); // Building the segment tree buildTree(0, n - 1, 0, arr); // Building and printing cartesian tree inorder(createCartesianTree(0, n - 1, arr, n));}", "e": 30109, "s": 27310, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{static int maxLen = 30; // Node of the BSTstatic class node{ int data; node left; node right; node(int data) { left = null; right = null; this.data = data; }}; // Array to store segment treestatic int segtree[] = new int[maxLen * 4]; // Function to create segment-tree to answer// range-max querystatic int buildTree(int l, int r, int i, int[] arr){ // Base case if (l == r) { segtree[i] = l; return l; } // Maximum index in left range int l1 = buildTree(l, (l + r) / 2, 2 * i + 1, arr); // Maximum index in right range int r1 = buildTree((l + r) / 2 + 1, r, 2 * i + 2, arr); // If value at l1 > r1 if (arr[l1] > arr[r1]) segtree[i] = l1; // Else else segtree[i] = r1; // Returning the maximum in range return segtree[i];} // Function to answer range max querystatic int rangeMax(int l, int r, int rl, int rr, int i, int[] arr){ // Base cases if (r < rl || l > rr) return -1; if (l >= rl && r <= rr) return segtree[i]; // Maximum in left range int l1 = rangeMax(l, (l + r) / 2, rl, rr, 2 * i + 1, arr); // Maximum in right range int r1 = rangeMax((l + r) / 2 + 1, r, rl, rr, 2 * i + 2, arr); // l1 = -1 means left range // was out-side required range if (l1 == -1) return r1; if (r1 == -1) return l1; // Returning the maximum // among two ranges if (arr[l1] > arr[r1]) return l1; else return r1;} // Function to print the inorder// traversal of the binary treestatic void inorder(node curr){ // Base case if (curr == null) return; // Traversing the left sub-tree inorder(curr.left); // Printing current node System.out.print(curr.data + \" \"); // Traversing the right sub-tree inorder(curr.right);} // Function to build cartesian treestatic node createCartesianTree(int l, int r, int[] arr, int n){ // Base case if (r < l) return null; // Maximum in the range int m = rangeMax(0, n - 1, l, r, 0, arr); // Creating current node node curr = new node(arr[m]); // Creating left sub-tree curr.left = createCartesianTree(l, m - 1, arr, n); // Creating right sub-tree curr.right = createCartesianTree(m + 1, r, arr, n); // Returning current node return curr;} // Driver codepublic static void main(String args[]){ // In-order traversal of cartesian tree int arr[] = { 8, 11, 21, 100, 5, 70, 55 }; // Size of the array int n = arr.length; // Building the segment tree buildTree(0, n - 1, 0, arr); // Building && printing cartesian tree inorder(createCartesianTree(0, n - 1, arr, n));}} // This code is contributed by Arnab Kundu", "e": 33071, "s": 30109, "text": null }, { "code": "# Python3 implementation of the approach # Node of a linked listclass Node: def __init__(self, data = None, left = None, right = None ): self.data = data self.right = right self.left = left maxLen = 30 # Array to store segment treesegtree = [0]*(maxLen * 4) # Function to create segment-tree to answer# range-max querydef buildTree(l , r ,i , arr): global segtree global maxLen # Base case if (l == r) : segtree[i] = l return l # Maximum index in left range l1 = buildTree(l, int((l + r) / 2), 2 * i + 1, arr) # Maximum index in right range r1 = buildTree(int((l + r) / 2) + 1,r, 2 * i + 2, arr) # If value at l1 > r1 if (arr[l1] > arr[r1]): segtree[i] = l1 # Else else: segtree[i] = r1 # Returning the maximum in range return segtree[i] # Function to answer range max querydef rangeMax(l, r, rl, rr, i, arr): global segtree global maxLen # Base cases if (r < rl or l > rr): return -1 if (l >= rl and r <= rr): return segtree[i] # Maximum in left range l1 = rangeMax(l, int((l + r) / 2), rl, rr, 2 * i + 1, arr) # Maximum in right range r1 = rangeMax(int((l + r) / 2) + 1, r, rl, rr, 2 * i + 2, arr) # l1 = -1 means left range # was out-side required range if (l1 == -1): return r1 if (r1 == -1): return l1 # Returning the maximum # among two ranges if (arr[l1] > arr[r1]): return l1 else: return r1 # Function to print the inorder# traversal of the binary treedef inorder(curr): # Base case if (curr == None): return # Traversing the left sub-tree inorder(curr.left) # Printing current node print(curr.data, end= \" \") # Traversing the right sub-tree inorder(curr.right) # Function to build cartesian treedef createCartesianTree(l , r , arr, n): # Base case if (r < l): return None # Maximum in the range m = rangeMax(0, n - 1, l, r, 0, arr) # Creating current node curr = Node(arr[m]) # Creating left sub-tree curr.left = createCartesianTree(l, m - 1, arr, n) # Creating right sub-tree curr.right = createCartesianTree(m + 1, r, arr, n) # Returning current node return curr # Driver code # In-order traversal of cartesian treearr = [ 8, 11, 21, 100, 5, 70, 55 ] # Size of the arrayn = len(arr) # Building the segment treebuildTree(0, n - 1, 0, arr) # Building && printing cartesian treeinorder(createCartesianTree(0, n - 1, arr, n)) # This code is contributed by Arnab Kundu", "e": 35753, "s": 33071, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ static int maxLen = 30; // Node of the BST public class node { public int data; public node left; public node right; public node(int data) { left = null; right = null; this.data = data; } }; // Array to store segment tree static int []segtree = new int[maxLen * 4]; // Function to create segment-tree to answer // range-max query static int buildTree(int l, int r, int i, int[] arr) { // Base case if (l == r) { segtree[i] = l; return l; } // Maximum index in left range int l1 = buildTree(l, (l + r) / 2, 2 * i + 1, arr); // Maximum index in right range int r1 = buildTree((l + r) / 2 + 1, r, 2 * i + 2, arr); // If value at l1 > r1 if (arr[l1] > arr[r1]) segtree[i] = l1; // Else else segtree[i] = r1; // Returning the maximum in range return segtree[i]; } // Function to answer range max query static int rangeMax(int l, int r, int rl, int rr, int i, int[] arr) { // Base cases if (r < rl || l > rr) return -1; if (l >= rl && r <= rr) return segtree[i]; // Maximum in left range int l1 = rangeMax(l, (l + r) / 2, rl, rr, 2 * i + 1, arr); // Maximum in right range int r1 = rangeMax((l + r) / 2 + 1, r, rl, rr, 2 * i + 2, arr); // l1 = -1 means left range // was out-side required range if (l1 == -1) return r1; if (r1 == -1) return l1; // Returning the maximum // among two ranges if (arr[l1] > arr[r1]) return l1; else return r1; } // Function to print the inorder // traversal of the binary tree static void inorder(node curr) { // Base case if (curr == null) return; // Traversing the left sub-tree inorder(curr.left); // Printing current node Console.Write(curr.data + \" \"); // Traversing the right sub-tree inorder(curr.right); } // Function to build cartesian tree static node createCartesianTree(int l, int r, int[] arr, int n) { // Base case if (r < l) return null; // Maximum in the range int m = rangeMax(0, n - 1, l, r, 0, arr); // Creating current node node curr = new node(arr[m]); // Creating left sub-tree curr.left = createCartesianTree(l, m - 1, arr, n); // Creating right sub-tree curr.right = createCartesianTree(m + 1, r, arr, n); // Returning current node return curr; } // Driver code public static void Main() { // In-order traversal of cartesian tree int []arr = { 8, 11, 21, 100, 5, 70, 55 }; // Size of the array int n = arr.Length; // Building the segment tree buildTree(0, n - 1, 0, arr); // Building && printing cartesian tree inorder(createCartesianTree(0, n - 1, arr, n)); }} // This code is contributed by AnkitRai01", "e": 39371, "s": 35753, "text": null }, { "code": "<script> // Javascript implementation of the approachvar maxLen = 30; // Node of the BSTclass node{ constructor(data) { this.data = data; this.left = null; this.right = null; }}; // Array to store segment treevar segtree = Array(maxLen * 4).fill(0); // Function to create segment-tree to answer// range-max queryfunction buildTree(l, r, i, arr){ // Base case if (l == r) { segtree[i] = l; return l; } // Maximum index in left range var l1 = buildTree(l, parseInt((l + r) / 2), 2 * i + 1, arr); // Maximum index in right range var r1 = buildTree(parseInt((l + r) / 2) + 1, r, 2 * i + 2, arr); // If value at l1 > r1 if (arr[l1] > arr[r1]) segtree[i] = l1; // Else else segtree[i] = r1; // Returning the maximum in range return segtree[i];} // Function to answer range max queryfunction rangeMax(l, r, rl, rr, i, arr){ // Base cases if (r < rl || l > rr) return -1; if (l >= rl && r <= rr) return segtree[i]; // Maximum in left range var l1 = rangeMax(l, parseInt((l + r) / 2), rl, rr, 2 * i + 1, arr); // Maximum in right range var r1 = rangeMax(parseInt((l + r) / 2) + 1, r, rl, rr, 2 * i + 2, arr); // l1 = -1 means left range // was out-side required range if (l1 == -1) return r1; if (r1 == -1) return l1; // Returning the maximum // among two ranges if (arr[l1] > arr[r1]) return l1; else return r1;} // Function to print the inorder// traversal of the binary treefunction inorder(curr){ // Base case if (curr == null) return; // Traversing the left sub-tree inorder(curr.left); // Printing current node document.write(curr.data + \" \"); // Traversing the right sub-tree inorder(curr.right);} // Function to build cartesian treefunction createCartesianTree(l, r, arr, n){ // Base case if (r < l) return null; // Maximum in the range var m = rangeMax(0, n - 1, l, r, 0, arr); // Creating current node var curr = new node(arr[m]); // Creating left sub-tree curr.left = createCartesianTree(l, m - 1, arr, n); // Creating right sub-tree curr.right = createCartesianTree(m + 1, r, arr, n); // Returning current node return curr;} // Driver code // In-order traversal of cartesian treevar arr = [ 8, 11, 21, 100, 5, 70, 55 ]; // Size of the arrayvar n = arr.length; // Building the segment treebuildTree(0, n - 1, 0, arr); // Building && printing cartesian treeinorder(createCartesianTree(0, n - 1, arr, n)); // This code is contributed by noob2000 </script>", "e": 42211, "s": 39371, "text": null }, { "code": null, "e": 42231, "s": 42211, "text": "8 11 21 100 5 70 55" }, { "code": null, "e": 42284, "s": 42233, "text": "Time complexity: O(N+logN)Auxiliary Space: O(N). " }, { "code": null, "e": 42295, "s": 42284, "text": "andrew1234" }, { "code": null, "e": 42303, "s": 42295, "text": "ankthon" }, { "code": null, "e": 42312, "s": 42303, "text": "noob2000" }, { "code": null, "e": 42328, "s": 42312, "text": "pankajsharmagfg" }, { "code": null, "e": 42355, "s": 42328, "text": "ashutoshsinghgeeksforgeeks" }, { "code": null, "e": 42368, "s": 42355, "text": "Segment-Tree" }, { "code": null, "e": 42379, "s": 42368, "text": "Algorithms" }, { "code": null, "e": 42395, "s": 42379, "text": "Data Structures" }, { "code": null, "e": 42414, "s": 42395, "text": "Divide and Conquer" }, { "code": null, "e": 42424, "s": 42414, "text": "Recursion" }, { "code": null, "e": 42429, "s": 42424, "text": "Tree" }, { "code": null, "e": 42445, "s": 42429, "text": "Data Structures" }, { "code": null, "e": 42455, "s": 42445, "text": "Recursion" }, { "code": null, "e": 42474, "s": 42455, "text": "Divide and Conquer" }, { "code": null, "e": 42479, "s": 42474, "text": "Tree" }, { "code": null, "e": 42492, "s": 42479, "text": "Segment-Tree" }, { "code": null, "e": 42503, "s": 42492, "text": "Algorithms" }, { "code": null, "e": 42601, "s": 42503, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42626, "s": 42601, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 42653, "s": 42626, "text": "How to Start Learning DSA?" }, { "code": null, "e": 42687, "s": 42653, "text": "K means Clustering - Introduction" }, { "code": null, "e": 42740, "s": 42687, "text": "Difference between Algorithm, Pseudocode and Program" }, { "code": null, "e": 42807, "s": 42740, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 42832, "s": 42807, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 42888, "s": 42832, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 42915, "s": 42888, "text": "How to Start Learning DSA?" }, { "code": null, "e": 42935, "s": 42915, "text": "Abstract Data Types" } ]
Check if removing a given edge disconnects a graph - GeeksforGeeks
16 Feb, 2022 Given an undirected graph and an edge, the task is to find if the given edge is a bridge in graph, i.e., removing the edge disconnects the graph. Following are some example graphs with bridges highlighted with red color. One solution is to find all bridges in given graph and then check if given edge is a bridge or not.A simpler solution is to remove the edge, check if graph remains connect after removal or not, finally add the edge back. We can always find if an undirected is connected or not by finding all reachable vertices from any vertex. If count of reachable vertices is equal to number of vertices in graph, then the graph is connected else not. We can find all reachable vertices either using BFS or DFS. Below are complete steps.1) Remove the given edge 2) Find all reachable vertices from any vertex. We have chosen first vertex in below implementation. 3) If count of reachable nodes is V, then return false [given is not Bridge]. Else return yes. C++ Java Python3 // C++ program to check if removing an// edge disconnects a graph or not.#include<bits/stdc++.h>using namespace std; // Graph class represents a directed graph// using adjacency list representationclass Graph{ int V; // No. of vertices list<int> *adj; void DFS(int v, bool visited[]);public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); // Returns true if graph is connected bool isConnected(); bool isBridge(int u, int v);}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int u, int v){ adj[u].push_back(v); // Add w to v’s list. adj[v].push_back(u); // Add w to v’s list.} void Graph::DFS(int v, bool visited[]){ // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to // this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFS(*i, visited);} // Returns true if given graph is connected, else falsebool Graph::isConnected(){ bool visited[V]; memset(visited, false, sizeof(visited)); // Find all reachable vertices from first vertex DFS(0, visited); // If set of reachable vertices includes all, // return true. for (int i=1; i<V; i++) if (visited[i] == false) return false; return true;} // This function assumes that edge (u, v)// exists in graph or not,bool Graph::isBridge(int u, int v){ // Remove edge from undirected graph adj[u].remove(v); adj[v].remove(u); bool res = isConnected(); // Adding the edge back addEdge(u, v); // Return true if graph becomes disconnected // after removing the edge. return (res == false);} // Driver codeint main(){ // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(1, 2); g.addEdge(2, 3); g.isBridge(1, 2)? cout << "Yes" : cout << "No"; return 0;} // Java program to check if removing an// edge disconnects a graph or not.import java.util.*; // Graph class represents a directed graph// using adjacency list representationclass Graph { int V; // No. of vertices ArrayList<ArrayList<Integer> > adj; private void DFS(int v, boolean[] visited) { // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to // this vertex for (Integer i : adj.get(v)) { if (!visited[i]) { DFS(i, visited); } } } public Graph(int V) { this.V = V; adj = new ArrayList<>(); for (int i = 0; i < V; i++) { adj.add(new ArrayList<>()); } } public void addEdge(int u, int v) { adj.get(u).add(v); // Add v to u’s list. adj.get(v).add(u); // Add u to v’s list. } // Returns true if given graph is connected, else false public boolean isConnected() { boolean[] visited = new boolean[V]; // Find all reachable vertices from first vertex DFS(0, visited); // If set of reachable vertices includes all, // return true. for (int i = 1; i < V; i++) if (visited[i] == false) return false; return true; } // This function assumes that edge (u, v) // exists in graph or not, public boolean isBridge(int u, int v) { // Remove edge from undirected graph adj.get(u).remove(Integer.valueOf(v)); adj.get(v).remove(Integer.valueOf(u)); boolean res = isConnected(); // Adding the edge back addEdge(u, v); // Return true if graph becomes disconnected // after removing the edge. return (res == false); } // Driver code public static void main(String[] args) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(1, 2); g.addEdge(2, 3); if (g.isBridge(1, 2)) { System.out.println("Yes"); } else { System.out.println("No"); } }} // This code is contributed by Karandeep Singh # Python3 program to check if removing# an edge disconnects a graph or not. # Graph class represents a directed graph# using adjacency list representationclass Graph: def __init__(self, V): self.V = V self.adj = [[] for i in range(V)] def addEdge(self, u, v): self.adj[u].append(v) # Add w to v’s list. self.adj[v].append(u) # Add w to v’s list. def DFS(self, v, visited): # Mark the current node as # visited and print it visited[v] = True # Recur for all the vertices # adjacent to this vertex i = 0 while i != len(self.adj[v]): if (not visited[self.adj[v][i]]): self.DFS(self.adj[v][i], visited) i += 1 # Returns true if given graph is # connected, else false def isConnected(self): visited = [False] * self.V # Find all reachable vertices # from first vertex self.DFS(0, visited) # If set of reachable vertices # includes all, return true. for i in range(1, self.V): if (visited[i] == False): return False return True # This function assumes that edge # (u, v) exists in graph or not, def isBridge(self, u, v): # Remove edge from undirected graph indU = self.adj[v].index(u) indV = self.adj[u].index(v) del self.adj[u][indV] del self.adj[v][indU] res = self.isConnected() # Adding the edge back self.addEdge(u, v) # Return true if graph becomes # disconnected after removing # the edge. return (res == False) # Driver codeif __name__ == '__main__': # Create a graph given in the # above diagram g = Graph(4) g.addEdge(0, 1) g.addEdge(1, 2) g.addEdge(2, 3) if g.isBridge(1, 2): print("Yes") else: print("No") # This code is contributed by PranchalK Output : Yes Time Complexity : O(V + E)This article is contributed by Pankaj Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above PranchalKatiyar karandeep1234 graph-connectivity Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Topological Sorting Detect Cycle in a Directed Graph Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Ford-Fulkerson Algorithm for Maximum Flow Problem Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Detect cycle in an undirected graph Traveling Salesman Problem (TSP) Implementation Longest Path in a Directed Acyclic Graph Find the number of islands | Set 1 (Using DFS) m Coloring Problem | Backtracking-5
[ { "code": null, "e": 26437, "s": 26409, "text": "\n16 Feb, 2022" }, { "code": null, "e": 26659, "s": 26437, "text": "Given an undirected graph and an edge, the task is to find if the given edge is a bridge in graph, i.e., removing the edge disconnects the graph. Following are some example graphs with bridges highlighted with red color. " }, { "code": null, "e": 27407, "s": 26661, "text": "One solution is to find all bridges in given graph and then check if given edge is a bridge or not.A simpler solution is to remove the edge, check if graph remains connect after removal or not, finally add the edge back. We can always find if an undirected is connected or not by finding all reachable vertices from any vertex. If count of reachable vertices is equal to number of vertices in graph, then the graph is connected else not. We can find all reachable vertices either using BFS or DFS. Below are complete steps.1) Remove the given edge 2) Find all reachable vertices from any vertex. We have chosen first vertex in below implementation. 3) If count of reachable nodes is V, then return false [given is not Bridge]. Else return yes. " }, { "code": null, "e": 27411, "s": 27407, "text": "C++" }, { "code": null, "e": 27416, "s": 27411, "text": "Java" }, { "code": null, "e": 27424, "s": 27416, "text": "Python3" }, { "code": "// C++ program to check if removing an// edge disconnects a graph or not.#include<bits/stdc++.h>using namespace std; // Graph class represents a directed graph// using adjacency list representationclass Graph{ int V; // No. of vertices list<int> *adj; void DFS(int v, bool visited[]);public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); // Returns true if graph is connected bool isConnected(); bool isBridge(int u, int v);}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int u, int v){ adj[u].push_back(v); // Add w to v’s list. adj[v].push_back(u); // Add w to v’s list.} void Graph::DFS(int v, bool visited[]){ // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to // this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFS(*i, visited);} // Returns true if given graph is connected, else falsebool Graph::isConnected(){ bool visited[V]; memset(visited, false, sizeof(visited)); // Find all reachable vertices from first vertex DFS(0, visited); // If set of reachable vertices includes all, // return true. for (int i=1; i<V; i++) if (visited[i] == false) return false; return true;} // This function assumes that edge (u, v)// exists in graph or not,bool Graph::isBridge(int u, int v){ // Remove edge from undirected graph adj[u].remove(v); adj[v].remove(u); bool res = isConnected(); // Adding the edge back addEdge(u, v); // Return true if graph becomes disconnected // after removing the edge. return (res == false);} // Driver codeint main(){ // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(1, 2); g.addEdge(2, 3); g.isBridge(1, 2)? cout << \"Yes\" : cout << \"No\"; return 0;}", "e": 29409, "s": 27424, "text": null }, { "code": "// Java program to check if removing an// edge disconnects a graph or not.import java.util.*; // Graph class represents a directed graph// using adjacency list representationclass Graph { int V; // No. of vertices ArrayList<ArrayList<Integer> > adj; private void DFS(int v, boolean[] visited) { // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to // this vertex for (Integer i : adj.get(v)) { if (!visited[i]) { DFS(i, visited); } } } public Graph(int V) { this.V = V; adj = new ArrayList<>(); for (int i = 0; i < V; i++) { adj.add(new ArrayList<>()); } } public void addEdge(int u, int v) { adj.get(u).add(v); // Add v to u’s list. adj.get(v).add(u); // Add u to v’s list. } // Returns true if given graph is connected, else false public boolean isConnected() { boolean[] visited = new boolean[V]; // Find all reachable vertices from first vertex DFS(0, visited); // If set of reachable vertices includes all, // return true. for (int i = 1; i < V; i++) if (visited[i] == false) return false; return true; } // This function assumes that edge (u, v) // exists in graph or not, public boolean isBridge(int u, int v) { // Remove edge from undirected graph adj.get(u).remove(Integer.valueOf(v)); adj.get(v).remove(Integer.valueOf(u)); boolean res = isConnected(); // Adding the edge back addEdge(u, v); // Return true if graph becomes disconnected // after removing the edge. return (res == false); } // Driver code public static void main(String[] args) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(1, 2); g.addEdge(2, 3); if (g.isBridge(1, 2)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } }} // This code is contributed by Karandeep Singh", "e": 31323, "s": 29409, "text": null }, { "code": "# Python3 program to check if removing# an edge disconnects a graph or not. # Graph class represents a directed graph# using adjacency list representationclass Graph: def __init__(self, V): self.V = V self.adj = [[] for i in range(V)] def addEdge(self, u, v): self.adj[u].append(v) # Add w to v’s list. self.adj[v].append(u) # Add w to v’s list. def DFS(self, v, visited): # Mark the current node as # visited and print it visited[v] = True # Recur for all the vertices # adjacent to this vertex i = 0 while i != len(self.adj[v]): if (not visited[self.adj[v][i]]): self.DFS(self.adj[v][i], visited) i += 1 # Returns true if given graph is # connected, else false def isConnected(self): visited = [False] * self.V # Find all reachable vertices # from first vertex self.DFS(0, visited) # If set of reachable vertices # includes all, return true. for i in range(1, self.V): if (visited[i] == False): return False return True # This function assumes that edge # (u, v) exists in graph or not, def isBridge(self, u, v): # Remove edge from undirected graph indU = self.adj[v].index(u) indV = self.adj[u].index(v) del self.adj[u][indV] del self.adj[v][indU] res = self.isConnected() # Adding the edge back self.addEdge(u, v) # Return true if graph becomes # disconnected after removing # the edge. return (res == False) # Driver codeif __name__ == '__main__': # Create a graph given in the # above diagram g = Graph(4) g.addEdge(0, 1) g.addEdge(1, 2) g.addEdge(2, 3) if g.isBridge(1, 2): print(\"Yes\") else: print(\"No\") # This code is contributed by PranchalK", "e": 33293, "s": 31323, "text": null }, { "code": null, "e": 33303, "s": 33293, "text": "Output : " }, { "code": null, "e": 33307, "s": 33303, "text": "Yes" }, { "code": null, "e": 33725, "s": 33307, "text": "Time Complexity : O(V + E)This article is contributed by Pankaj Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 33741, "s": 33725, "text": "PranchalKatiyar" }, { "code": null, "e": 33755, "s": 33741, "text": "karandeep1234" }, { "code": null, "e": 33774, "s": 33755, "text": "graph-connectivity" }, { "code": null, "e": 33780, "s": 33774, "text": "Graph" }, { "code": null, "e": 33786, "s": 33780, "text": "Graph" }, { "code": null, "e": 33884, "s": 33786, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33904, "s": 33884, "text": "Topological Sorting" }, { "code": null, "e": 33937, "s": 33904, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 34005, "s": 33937, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 34055, "s": 34005, "text": "Ford-Fulkerson Algorithm for Maximum Flow Problem" }, { "code": null, "e": 34130, "s": 34055, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 34166, "s": 34130, "text": "Detect cycle in an undirected graph" }, { "code": null, "e": 34214, "s": 34166, "text": "Traveling Salesman Problem (TSP) Implementation" }, { "code": null, "e": 34255, "s": 34214, "text": "Longest Path in a Directed Acyclic Graph" }, { "code": null, "e": 34302, "s": 34255, "text": "Find the number of islands | Set 1 (Using DFS)" } ]
strings.Contains Function in Golang with Examples - GeeksforGeeks
31 Dec, 2021 strings.Contains Function in Golang is used to check the given letters present in the given string or not. If the letter is present in the given string, then it will return true, otherwise, return false. Syntax: func Contains(str, substr string) bool Here, str is the original string and substr is the string that you want to check. Let us discuss this concept with the help of an example: Example 1: Go // Golang program to illustrate// the strings.Contains() Functionpackage main import ( "fmt" "strings") func main() { // using the function fmt.Println(strings.Contains("GeeksforGeeks", "for")) fmt.Println(strings.Contains("A computer science portal", "science")) } Output: true true Explanation: In the above example, we check the presence of sub-string ‘for’ and ‘science’ in different strings. Since strings.Contains() function returns boolean value, it returns true in both the cases. Example 2: Following example illustrates how the user can print the desired result instead of a boolean output: Go // Golang program to illustrate// the strings.Contains() Functionpackage main import ( "fmt" "strings") func main() { input := "Golang" str := "This is a Golang program" if strings.Contains(str, input) { fmt.Println("Yes") }} Output: Yes Explanation: In the above example, we take a sub-string as ‘input’ and the main string as ‘str’. Then, we check if ‘Golang’ is present in the main string. If so, ‘Yes’ is returned as the output as shown above. lxy560zahwm90n5ebjfi8cqx251rqm1qx0yjn4v9 Golang-String Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 6 Best Books to Learn Go Programming Language Arrays in Go Slices in Golang Golang Maps Inheritance in GoLang Different Ways to Find the Type of Variable in Golang Interfaces in Golang How to Trim a String in Golang? How to compare times in Golang? How to Parse JSON in Golang?
[ { "code": null, "e": 25653, "s": 25625, "text": "\n31 Dec, 2021" }, { "code": null, "e": 25857, "s": 25653, "text": "strings.Contains Function in Golang is used to check the given letters present in the given string or not. If the letter is present in the given string, then it will return true, otherwise, return false." }, { "code": null, "e": 25866, "s": 25857, "text": "Syntax: " }, { "code": null, "e": 25905, "s": 25866, "text": "func Contains(str, substr string) bool" }, { "code": null, "e": 26044, "s": 25905, "text": "Here, str is the original string and substr is the string that you want to check. Let us discuss this concept with the help of an example:" }, { "code": null, "e": 26056, "s": 26044, "text": "Example 1: " }, { "code": null, "e": 26059, "s": 26056, "text": "Go" }, { "code": "// Golang program to illustrate// the strings.Contains() Functionpackage main import ( \"fmt\" \"strings\") func main() { // using the function fmt.Println(strings.Contains(\"GeeksforGeeks\", \"for\")) fmt.Println(strings.Contains(\"A computer science portal\", \"science\")) }", "e": 26349, "s": 26059, "text": null }, { "code": null, "e": 26357, "s": 26349, "text": "Output:" }, { "code": null, "e": 26367, "s": 26357, "text": "true\ntrue" }, { "code": null, "e": 26572, "s": 26367, "text": "Explanation: In the above example, we check the presence of sub-string ‘for’ and ‘science’ in different strings. Since strings.Contains() function returns boolean value, it returns true in both the cases." }, { "code": null, "e": 26685, "s": 26572, "text": "Example 2: Following example illustrates how the user can print the desired result instead of a boolean output: " }, { "code": null, "e": 26688, "s": 26685, "text": "Go" }, { "code": "// Golang program to illustrate// the strings.Contains() Functionpackage main import ( \"fmt\" \"strings\") func main() { input := \"Golang\" str := \"This is a Golang program\" if strings.Contains(str, input) { fmt.Println(\"Yes\") }}", "e": 26949, "s": 26688, "text": null }, { "code": null, "e": 26958, "s": 26949, "text": "Output: " }, { "code": null, "e": 26962, "s": 26958, "text": "Yes" }, { "code": null, "e": 27173, "s": 26962, "text": "Explanation: In the above example, we take a sub-string as ‘input’ and the main string as ‘str’. Then, we check if ‘Golang’ is present in the main string. If so, ‘Yes’ is returned as the output as shown above. " }, { "code": null, "e": 27214, "s": 27173, "text": "lxy560zahwm90n5ebjfi8cqx251rqm1qx0yjn4v9" }, { "code": null, "e": 27228, "s": 27214, "text": "Golang-String" }, { "code": null, "e": 27235, "s": 27228, "text": "Picked" }, { "code": null, "e": 27247, "s": 27235, "text": "Go Language" }, { "code": null, "e": 27345, "s": 27247, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27391, "s": 27345, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 27404, "s": 27391, "text": "Arrays in Go" }, { "code": null, "e": 27421, "s": 27404, "text": "Slices in Golang" }, { "code": null, "e": 27433, "s": 27421, "text": "Golang Maps" }, { "code": null, "e": 27455, "s": 27433, "text": "Inheritance in GoLang" }, { "code": null, "e": 27509, "s": 27455, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 27530, "s": 27509, "text": "Interfaces in Golang" }, { "code": null, "e": 27562, "s": 27530, "text": "How to Trim a String in Golang?" }, { "code": null, "e": 27594, "s": 27562, "text": "How to compare times in Golang?" } ]
Chi-Square Test in R - GeeksforGeeks
30 Jun, 2020 The chi-square test of independence evaluates whether there is an association between the categories of the two variables. There are basically two types of random variables and they yield two types of data: numerical and categorical. Chi-square statistics is used to investigate whether distributions of categorical variables differ from one another. Chi-square test is also useful while comparing the tallies or counts of categorical responses between two(or more) independent groups. In R, the function used for performing a chi-square test is chisq.test(). Syntax:chisq.test(data) Parameters:data: data is a table containing count values of the variables in the table. ExampleWe will take the survey data in the MASS library which represents the data from a survey conducted on students. # load the MASS packagelibrary(MASS) print(str(survey)) Output: 'data.frame': 237 obs. of 12 variables: $ Sex : Factor w/ 2 levels "Female","Male": 1 2 2 2 2 1 2 1 2 2 ... $ Wr.Hnd: num 18.5 19.5 18 18.8 20 18 17.7 17 20 18.5 ... $ NW.Hnd: num 18 20.5 13.3 18.9 20 17.7 17.7 17.3 19.5 18.5 ... $ W.Hnd : Factor w/ 2 levels "Left","Right": 2 1 2 2 2 2 2 2 2 2 ... $ Fold : Factor w/ 3 levels "L on R","Neither",..: 3 3 1 3 2 1 1 3 3 3 ... $ Pulse : int 92 104 87 NA 35 64 83 74 72 90 ... $ Clap : Factor w/ 3 levels "Left","Neither",..: 1 1 2 2 3 3 3 3 3 3 ... $ Exer : Factor w/ 3 levels "Freq","None",..: 3 2 2 2 3 3 1 1 3 3 ... $ Smoke : Factor w/ 4 levels "Heavy","Never",..: 2 4 3 2 2 2 2 2 2 2 ... $ Height: num 173 178 NA 160 165 ... $ M.I : Factor w/ 2 levels "Imperial","Metric": 2 1 NA 2 2 1 1 2 2 2 ... $ Age : num 18.2 17.6 16.9 20.3 23.7 ... NULL The above result shows the dataset has many Factor variables which can be considered as categorical variables. For our model, we will consider the variables “Exer” and “Smoke“.The Smoke column records the students smoking habits while the Exer column records their exercise level. Our aim is to test the hypothesis whether the students smoking habit is independent of their exercise level at .05 significance level. # Create a data frame from the main data set.stu_data = data.frame(survey$Smoke,survey$Exer) # Create a contingency table with the needed variables. stu_data = table(survey$Smoke,survey$Exer) print(stu_data) Output: Freq None Some Heavy 7 1 3 Never 87 18 84 Occas 12 3 4 Regul 9 1 7 And finally we apply the chisq.test() function to the contingency table stu_data. # applying chisq.test() functionprint(chisq.test(stu_data)) Output: Pearson's Chi-squared test data: stu_data X-squared = 5.4885, df = 6, p-value = 0.4828 As the p-value 0.4828 is greater than the .05, we conclude that the smoking habit is independent of the exercise level of the student and hence there is a weak or no correlation between the two variables. The complete R code is given below. # R program to illustrate# Chi-Square Test in R library(MASS)print(str(survey)) stu_data = data.frame(survey$Smoke,survey$Exer) stu_data = table(survey$Smoke,survey$Exer) print(stu_data) print(chisq.test(stu_data)) So, in summary, it can be said that it is very easy to perform a Chi-square test using R. One can perform this task using chisq.test() function in R. Picked 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 R - if statement Logistic Regression in R Programming
[ { "code": null, "e": 26487, "s": 26459, "text": "\n30 Jun, 2020" }, { "code": null, "e": 26973, "s": 26487, "text": "The chi-square test of independence evaluates whether there is an association between the categories of the two variables. There are basically two types of random variables and they yield two types of data: numerical and categorical. Chi-square statistics is used to investigate whether distributions of categorical variables differ from one another. Chi-square test is also useful while comparing the tallies or counts of categorical responses between two(or more) independent groups." }, { "code": null, "e": 27047, "s": 26973, "text": "In R, the function used for performing a chi-square test is chisq.test()." }, { "code": null, "e": 27071, "s": 27047, "text": "Syntax:chisq.test(data)" }, { "code": null, "e": 27159, "s": 27071, "text": "Parameters:data: data is a table containing count values of the variables in the table." }, { "code": null, "e": 27278, "s": 27159, "text": "ExampleWe will take the survey data in the MASS library which represents the data from a survey conducted on students." }, { "code": "# load the MASS packagelibrary(MASS) print(str(survey))", "e": 27341, "s": 27278, "text": null }, { "code": null, "e": 27349, "s": 27341, "text": "Output:" }, { "code": null, "e": 28175, "s": 27349, "text": "'data.frame': 237 obs. of 12 variables:\n $ Sex : Factor w/ 2 levels \"Female\",\"Male\": 1 2 2 2 2 1 2 1 2 2 ...\n $ Wr.Hnd: num 18.5 19.5 18 18.8 20 18 17.7 17 20 18.5 ...\n $ NW.Hnd: num 18 20.5 13.3 18.9 20 17.7 17.7 17.3 19.5 18.5 ...\n $ W.Hnd : Factor w/ 2 levels \"Left\",\"Right\": 2 1 2 2 2 2 2 2 2 2 ...\n $ Fold : Factor w/ 3 levels \"L on R\",\"Neither\",..: 3 3 1 3 2 1 1 3 3 3 ...\n $ Pulse : int 92 104 87 NA 35 64 83 74 72 90 ...\n $ Clap : Factor w/ 3 levels \"Left\",\"Neither\",..: 1 1 2 2 3 3 3 3 3 3 ...\n $ Exer : Factor w/ 3 levels \"Freq\",\"None\",..: 3 2 2 2 3 3 1 1 3 3 ...\n $ Smoke : Factor w/ 4 levels \"Heavy\",\"Never\",..: 2 4 3 2 2 2 2 2 2 2 ...\n $ Height: num 173 178 NA 160 165 ...\n $ M.I : Factor w/ 2 levels \"Imperial\",\"Metric\": 2 1 NA 2 2 1 1 2 2 2 ...\n $ Age : num 18.2 17.6 16.9 20.3 23.7 ...\nNULL\n" }, { "code": null, "e": 28591, "s": 28175, "text": "The above result shows the dataset has many Factor variables which can be considered as categorical variables. For our model, we will consider the variables “Exer” and “Smoke“.The Smoke column records the students smoking habits while the Exer column records their exercise level. Our aim is to test the hypothesis whether the students smoking habit is independent of their exercise level at .05 significance level." }, { "code": "# Create a data frame from the main data set.stu_data = data.frame(survey$Smoke,survey$Exer) # Create a contingency table with the needed variables. stu_data = table(survey$Smoke,survey$Exer) print(stu_data)", "e": 28828, "s": 28591, "text": null }, { "code": null, "e": 28836, "s": 28828, "text": "Output:" }, { "code": null, "e": 28953, "s": 28836, "text": " Freq None Some\n Heavy 7 1 3\n Never 87 18 84\n Occas 12 3 4\n Regul 9 1 7\n" }, { "code": null, "e": 29035, "s": 28953, "text": "And finally we apply the chisq.test() function to the contingency table stu_data." }, { "code": "# applying chisq.test() functionprint(chisq.test(stu_data))", "e": 29095, "s": 29035, "text": null }, { "code": null, "e": 29103, "s": 29095, "text": "Output:" }, { "code": null, "e": 29200, "s": 29103, "text": " Pearson's Chi-squared test\n\ndata: stu_data\nX-squared = 5.4885, df = 6, p-value = 0.4828\n" }, { "code": null, "e": 29405, "s": 29200, "text": "As the p-value 0.4828 is greater than the .05, we conclude that the smoking habit is independent of the exercise level of the student and hence there is a weak or no correlation between the two variables." }, { "code": null, "e": 29441, "s": 29405, "text": "The complete R code is given below." }, { "code": "# R program to illustrate# Chi-Square Test in R library(MASS)print(str(survey)) stu_data = data.frame(survey$Smoke,survey$Exer) stu_data = table(survey$Smoke,survey$Exer) print(stu_data) print(chisq.test(stu_data))", "e": 29684, "s": 29441, "text": null }, { "code": null, "e": 29834, "s": 29684, "text": "So, in summary, it can be said that it is very easy to perform a Chi-square test using R. One can perform this task using chisq.test() function in R." }, { "code": null, "e": 29841, "s": 29834, "text": "Picked" }, { "code": null, "e": 29852, "s": 29841, "text": "R Language" }, { "code": null, "e": 29950, "s": 29852, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30002, "s": 29950, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30037, "s": 30002, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 30075, "s": 30037, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30133, "s": 30075, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30176, "s": 30133, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30213, "s": 30176, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 30262, "s": 30213, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30288, "s": 30262, "text": "Time Series Analysis in R" }, { "code": null, "e": 30305, "s": 30288, "text": "R - if statement" } ]
C# - Reading Lines From a File Until the End of File is Reached - GeeksforGeeks
27 Dec, 2021 Given a file, now our task is to read lines from the file until the end of the file using C#. Before reading the lines from a file we must have some data, so first we need an empty file in our path and then insert lines in our file and then we read lines from a file. So to do this task we use two basic operations that are reading and writing. The file becomes a stream when we open the file for writing and reading, here the stream means a sequence of bytes that is used for communication. So to our task, we use: Path: For reading a file from any source we have to need the location/path. A Path is a string that includes a file path in a system. @"c:\folder\file_name.txt" We will check if the file exists in the path or not by using File.Exists(path) method StreamWriter: StreamWriter is used to write a stream of data/lines to a file. StreamWriter sw = new StreamWriter(myfilepath) StreamReader: StreamReader is used to read a stream of data/lines from a file. StreamReader sr = new StreamReader(myfilepath) Peek: Used to read the data/lines from the file till the end of the file. StreamReaderObject.Peek() So all are placed in try() block to catch the exceptions that occur. Example: Consider the path and file are: C# // C# program to read lines from a file// until the end of file is reachedusing System;using System.IO; class GFG{ public static void Main(){ // File name is data // File path is the following path string myfilepath = @"c:\sravan\data.txt"; try { // Check if file exists or not if (File.Exists(path)) { File.Delete(path); } // Write data into file using StreamWriter through the path using (StreamWriter sw = new StreamWriter(myfilepath)) { sw.WriteLine("hello"); sw.WriteLine("geeks for geeks"); sw.WriteLine("welcome to c#"); } // Read the file present in the path using (StreamReader sr = new StreamReader(myfilepath)) { // Iterating the file while (sr.Peek() >= 0) { // Read the data in the file until the peak Console.WriteLine(sr.ReadLine()); } } } // Caught the exception catch (Exception e) { Console.WriteLine("The process failed: {0}", e.ToString()); } Console.Read();} Output: hello geeks for geeks welcome to c# See the file data is inserted: rajeev0719singh CSharp-File-Handling Picked C# C# Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Convert String to Character Array in C# Program to Print a New Line in C# Getting a Month Name Using Month Number in C# Socket Programming in C# C# Program for Dijkstra's shortest path algorithm | Greedy Algo-7
[ { "code": null, "e": 25547, "s": 25519, "text": "\n27 Dec, 2021" }, { "code": null, "e": 26063, "s": 25547, "text": "Given a file, now our task is to read lines from the file until the end of the file using C#. Before reading the lines from a file we must have some data, so first we need an empty file in our path and then insert lines in our file and then we read lines from a file. So to do this task we use two basic operations that are reading and writing. The file becomes a stream when we open the file for writing and reading, here the stream means a sequence of bytes that is used for communication. So to our task, we use:" }, { "code": null, "e": 26197, "s": 26063, "text": "Path: For reading a file from any source we have to need the location/path. A Path is a string that includes a file path in a system." }, { "code": null, "e": 26225, "s": 26197, "text": " @\"c:\\folder\\file_name.txt\"" }, { "code": null, "e": 26311, "s": 26225, "text": "We will check if the file exists in the path or not by using File.Exists(path) method" }, { "code": null, "e": 26389, "s": 26311, "text": "StreamWriter: StreamWriter is used to write a stream of data/lines to a file." }, { "code": null, "e": 26436, "s": 26389, "text": "StreamWriter sw = new StreamWriter(myfilepath)" }, { "code": null, "e": 26515, "s": 26436, "text": "StreamReader: StreamReader is used to read a stream of data/lines from a file." }, { "code": null, "e": 26562, "s": 26515, "text": "StreamReader sr = new StreamReader(myfilepath)" }, { "code": null, "e": 26636, "s": 26562, "text": "Peek: Used to read the data/lines from the file till the end of the file." }, { "code": null, "e": 26662, "s": 26636, "text": "StreamReaderObject.Peek()" }, { "code": null, "e": 26731, "s": 26662, "text": "So all are placed in try() block to catch the exceptions that occur." }, { "code": null, "e": 26773, "s": 26731, "text": "Example: Consider the path and file are: " }, { "code": null, "e": 26776, "s": 26773, "text": "C#" }, { "code": "// C# program to read lines from a file// until the end of file is reachedusing System;using System.IO; class GFG{ public static void Main(){ // File name is data // File path is the following path string myfilepath = @\"c:\\sravan\\data.txt\"; try { // Check if file exists or not if (File.Exists(path)) { File.Delete(path); } // Write data into file using StreamWriter through the path using (StreamWriter sw = new StreamWriter(myfilepath)) { sw.WriteLine(\"hello\"); sw.WriteLine(\"geeks for geeks\"); sw.WriteLine(\"welcome to c#\"); } // Read the file present in the path using (StreamReader sr = new StreamReader(myfilepath)) { // Iterating the file while (sr.Peek() >= 0) { // Read the data in the file until the peak Console.WriteLine(sr.ReadLine()); } } } // Caught the exception catch (Exception e) { Console.WriteLine(\"The process failed: {0}\", e.ToString()); } Console.Read();}", "e": 27979, "s": 26776, "text": null }, { "code": null, "e": 27987, "s": 27979, "text": "Output:" }, { "code": null, "e": 28023, "s": 27987, "text": "hello\ngeeks for geeks\nwelcome to c#" }, { "code": null, "e": 28054, "s": 28023, "text": "See the file data is inserted:" }, { "code": null, "e": 28072, "s": 28056, "text": "rajeev0719singh" }, { "code": null, "e": 28093, "s": 28072, "text": "CSharp-File-Handling" }, { "code": null, "e": 28100, "s": 28093, "text": "Picked" }, { "code": null, "e": 28103, "s": 28100, "text": "C#" }, { "code": null, "e": 28115, "s": 28103, "text": "C# Programs" }, { "code": null, "e": 28213, "s": 28115, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28236, "s": 28213, "text": "Extension Method in C#" }, { "code": null, "e": 28264, "s": 28236, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28281, "s": 28264, "text": "C# | Inheritance" }, { "code": null, "e": 28303, "s": 28281, "text": "Partial Classes in C#" }, { "code": null, "e": 28332, "s": 28303, "text": "C# | Generics - Introduction" }, { "code": null, "e": 28372, "s": 28332, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 28406, "s": 28372, "text": "Program to Print a New Line in C#" }, { "code": null, "e": 28452, "s": 28406, "text": "Getting a Month Name Using Month Number in C#" }, { "code": null, "e": 28477, "s": 28452, "text": "Socket Programming in C#" } ]
Word Break Problem | DP-32 - GeeksforGeeks
20 Apr, 2022 Given an input string and a dictionary of words, find out if the input string can be segmented into a space-separated sequence of dictionary words. See following examples for more details. This is a famous Google interview question, also being asked by many other companies now a days. Consider the following dictionary { i, like, sam, sung, samsung, mobile, ice, cream, icecream, man, go, mango} Input: ilike Output: Yes The string can be segmented as "i like". Input: ilikesamsung Output: Yes The string can be segmented as "i like samsung" or "i like sam sung". Recursive implementation: The idea is simple, we consider each prefix and search it in dictionary. If the prefix is present in dictionary, we recur for rest of the string (or suffix). Python3 def wordBreak(wordList, word): if word == '': return True else: wordLen = len(word) return any([(word[:i] in wordList) and wordBreak(wordList, word[i:]) for i in range(1, wordLen+1)]) If the recursive call for suffix returns true, we return true, otherwise we try next prefix. If we have tried all prefixes and none of them resulted in a solution, we return false.We strongly recommend to see substr function which is used extensively in following implementations. C++ Java Python3 Javascript // A recursive program to test whether a given// string can be segmented into space separated// words in dictionary#include <iostream>using namespace std; /* A utility function to check whether a word is present in dictionary or not. An array of strings is used for dictionary. Using array of strings for dictionary is definitely not a good idea. We have used for simplicity of the program*/int dictionaryContains(string word){ string dictionary[] = {"mobile","samsung","sam","sung", "man","mango","icecream","and", "go","i","like","ice","cream"}; int size = sizeof(dictionary)/sizeof(dictionary[0]); for (int i = 0; i < size; i++) if (dictionary[i].compare(word) == 0) return true; return false;} // returns true if string can be segmented into space// separated words, otherwise returns falsebool wordBreak(string str){ int size = str.size(); // Base case if (size == 0) return true; // Try all prefixes of lengths from 1 to size for (int i=1; i<=size; i++) { // The parameter for dictionaryContains is // str.substr(0, i) which is prefix (of input // string) of length 'i'. We first check whether // current prefix is in dictionary. Then we // recursively check for remaining string // str.substr(i, size-i) which is suffix of // length size-i if (dictionaryContains( str.substr(0, i) ) && wordBreak( str.substr(i, size-i) )) return true; } // If we have tried all prefixes and // none of them worked return false;} // Driver program to test above functionsint main(){ wordBreak("ilikesamsung")? cout <<"Yes\n": cout << "No\n"; wordBreak("iiiiiiii")? cout <<"Yes\n": cout << "No\n"; wordBreak("")? cout <<"Yes\n": cout << "No\n"; wordBreak("ilikelikeimangoiii")? cout <<"Yes\n": cout << "No\n"; wordBreak("samsungandmango")? cout <<"Yes\n": cout << "No\n"; wordBreak("samsungandmangok")? cout <<"Yes\n": cout << "No\n"; return 0;} import java.util.*; // Recursive implementation of// word break problem in javapublic class WordBreakProblem{ // set to hold dictionary values private static Set<String> dictionary = new HashSet<>(); public static void main(String []args) { // array of strings to be added in dictionary set. String temp_dictionary[] = {"mobile","samsung","sam","sung", "man","mango","icecream","and", "go","i","like","ice","cream"}; // loop to add all strings in dictionary set for (String temp :temp_dictionary) { dictionary.add(temp); } // sample input cases System.out.println(wordBreak("ilikesamsung")); System.out.println(wordBreak("iiiiiiii")); System.out.println(wordBreak("")); System.out.println(wordBreak("ilikelikeimangoiii")); System.out.println(wordBreak("samsungandmango")); System.out.println(wordBreak("samsungandmangok")); } // returns true if the word can be segmented into parts such // that each part is contained in dictionary public static boolean wordBreak(String word) { int size = word.length(); // base case if (size == 0) return true; //else check for all words for (int i = 1; i <= size; i++) { // Now we will first divide the word into two parts , // the prefix will have a length of i and check if it is // present in dictionary ,if yes then we will check for // suffix of length size-i recursively. if both prefix and // suffix are present the word is found in dictionary. if (dictionary.contains(word.substring(0,i)) && wordBreak(word.substring(i,size))) return true; } // if all cases failed then return false return false; }} // This code is contributed by Sparsh Singhal # Recursive implementation of# word break problem in Python # returns True if the word can be segmented into parts such# that each part is contained in dictionarydef wordBreak(word): global dictionary size = len(word) # base case if (size == 0): return True # else check for all words for i in range(1,size + 1): # Now we will first divide the word into two parts , # the prefix will have a length of i and check if it is # present in dictionary ,if yes then we will check for # suffix of length size-i recursively. if both prefix and # suffix are present the word is found in dictionary. if (word[0:i] in dictionary and wordBreak(word[i: size])): return True # if all cases failed then return False return False # set to hold dictionary valuesdictionary = set() # array of strings to be added in dictionary set.temp_dictionary = [ "mobile", "samsung", "sam", "sung", "man", "mango", "icecream", "and", "go", "i","like", "ice", "cream" ] # loop to add all strings in dictionary setfor temp in temp_dictionary: dictionary.add(temp) # sample input casesprint("Yes" if wordBreak("ilikesamsung") else "No")print("Yes" if wordBreak("iiiiiiii") else "No")print("Yes" if wordBreak("") else "No")print("Yes" if wordBreak("ilikelikeimangoiii") else "No")print("Yes" if wordBreak("samsungandmango") else "No")print("Yes" if wordBreak("samsungandmangok") else "No") # This code is contributed by shinjanpatra <script>// Recursive implementation of// word break problem in java // set to hold dictionary values var dictionary = new Set(); // array of strings to be added in dictionary set. var temp_dictionary = [ "mobile", "samsung", "sam", "sung", "man", "mango", "icecream", "and", "go", "i", "like", "ice", "cream" ]; // loop to add all strings in dictionary set for (var temp of temp_dictionary) { dictionary.add(temp); } // sample input cases document.write(((wordBreak("ilikesamsung"))?"Yes":"No")+"<br/>"); document.write(((wordBreak("iiiiiiii"))?"Yes":"No")+"<br/>"); document.write(((wordBreak(""))?"Yes":"No")+"<br/>"); document.write(((wordBreak("ilikelikeimangoiii"))?"Yes":"No")+"<br/>"); document.write(((wordBreak("samsungandmango"))?"Yes":"No")+"<br/>"); document.write(((wordBreak("samsungandmangok"))?"Yes":"No")+"<br/>"); // returns true if the word can be segmented into parts such // that each part is contained in dictionary function wordBreak( word) { var size = word.length; // base case if (size == 0) return true; // else check for all words for (var i = 1; i <= size; i++) { // Now we will first divide the word into two parts , // the prefix will have a length of i and check if it is // present in dictionary ,if yes then we will check for // suffix of length size-i recursively. if both prefix and // suffix are present the word is found in dictionary. if (dictionary.has(word.substring(0, i)) && wordBreak(word.substring(i, size))) return true; } // if all cases failed then return false return false;} // This code is contributed by Rajput-Ji</script> Yes Yes Yes Yes Yes No Dynamic Programming Why Dynamic Programming? The above problem exhibits overlapping sub-problems. For example, see the following partial recursion tree for string “abcde” in worst case. CPP Java Javascript // A Dynamic Programming based program to test whether a given string can// be segmented into space separated words in dictionary#include <iostream>#include <string.h>using namespace std; /* A utility function to check whether a word is present in dictionary or not. An array of strings is used for dictionary. Using array of strings for dictionary is definitely not a good idea. We have used for simplicity of the program*/int dictionaryContains(string word){ string dictionary[] = {"mobile","samsung","sam","sung","man","mango", "icecream","and","go","i","like","ice","cream"}; int size = sizeof(dictionary)/sizeof(dictionary[0]); for (int i = 0; i < size; i++) if (dictionary[i].compare(word) == 0) return true; return false;} // Returns true if string can be segmented into space separated// words, otherwise returns falsebool wordBreak(string str){ int size = str.size(); if (size == 0) return true; // Create the DP table to store results of subproblems. The value wb[i] // will be true if str[0..i-1] can be segmented into dictionary words, // otherwise false. bool wb[size+1]; memset(wb, 0, sizeof(wb)); // Initialize all values as false. for (int i=1; i<=size; i++) { // if wb[i] is false, then check if current prefix can make it true. // Current prefix is "str.substr(0, i)" if (wb[i] == false && dictionaryContains( str.substr(0, i) )) wb[i] = true; // wb[i] is true, then check for all substrings starting from // (i+1)th character and store their results. if (wb[i] == true) { // If we reached the last prefix if (i == size) return true; for (int j = i+1; j <= size; j++) { // Update wb[j] if it is false and can be updated // Note the parameter passed to dictionaryContains() is // substring starting from index 'i' and length 'j-i' if (wb[j] == false && dictionaryContains( str.substr(i, j-i) )) wb[j] = true; // If we reached the last character if (j == size && wb[j] == true) return true; } } } /* Uncomment these lines to print DP table "wb[]" for (int i = 1; i <= size; i++) cout << " " << wb[i]; */ // If we have tried all prefixes and none of them worked return false;} // Driver program to test above functionsint main(){ wordBreak("ilikesamsung")? cout <<"Yes\n": cout << "No\n"; wordBreak("iiiiiiii")? cout <<"Yes\n": cout << "No\n"; wordBreak("")? cout <<"Yes\n": cout << "No\n"; wordBreak("ilikelikeimangoiii")? cout <<"Yes\n": cout << "No\n"; wordBreak("samsungandmango")? cout <<"Yes\n": cout << "No\n"; wordBreak("samsungandmangok")? cout <<"Yes\n": cout << "No\n"; return 0;} // A Dynamic Programming based program to test whether a given String can// be segmented into space separated words in dictionaryimport java.util.*; class GFG{ /* A utility function to check whether a word is present in dictionary or not. An array of Strings is used for dictionary. Using array of Strings for dictionary is definitely not a good idea. We have used for simplicity of the program*/static boolean dictionaryContains(String word){ String dictionary[] = {"mobile","samsung","sam","sung","man","mango", "icecream","and","go","i","like","ice","cream"}; int size = dictionary.length; for (int i = 0; i < size; i++) if (dictionary[i].compareTo(word) == 0) return true; return false;} // Returns true if String can be segmented into space separated// words, otherwise returns falsestatic boolean wordBreak(String str){ int size = str.length(); if (size == 0) return true; // Create the DP table to store results of subproblems. The value wb[i] // will be true if str[0..i-1] can be segmented into dictionary words, // otherwise false. boolean []wb = new boolean[size+1]; for (int i=1; i<=size; i++) { // if wb[i] is false, then check if current prefix can make it true. // Current prefix is "str.substring(0, i)" if (wb[i] == false && dictionaryContains( str.substring(0, i) )) wb[i] = true; // wb[i] is true, then check for all subStrings starting from // (i+1)th character and store their results. if (wb[i] == true) { // If we reached the last prefix if (i == size) return true; for (int j = i+1; j <= size; j++) { // Update wb[j] if it is false and can be updated // Note the parameter passed to dictionaryContains() is // subString starting from index 'i' and length 'j-i' if (wb[j] == false && dictionaryContains( str.substring(i, j) )) wb[j] = true; // If we reached the last character if (j == size && wb[j] == true) return true; } } } /* Uncomment these lines to print DP table "wb[]" for (int i = 1; i <= size; i++) System.out.print(" " + wb[i]; */ // If we have tried all prefixes and none of them worked return false;} // Driver program to test above functionspublic static void main(String[] args){ if(wordBreak("ilikesamsung")) System.out.print("Yes\n"); else System.out.print("No\n"); if(wordBreak("iiiiiiii")) System.out.print("Yes\n"); else System.out.print("No\n"); if(wordBreak("")) System.out.print("Yes\n"); else System.out.print("No\n"); if(wordBreak("ilikelikeimangoiii")) System.out.print("Yes\n"); else System.out.print("No\n"); if(wordBreak("samsungandmango")) System.out.print("Yes\n"); else System.out.print("No\n"); if(wordBreak("samsungandmangok")) System.out.print("Yes\n"); else System.out.print("No\n"); }} // This code is contributed by Rajput-Ji <script>// A Dynamic Programming based program to test whether a given String can// be segmented into space separated words in dictionary /* * A utility function to check whether a word is present in dictionary or not. * An array of Strings is used for dictionary. Using array of Strings for * dictionary is definitely not a good idea. We have used for simplicity of the * program */ function dictionaryContains( word) { var dictionary = [ "mobile", "samsung", "sam", "sung", "man", "mango", "icecream", "and", "go", "i", "like", "ice", "cream" ]; var size = dictionary.length; for (var i = 0; i < size; i++) if (dictionary[i]===(word)) return true; return false; } // Returns true if String can be segmented into space separated // words, otherwise returns false function wordBreak( str) { var size = str.length; if (size == 0) return true; // Create the DP table to store results of subproblems. The value wb[i] // will be true if str[0..i-1] can be segmented into dictionary words, // otherwise false. var wb = Array(size + 1).fill(false); for (var i = 1; i <= size; i++) { // if wb[i] is false, then check if current prefix can make it true. // Current prefix is "str.substring(0, i)" if (wb[i] == false && dictionaryContains(str.substring(0, i))) wb[i] = true; // wb[i] is true, then check for all subStrings starting from // (i+1)th character and store their results. if (wb[i] == true) { // If we reached the last prefix if (i == size) return true; for (j = i + 1; j <= size; j++) { // Update wb[j] if it is false and can be updated // Note the parameter passed to dictionaryContains() is // subString starting from index 'i' and length 'j-i' if (wb[j] == false && dictionaryContains(str.substring(i, j))) wb[j] = true; // If we reached the last character if (j == size && wb[j] == true) return true; } } } /* * Uncomment these lines to print DP table "wb" for (i = 1; i <= size; * i++) document.write(" " + wb[i]; */ // If we have tried all prefixes and none of them worked return false; } // Driver program to test above functions if (wordBreak("ilikesamsung")) document.write("Yes<br/>"); else document.write("No<br/>"); if (wordBreak("iiiiiiii")) document.write("Yes<br/>"); else document.write("No<br/>"); if (wordBreak("")) document.write("Yes<br/>"); else document.write("No<br/>"); if (wordBreak("ilikelikeimangoiii")) document.write("Yes<br/>"); else document.write("No<br/>"); if (wordBreak("samsungandmango")) document.write("Yes<br/>"); else document.write("No<br/>"); if (wordBreak("samsungandmangok")) document.write("Yes<br/>"); else document.write("No<br/>"); // This code contributed by Rajput-Ji</script> Yes Yes Yes Yes Yes No Optimized Dynamic Programming: In this approach, apart from the dp table, we also maintain all the indexes which have matched earlier. Then we will check the substrings from those indexes to the current index. If anyone of that matches then we can divide the string up to that index.In this program, we are using some extra space. However, its time complexity is O(n*s) where s is the length of the largest string in the dictionary and n is the length of the given string. CPP Java Python3 Javascript // A Dynamic Programming based program to test// whether a given string can be segmented into// space separated words in dictionary#include <bits/stdc++.h>using namespace std; /* A utility function to check whether a word is present in dictionary or not. An array of strings is used for dictionary. Using array of strings for dictionary is definitely not a good idea. We have used for simplicity of the program*/int dictionaryContains(string word){ string dictionary[] = { "mobile", "samsung", "sam", "sung", "man", "mango", "icecream", "and", "go", "i", "like", "ice", "cream" }; int size = sizeof(dictionary) / sizeof(dictionary[0]); for (int i = 0; i < size; i++) if (dictionary[i].compare(word) == 0) return true; return false;} // Returns true if string can be segmented into space// separated words, otherwise returns falsebool wordBreak(string s){ int n = s.size(); if (n == 0) return true; // Create the DP table to store results of subproblems. // The value dp[i] will be true if str[0..i] can be // segmented into dictionary words, otherwise false. vector<bool> dp(n + 1, 0); // Initialize all values // as false. // matched_index array represents the indexes for which // dp[i] is true. Initially only -1 element is present // in this array. vector<int> matched_index; matched_index.push_back(-1); for (int i = 0; i < n; i++) { int msize = matched_index.size(); // Flag value which tells that a substring matches // with given words or not. int f = 0; // Check all the substring from the indexes matched // earlier. If any of that substring matches than // make flag value = 1; for (int j = msize - 1; j >= 0; j--) { // sb is substring starting from // matched_index[j] // + 1 and of length i - matched_index[j] string sb = s.substr(matched_index[j] + 1, i - matched_index[j]); if (dictionaryContains(sb)) { f = 1; break; } } // If substring matches than do dp[i] = 1 and // push that index in matched_index array. if (f == 1) { dp[i] = 1; matched_index.push_back(i); } } return dp[n - 1];} // Driver codeint main(){ wordBreak("ilikesamsung") ? cout << "Yes\n" : cout << "No\n"; wordBreak("iiiiiiii") ? cout << "Yes\n" : cout << "No\n"; wordBreak("") ? cout << "Yes\n" : cout << "No\n"; wordBreak("ilikelikeimangoiii") ? cout << "Yes\n" : cout << "No\n"; wordBreak("samsungandmango") ? cout << "Yes\n" : cout << "No\n"; wordBreak("samsungandmangok") ? cout << "Yes\n" : cout << "No\n"; return 0;} import java.io.*;import java.util.*; class GFG { public static boolean wordBreak(String s, List<String> dictionary) { // create a dp table to store results of subproblems // value of dp[i] will be true if string s can be segmented // into dictionary words from 0 to i. boolean[] dp = new boolean[s.length() + 1]; // dp[0] is true because an empty string can always be segmented. dp[0] = true; for(int i = 0; i <= s.length(); i++){ for(int j = 0; j < i; j++){ if(dp[j] && dictionary.contains(s.substring(j, i))){ dp[i] = true; break; } } } return dp[s.length()]; } public static void main (String[] args) { String[] dictionary = { "mobile", "samsung", "sam", "sung", "man", "mango", "icecream", "and", "go", "i", "like", "ice", "cream" }; List<String> dict = new ArrayList<>(); for(String s : dictionary){ dict.add(s); } if (wordBreak("ilikesamsung", dict)) { System.out.println("Yes"); } else { System.out.println("No"); } if (wordBreak("iiiiiiii", dict)) { System.out.println("Yes"); } else { System.out.println("No"); } if (wordBreak("", dict)) { System.out.println("Yes"); } else { System.out.println("No"); } if (wordBreak("samsungandmango", dict)) { System.out.println("Yes"); } else { System.out.println("No"); } if (wordBreak("ilikesamsung", dict)) { System.out.println("Yes"); } else { System.out.println("No"); } if (wordBreak("samsungandmangok", dict)) { System.out.println("Yes"); } else { System.out.println("No"); } }} def wordBreak(s, dictionary): # create a dp table to store results of subproblems # value of dp[i] will be true if string s can be segmented # into dictionary words from 0 to i. dp = [False for i in range(len(s) + 1)] # dp[0] is true because an empty string can always be segmented. dp[0] = True for i in range(len(s) + 1): for j in range(i): if dp[j] and s[j: i] in dictionary: dp[i] = True break return dp[len(s)] # driver codedictionary = [ "mobile", "samsung", "sam", "sung", "man", "mango", "icecream", "and", "go", "i", "like", "ice", "cream" ] dict = set()for s in dictionary: dict.add(s) if (wordBreak("ilikesamsung", dict)): print("Yes")else : print("No") if (wordBreak("iiiiiiii", dict)): print("Yes")else: print("No") if (wordBreak("", dict)): print("Yes")else: print("No") if (wordBreak("samsungandmango", dict)): print("Yes")else: print("No") if (wordBreak("ilikesamsung", dict)): print("Yes")else: print("No") if (wordBreak("samsungandmangok", dict)): print("Yes")else: print("No") # This code is contributed by shinjanpatra <script> function wordBreak( s, dictionary) { // create a dp table to store results of subproblems // value of dp[i] will be true if string s can be segmented // into dictionary words from 0 to i. var dp = Array(s.length + 1).fill(false); // dp[0] is true because an empty string can always be segmented. dp[0] = true; for (var i = 0; i <= s.length; i++) { for (var j = 0; j < i; j++) { if (dp[j] && dictionary.has(s.substring(j, i))) { dp[i] = true; break; } } } return dp[s.length]; } var dictionary = [ "mobile", "samsung", "sam", "sung", "man", "mango", "icecream", "and", "go", "i", "like", "ice", "cream" ]; var dict = new Set(); for (var s of dictionary) { dict.add(s); } if (wordBreak("ilikesamsung", dict)) { document.write("<br/>Yes"); } else { document.write("<br/>No"); } if (wordBreak("iiiiiiii", dict)) { document.write("<br/>Yes"); } else { document.write("<br/>No"); } if (wordBreak("", dict)) { document.write("<br/>Yes"); } else { document.write("<br/>No"); } if (wordBreak("samsungandmango", dict)) { document.write("<br/>Yes"); } else { document.write("<br/>No"); } if (wordBreak("ilikesamsung", dict)) { document.write("<br/>Yes"); } else { document.write("<br/>No"); } if (wordBreak("samsungandmangok", dict)) { document.write("<br/>Yes"); } else { document.write("<br/>No"); } // This code is contributed by Rajput-Ji</script> Yes Yes Yes Yes Yes No Word Break Problem | (Trie solution)Exercise: The above solutions only finds out whether a given string can be segmented or not. Extend the above Dynamic Programming solution to print all possible partitions of input string.Examples: Input: ilikeicecreamandmango Output: i like ice cream and man go i like ice cream and mango i like icecream and man go i like icecream and mango Input: ilikesamsungmobile Output: i like sam sung mobile i like samsung mobile Refer below post for solution of exercise. Word Break Problem using BacktrackingPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above sparsh singhal ChongSun shivendr7 harshvasoya008 vaibhavpatel1904 Rajput-Ji simmytarika5 surinderdawra388 sagartomar9927 shinjanpatra Amazon Google IBM MAQ Software Microsoft Walmart Zoho Dynamic Programming Zoho Amazon Microsoft Walmart MAQ Software Google IBM 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": 26291, "s": 26263, "text": "\n20 Apr, 2022" }, { "code": null, "e": 26577, "s": 26291, "text": "Given an input string and a dictionary of words, find out if the input string can be segmented into a space-separated sequence of dictionary words. See following examples for more details. This is a famous Google interview question, also being asked by many other companies now a days." }, { "code": null, "e": 26866, "s": 26577, "text": "Consider the following dictionary \n{ i, like, sam, sung, samsung, mobile, ice, \n cream, icecream, man, go, mango}\n\nInput: ilike\nOutput: Yes \nThe string can be segmented as \"i like\".\n\nInput: ilikesamsung\nOutput: Yes\nThe string can be segmented as \"i like samsung\" \nor \"i like sam sung\"." }, { "code": null, "e": 27050, "s": 26866, "text": "Recursive implementation: The idea is simple, we consider each prefix and search it in dictionary. If the prefix is present in dictionary, we recur for rest of the string (or suffix)." }, { "code": null, "e": 27058, "s": 27050, "text": "Python3" }, { "code": "def wordBreak(wordList, word): if word == '': return True else: wordLen = len(word) return any([(word[:i] in wordList) and wordBreak(wordList, word[i:]) for i in range(1, wordLen+1)])", "e": 27269, "s": 27058, "text": null }, { "code": null, "e": 27552, "s": 27271, "text": "If the recursive call for suffix returns true, we return true, otherwise we try next prefix. If we have tried all prefixes and none of them resulted in a solution, we return false.We strongly recommend to see substr function which is used extensively in following implementations." }, { "code": null, "e": 27556, "s": 27552, "text": "C++" }, { "code": null, "e": 27561, "s": 27556, "text": "Java" }, { "code": null, "e": 27569, "s": 27561, "text": "Python3" }, { "code": null, "e": 27580, "s": 27569, "text": "Javascript" }, { "code": "// A recursive program to test whether a given// string can be segmented into space separated// words in dictionary#include <iostream>using namespace std; /* A utility function to check whether a word is present in dictionary or not. An array of strings is used for dictionary. Using array of strings for dictionary is definitely not a good idea. We have used for simplicity of the program*/int dictionaryContains(string word){ string dictionary[] = {\"mobile\",\"samsung\",\"sam\",\"sung\", \"man\",\"mango\",\"icecream\",\"and\", \"go\",\"i\",\"like\",\"ice\",\"cream\"}; int size = sizeof(dictionary)/sizeof(dictionary[0]); for (int i = 0; i < size; i++) if (dictionary[i].compare(word) == 0) return true; return false;} // returns true if string can be segmented into space// separated words, otherwise returns falsebool wordBreak(string str){ int size = str.size(); // Base case if (size == 0) return true; // Try all prefixes of lengths from 1 to size for (int i=1; i<=size; i++) { // The parameter for dictionaryContains is // str.substr(0, i) which is prefix (of input // string) of length 'i'. We first check whether // current prefix is in dictionary. Then we // recursively check for remaining string // str.substr(i, size-i) which is suffix of // length size-i if (dictionaryContains( str.substr(0, i) ) && wordBreak( str.substr(i, size-i) )) return true; } // If we have tried all prefixes and // none of them worked return false;} // Driver program to test above functionsint main(){ wordBreak(\"ilikesamsung\")? cout <<\"Yes\\n\": cout << \"No\\n\"; wordBreak(\"iiiiiiii\")? cout <<\"Yes\\n\": cout << \"No\\n\"; wordBreak(\"\")? cout <<\"Yes\\n\": cout << \"No\\n\"; wordBreak(\"ilikelikeimangoiii\")? cout <<\"Yes\\n\": cout << \"No\\n\"; wordBreak(\"samsungandmango\")? cout <<\"Yes\\n\": cout << \"No\\n\"; wordBreak(\"samsungandmangok\")? cout <<\"Yes\\n\": cout << \"No\\n\"; return 0;}", "e": 29638, "s": 27580, "text": null }, { "code": "import java.util.*; // Recursive implementation of// word break problem in javapublic class WordBreakProblem{ // set to hold dictionary values private static Set<String> dictionary = new HashSet<>(); public static void main(String []args) { // array of strings to be added in dictionary set. String temp_dictionary[] = {\"mobile\",\"samsung\",\"sam\",\"sung\", \"man\",\"mango\",\"icecream\",\"and\", \"go\",\"i\",\"like\",\"ice\",\"cream\"}; // loop to add all strings in dictionary set for (String temp :temp_dictionary) { dictionary.add(temp); } // sample input cases System.out.println(wordBreak(\"ilikesamsung\")); System.out.println(wordBreak(\"iiiiiiii\")); System.out.println(wordBreak(\"\")); System.out.println(wordBreak(\"ilikelikeimangoiii\")); System.out.println(wordBreak(\"samsungandmango\")); System.out.println(wordBreak(\"samsungandmangok\")); } // returns true if the word can be segmented into parts such // that each part is contained in dictionary public static boolean wordBreak(String word) { int size = word.length(); // base case if (size == 0) return true; //else check for all words for (int i = 1; i <= size; i++) { // Now we will first divide the word into two parts , // the prefix will have a length of i and check if it is // present in dictionary ,if yes then we will check for // suffix of length size-i recursively. if both prefix and // suffix are present the word is found in dictionary. if (dictionary.contains(word.substring(0,i)) && wordBreak(word.substring(i,size))) return true; } // if all cases failed then return false return false; }} // This code is contributed by Sparsh Singhal", "e": 31675, "s": 29638, "text": null }, { "code": "# Recursive implementation of# word break problem in Python # returns True if the word can be segmented into parts such# that each part is contained in dictionarydef wordBreak(word): global dictionary size = len(word) # base case if (size == 0): return True # else check for all words for i in range(1,size + 1): # Now we will first divide the word into two parts , # the prefix will have a length of i and check if it is # present in dictionary ,if yes then we will check for # suffix of length size-i recursively. if both prefix and # suffix are present the word is found in dictionary. if (word[0:i] in dictionary and wordBreak(word[i: size])): return True # if all cases failed then return False return False # set to hold dictionary valuesdictionary = set() # array of strings to be added in dictionary set.temp_dictionary = [ \"mobile\", \"samsung\", \"sam\", \"sung\", \"man\", \"mango\", \"icecream\", \"and\", \"go\", \"i\",\"like\", \"ice\", \"cream\" ] # loop to add all strings in dictionary setfor temp in temp_dictionary: dictionary.add(temp) # sample input casesprint(\"Yes\" if wordBreak(\"ilikesamsung\") else \"No\")print(\"Yes\" if wordBreak(\"iiiiiiii\") else \"No\")print(\"Yes\" if wordBreak(\"\") else \"No\")print(\"Yes\" if wordBreak(\"ilikelikeimangoiii\") else \"No\")print(\"Yes\" if wordBreak(\"samsungandmango\") else \"No\")print(\"Yes\" if wordBreak(\"samsungandmangok\") else \"No\") # This code is contributed by shinjanpatra", "e": 33172, "s": 31675, "text": null }, { "code": "<script>// Recursive implementation of// word break problem in java // set to hold dictionary values var dictionary = new Set(); // array of strings to be added in dictionary set. var temp_dictionary = [ \"mobile\", \"samsung\", \"sam\", \"sung\", \"man\", \"mango\", \"icecream\", \"and\", \"go\", \"i\", \"like\", \"ice\", \"cream\" ]; // loop to add all strings in dictionary set for (var temp of temp_dictionary) { dictionary.add(temp); } // sample input cases document.write(((wordBreak(\"ilikesamsung\"))?\"Yes\":\"No\")+\"<br/>\"); document.write(((wordBreak(\"iiiiiiii\"))?\"Yes\":\"No\")+\"<br/>\"); document.write(((wordBreak(\"\"))?\"Yes\":\"No\")+\"<br/>\"); document.write(((wordBreak(\"ilikelikeimangoiii\"))?\"Yes\":\"No\")+\"<br/>\"); document.write(((wordBreak(\"samsungandmango\"))?\"Yes\":\"No\")+\"<br/>\"); document.write(((wordBreak(\"samsungandmangok\"))?\"Yes\":\"No\")+\"<br/>\"); // returns true if the word can be segmented into parts such // that each part is contained in dictionary function wordBreak( word) { var size = word.length; // base case if (size == 0) return true; // else check for all words for (var i = 1; i <= size; i++) { // Now we will first divide the word into two parts , // the prefix will have a length of i and check if it is // present in dictionary ,if yes then we will check for // suffix of length size-i recursively. if both prefix and // suffix are present the word is found in dictionary. if (dictionary.has(word.substring(0, i)) && wordBreak(word.substring(i, size))) return true; } // if all cases failed then return false return false;} // This code is contributed by Rajput-Ji</script>", "e": 35035, "s": 33172, "text": null }, { "code": null, "e": 35058, "s": 35035, "text": "Yes\nYes\nYes\nYes\nYes\nNo" }, { "code": null, "e": 35245, "s": 35058, "text": "Dynamic Programming Why Dynamic Programming? The above problem exhibits overlapping sub-problems. For example, see the following partial recursion tree for string “abcde” in worst case. " }, { "code": null, "e": 35249, "s": 35245, "text": "CPP" }, { "code": null, "e": 35254, "s": 35249, "text": "Java" }, { "code": null, "e": 35265, "s": 35254, "text": "Javascript" }, { "code": "// A Dynamic Programming based program to test whether a given string can// be segmented into space separated words in dictionary#include <iostream>#include <string.h>using namespace std; /* A utility function to check whether a word is present in dictionary or not. An array of strings is used for dictionary. Using array of strings for dictionary is definitely not a good idea. We have used for simplicity of the program*/int dictionaryContains(string word){ string dictionary[] = {\"mobile\",\"samsung\",\"sam\",\"sung\",\"man\",\"mango\", \"icecream\",\"and\",\"go\",\"i\",\"like\",\"ice\",\"cream\"}; int size = sizeof(dictionary)/sizeof(dictionary[0]); for (int i = 0; i < size; i++) if (dictionary[i].compare(word) == 0) return true; return false;} // Returns true if string can be segmented into space separated// words, otherwise returns falsebool wordBreak(string str){ int size = str.size(); if (size == 0) return true; // Create the DP table to store results of subproblems. The value wb[i] // will be true if str[0..i-1] can be segmented into dictionary words, // otherwise false. bool wb[size+1]; memset(wb, 0, sizeof(wb)); // Initialize all values as false. for (int i=1; i<=size; i++) { // if wb[i] is false, then check if current prefix can make it true. // Current prefix is \"str.substr(0, i)\" if (wb[i] == false && dictionaryContains( str.substr(0, i) )) wb[i] = true; // wb[i] is true, then check for all substrings starting from // (i+1)th character and store their results. if (wb[i] == true) { // If we reached the last prefix if (i == size) return true; for (int j = i+1; j <= size; j++) { // Update wb[j] if it is false and can be updated // Note the parameter passed to dictionaryContains() is // substring starting from index 'i' and length 'j-i' if (wb[j] == false && dictionaryContains( str.substr(i, j-i) )) wb[j] = true; // If we reached the last character if (j == size && wb[j] == true) return true; } } } /* Uncomment these lines to print DP table \"wb[]\" for (int i = 1; i <= size; i++) cout << \" \" << wb[i]; */ // If we have tried all prefixes and none of them worked return false;} // Driver program to test above functionsint main(){ wordBreak(\"ilikesamsung\")? cout <<\"Yes\\n\": cout << \"No\\n\"; wordBreak(\"iiiiiiii\")? cout <<\"Yes\\n\": cout << \"No\\n\"; wordBreak(\"\")? cout <<\"Yes\\n\": cout << \"No\\n\"; wordBreak(\"ilikelikeimangoiii\")? cout <<\"Yes\\n\": cout << \"No\\n\"; wordBreak(\"samsungandmango\")? cout <<\"Yes\\n\": cout << \"No\\n\"; wordBreak(\"samsungandmangok\")? cout <<\"Yes\\n\": cout << \"No\\n\"; return 0;}", "e": 38176, "s": 35265, "text": null }, { "code": "// A Dynamic Programming based program to test whether a given String can// be segmented into space separated words in dictionaryimport java.util.*; class GFG{ /* A utility function to check whether a word is present in dictionary or not. An array of Strings is used for dictionary. Using array of Strings for dictionary is definitely not a good idea. We have used for simplicity of the program*/static boolean dictionaryContains(String word){ String dictionary[] = {\"mobile\",\"samsung\",\"sam\",\"sung\",\"man\",\"mango\", \"icecream\",\"and\",\"go\",\"i\",\"like\",\"ice\",\"cream\"}; int size = dictionary.length; for (int i = 0; i < size; i++) if (dictionary[i].compareTo(word) == 0) return true; return false;} // Returns true if String can be segmented into space separated// words, otherwise returns falsestatic boolean wordBreak(String str){ int size = str.length(); if (size == 0) return true; // Create the DP table to store results of subproblems. The value wb[i] // will be true if str[0..i-1] can be segmented into dictionary words, // otherwise false. boolean []wb = new boolean[size+1]; for (int i=1; i<=size; i++) { // if wb[i] is false, then check if current prefix can make it true. // Current prefix is \"str.substring(0, i)\" if (wb[i] == false && dictionaryContains( str.substring(0, i) )) wb[i] = true; // wb[i] is true, then check for all subStrings starting from // (i+1)th character and store their results. if (wb[i] == true) { // If we reached the last prefix if (i == size) return true; for (int j = i+1; j <= size; j++) { // Update wb[j] if it is false and can be updated // Note the parameter passed to dictionaryContains() is // subString starting from index 'i' and length 'j-i' if (wb[j] == false && dictionaryContains( str.substring(i, j) )) wb[j] = true; // If we reached the last character if (j == size && wb[j] == true) return true; } } } /* Uncomment these lines to print DP table \"wb[]\" for (int i = 1; i <= size; i++) System.out.print(\" \" + wb[i]; */ // If we have tried all prefixes and none of them worked return false;} // Driver program to test above functionspublic static void main(String[] args){ if(wordBreak(\"ilikesamsung\")) System.out.print(\"Yes\\n\"); else System.out.print(\"No\\n\"); if(wordBreak(\"iiiiiiii\")) System.out.print(\"Yes\\n\"); else System.out.print(\"No\\n\"); if(wordBreak(\"\")) System.out.print(\"Yes\\n\"); else System.out.print(\"No\\n\"); if(wordBreak(\"ilikelikeimangoiii\")) System.out.print(\"Yes\\n\"); else System.out.print(\"No\\n\"); if(wordBreak(\"samsungandmango\")) System.out.print(\"Yes\\n\"); else System.out.print(\"No\\n\"); if(wordBreak(\"samsungandmangok\")) System.out.print(\"Yes\\n\"); else System.out.print(\"No\\n\"); }} // This code is contributed by Rajput-Ji", "e": 41370, "s": 38176, "text": null }, { "code": "<script>// A Dynamic Programming based program to test whether a given String can// be segmented into space separated words in dictionary /* * A utility function to check whether a word is present in dictionary or not. * An array of Strings is used for dictionary. Using array of Strings for * dictionary is definitely not a good idea. We have used for simplicity of the * program */ function dictionaryContains( word) { var dictionary = [ \"mobile\", \"samsung\", \"sam\", \"sung\", \"man\", \"mango\", \"icecream\", \"and\", \"go\", \"i\", \"like\", \"ice\", \"cream\" ]; var size = dictionary.length; for (var i = 0; i < size; i++) if (dictionary[i]===(word)) return true; return false; } // Returns true if String can be segmented into space separated // words, otherwise returns false function wordBreak( str) { var size = str.length; if (size == 0) return true; // Create the DP table to store results of subproblems. The value wb[i] // will be true if str[0..i-1] can be segmented into dictionary words, // otherwise false. var wb = Array(size + 1).fill(false); for (var i = 1; i <= size; i++) { // if wb[i] is false, then check if current prefix can make it true. // Current prefix is \"str.substring(0, i)\" if (wb[i] == false && dictionaryContains(str.substring(0, i))) wb[i] = true; // wb[i] is true, then check for all subStrings starting from // (i+1)th character and store their results. if (wb[i] == true) { // If we reached the last prefix if (i == size) return true; for (j = i + 1; j <= size; j++) { // Update wb[j] if it is false and can be updated // Note the parameter passed to dictionaryContains() is // subString starting from index 'i' and length 'j-i' if (wb[j] == false && dictionaryContains(str.substring(i, j))) wb[j] = true; // If we reached the last character if (j == size && wb[j] == true) return true; } } } /* * Uncomment these lines to print DP table \"wb\" for (i = 1; i <= size; * i++) document.write(\" \" + wb[i]; */ // If we have tried all prefixes and none of them worked return false; } // Driver program to test above functions if (wordBreak(\"ilikesamsung\")) document.write(\"Yes<br/>\"); else document.write(\"No<br/>\"); if (wordBreak(\"iiiiiiii\")) document.write(\"Yes<br/>\"); else document.write(\"No<br/>\"); if (wordBreak(\"\")) document.write(\"Yes<br/>\"); else document.write(\"No<br/>\"); if (wordBreak(\"ilikelikeimangoiii\")) document.write(\"Yes<br/>\"); else document.write(\"No<br/>\"); if (wordBreak(\"samsungandmango\")) document.write(\"Yes<br/>\"); else document.write(\"No<br/>\"); if (wordBreak(\"samsungandmangok\")) document.write(\"Yes<br/>\"); else document.write(\"No<br/>\"); // This code contributed by Rajput-Ji</script>", "e": 44787, "s": 41370, "text": null }, { "code": null, "e": 44810, "s": 44787, "text": "Yes\nYes\nYes\nYes\nYes\nNo" }, { "code": null, "e": 45284, "s": 44810, "text": "Optimized Dynamic Programming: In this approach, apart from the dp table, we also maintain all the indexes which have matched earlier. Then we will check the substrings from those indexes to the current index. If anyone of that matches then we can divide the string up to that index.In this program, we are using some extra space. However, its time complexity is O(n*s) where s is the length of the largest string in the dictionary and n is the length of the given string. " }, { "code": null, "e": 45288, "s": 45284, "text": "CPP" }, { "code": null, "e": 45293, "s": 45288, "text": "Java" }, { "code": null, "e": 45301, "s": 45293, "text": "Python3" }, { "code": null, "e": 45312, "s": 45301, "text": "Javascript" }, { "code": "// A Dynamic Programming based program to test// whether a given string can be segmented into// space separated words in dictionary#include <bits/stdc++.h>using namespace std; /* A utility function to check whether a word is present in dictionary or not. An array of strings is used for dictionary. Using array of strings for dictionary is definitely not a good idea. We have used for simplicity of the program*/int dictionaryContains(string word){ string dictionary[] = { \"mobile\", \"samsung\", \"sam\", \"sung\", \"man\", \"mango\", \"icecream\", \"and\", \"go\", \"i\", \"like\", \"ice\", \"cream\" }; int size = sizeof(dictionary) / sizeof(dictionary[0]); for (int i = 0; i < size; i++) if (dictionary[i].compare(word) == 0) return true; return false;} // Returns true if string can be segmented into space// separated words, otherwise returns falsebool wordBreak(string s){ int n = s.size(); if (n == 0) return true; // Create the DP table to store results of subproblems. // The value dp[i] will be true if str[0..i] can be // segmented into dictionary words, otherwise false. vector<bool> dp(n + 1, 0); // Initialize all values // as false. // matched_index array represents the indexes for which // dp[i] is true. Initially only -1 element is present // in this array. vector<int> matched_index; matched_index.push_back(-1); for (int i = 0; i < n; i++) { int msize = matched_index.size(); // Flag value which tells that a substring matches // with given words or not. int f = 0; // Check all the substring from the indexes matched // earlier. If any of that substring matches than // make flag value = 1; for (int j = msize - 1; j >= 0; j--) { // sb is substring starting from // matched_index[j] // + 1 and of length i - matched_index[j] string sb = s.substr(matched_index[j] + 1, i - matched_index[j]); if (dictionaryContains(sb)) { f = 1; break; } } // If substring matches than do dp[i] = 1 and // push that index in matched_index array. if (f == 1) { dp[i] = 1; matched_index.push_back(i); } } return dp[n - 1];} // Driver codeint main(){ wordBreak(\"ilikesamsung\") ? cout << \"Yes\\n\" : cout << \"No\\n\"; wordBreak(\"iiiiiiii\") ? cout << \"Yes\\n\" : cout << \"No\\n\"; wordBreak(\"\") ? cout << \"Yes\\n\" : cout << \"No\\n\"; wordBreak(\"ilikelikeimangoiii\") ? cout << \"Yes\\n\" : cout << \"No\\n\"; wordBreak(\"samsungandmango\") ? cout << \"Yes\\n\" : cout << \"No\\n\"; wordBreak(\"samsungandmangok\") ? cout << \"Yes\\n\" : cout << \"No\\n\"; return 0;}", "e": 48281, "s": 45312, "text": null }, { "code": "import java.io.*;import java.util.*; class GFG { public static boolean wordBreak(String s, List<String> dictionary) { // create a dp table to store results of subproblems // value of dp[i] will be true if string s can be segmented // into dictionary words from 0 to i. boolean[] dp = new boolean[s.length() + 1]; // dp[0] is true because an empty string can always be segmented. dp[0] = true; for(int i = 0; i <= s.length(); i++){ for(int j = 0; j < i; j++){ if(dp[j] && dictionary.contains(s.substring(j, i))){ dp[i] = true; break; } } } return dp[s.length()]; } public static void main (String[] args) { String[] dictionary = { \"mobile\", \"samsung\", \"sam\", \"sung\", \"man\", \"mango\", \"icecream\", \"and\", \"go\", \"i\", \"like\", \"ice\", \"cream\" }; List<String> dict = new ArrayList<>(); for(String s : dictionary){ dict.add(s); } if (wordBreak(\"ilikesamsung\", dict)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } if (wordBreak(\"iiiiiiii\", dict)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } if (wordBreak(\"\", dict)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } if (wordBreak(\"samsungandmango\", dict)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } if (wordBreak(\"ilikesamsung\", dict)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } if (wordBreak(\"samsungandmangok\", dict)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } }}", "e": 50239, "s": 48281, "text": null }, { "code": "def wordBreak(s, dictionary): # create a dp table to store results of subproblems # value of dp[i] will be true if string s can be segmented # into dictionary words from 0 to i. dp = [False for i in range(len(s) + 1)] # dp[0] is true because an empty string can always be segmented. dp[0] = True for i in range(len(s) + 1): for j in range(i): if dp[j] and s[j: i] in dictionary: dp[i] = True break return dp[len(s)] # driver codedictionary = [ \"mobile\", \"samsung\", \"sam\", \"sung\", \"man\", \"mango\", \"icecream\", \"and\", \"go\", \"i\", \"like\", \"ice\", \"cream\" ] dict = set()for s in dictionary: dict.add(s) if (wordBreak(\"ilikesamsung\", dict)): print(\"Yes\")else : print(\"No\") if (wordBreak(\"iiiiiiii\", dict)): print(\"Yes\")else: print(\"No\") if (wordBreak(\"\", dict)): print(\"Yes\")else: print(\"No\") if (wordBreak(\"samsungandmango\", dict)): print(\"Yes\")else: print(\"No\") if (wordBreak(\"ilikesamsung\", dict)): print(\"Yes\")else: print(\"No\") if (wordBreak(\"samsungandmangok\", dict)): print(\"Yes\")else: print(\"No\") # This code is contributed by shinjanpatra", "e": 51402, "s": 50239, "text": null }, { "code": " <script> function wordBreak( s, dictionary) { // create a dp table to store results of subproblems // value of dp[i] will be true if string s can be segmented // into dictionary words from 0 to i. var dp = Array(s.length + 1).fill(false); // dp[0] is true because an empty string can always be segmented. dp[0] = true; for (var i = 0; i <= s.length; i++) { for (var j = 0; j < i; j++) { if (dp[j] && dictionary.has(s.substring(j, i))) { dp[i] = true; break; } } } return dp[s.length]; } var dictionary = [ \"mobile\", \"samsung\", \"sam\", \"sung\", \"man\", \"mango\", \"icecream\", \"and\", \"go\", \"i\", \"like\", \"ice\", \"cream\" ]; var dict = new Set(); for (var s of dictionary) { dict.add(s); } if (wordBreak(\"ilikesamsung\", dict)) { document.write(\"<br/>Yes\"); } else { document.write(\"<br/>No\"); } if (wordBreak(\"iiiiiiii\", dict)) { document.write(\"<br/>Yes\"); } else { document.write(\"<br/>No\"); } if (wordBreak(\"\", dict)) { document.write(\"<br/>Yes\"); } else { document.write(\"<br/>No\"); } if (wordBreak(\"samsungandmango\", dict)) { document.write(\"<br/>Yes\"); } else { document.write(\"<br/>No\"); } if (wordBreak(\"ilikesamsung\", dict)) { document.write(\"<br/>Yes\"); } else { document.write(\"<br/>No\"); } if (wordBreak(\"samsungandmangok\", dict)) { document.write(\"<br/>Yes\"); } else { document.write(\"<br/>No\"); } // This code is contributed by Rajput-Ji</script>", "e": 53245, "s": 51402, "text": null }, { "code": null, "e": 53268, "s": 53245, "text": "Yes\nYes\nYes\nYes\nYes\nNo" }, { "code": null, "e": 53502, "s": 53268, "text": "Word Break Problem | (Trie solution)Exercise: The above solutions only finds out whether a given string can be segmented or not. Extend the above Dynamic Programming solution to print all possible partitions of input string.Examples:" }, { "code": null, "e": 53728, "s": 53502, "text": "Input: ilikeicecreamandmango\nOutput: \ni like ice cream and man go\ni like ice cream and mango\ni like icecream and man go\ni like icecream and mango\n\nInput: ilikesamsungmobile\nOutput:\ni like sam sung mobile\ni like samsung mobile" }, { "code": null, "e": 53933, "s": 53728, "text": "Refer below post for solution of exercise. Word Break Problem using BacktrackingPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 53948, "s": 53933, "text": "sparsh singhal" }, { "code": null, "e": 53957, "s": 53948, "text": "ChongSun" }, { "code": null, "e": 53967, "s": 53957, "text": "shivendr7" }, { "code": null, "e": 53982, "s": 53967, "text": "harshvasoya008" }, { "code": null, "e": 53999, "s": 53982, "text": "vaibhavpatel1904" }, { "code": null, "e": 54009, "s": 53999, "text": "Rajput-Ji" }, { "code": null, "e": 54022, "s": 54009, "text": "simmytarika5" }, { "code": null, "e": 54039, "s": 54022, "text": "surinderdawra388" }, { "code": null, "e": 54054, "s": 54039, "text": "sagartomar9927" }, { "code": null, "e": 54067, "s": 54054, "text": "shinjanpatra" }, { "code": null, "e": 54074, "s": 54067, "text": "Amazon" }, { "code": null, "e": 54081, "s": 54074, "text": "Google" }, { "code": null, "e": 54085, "s": 54081, "text": "IBM" }, { "code": null, "e": 54098, "s": 54085, "text": "MAQ Software" }, { "code": null, "e": 54108, "s": 54098, "text": "Microsoft" }, { "code": null, "e": 54116, "s": 54108, "text": "Walmart" }, { "code": null, "e": 54121, "s": 54116, "text": "Zoho" }, { "code": null, "e": 54141, "s": 54121, "text": "Dynamic Programming" }, { "code": null, "e": 54146, "s": 54141, "text": "Zoho" }, { "code": null, "e": 54153, "s": 54146, "text": "Amazon" }, { "code": null, "e": 54163, "s": 54153, "text": "Microsoft" }, { "code": null, "e": 54171, "s": 54163, "text": "Walmart" }, { "code": null, "e": 54184, "s": 54171, "text": "MAQ Software" }, { "code": null, "e": 54191, "s": 54184, "text": "Google" }, { "code": null, "e": 54195, "s": 54191, "text": "IBM" }, { "code": null, "e": 54215, "s": 54195, "text": "Dynamic Programming" }, { "code": null, "e": 54313, "s": 54215, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 54344, "s": 54313, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 54377, "s": 54344, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 54404, "s": 54377, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 54423, "s": 54404, "text": "Coin Change | DP-7" }, { "code": null, "e": 54458, "s": 54423, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 54496, "s": 54458, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 54564, "s": 54496, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 54585, "s": 54564, "text": "Edit Distance | DP-5" }, { "code": null, "e": 54607, "s": 54585, "text": "Sieve of Eratosthenes" } ]
Find a peak element in a 2D array in C++
In this tutorial, we are going to write a program that finds the peak element in a 2D array. An element is called a peak element if all the elements around it are smaller than the element. Let's see the steps to solve the problem. Initialize the 2D array with dummy data. Initialize the 2D array with dummy data. Iterate over the 2D array.First, check the corner elements of the 2D array.Next, write the conditions for the first and last rows of the 2D array.Now, check for the first and last columns of the 2D array.And finally, check the middle elements.In each case, we have to compare the current element with its surrounding elements. It varies based on the above conditions.Return the value wherever you find the result. Iterate over the 2D array. First, check the corner elements of the 2D array. First, check the corner elements of the 2D array. Next, write the conditions for the first and last rows of the 2D array. Next, write the conditions for the first and last rows of the 2D array. Now, check for the first and last columns of the 2D array. Now, check for the first and last columns of the 2D array. And finally, check the middle elements. And finally, check the middle elements. In each case, we have to compare the current element with its surrounding elements. It varies based on the above conditions. In each case, we have to compare the current element with its surrounding elements. It varies based on the above conditions. Return the value wherever you find the result. Return the value wherever you find the result. Let's see the code. Live Demo #include <bits/stdc++.h> using namespace std; const int MAX = 256; int findPeakElement(int arr[][MAX], int rows, int columns) { for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (i == 0 && j == 0) { if (arr[i][j] > arr[i + 1][j] && arr[i][j] > arr[i][j + 1]) { return arr[i][j]; } } else if (i == 0 && j == columns - 1) { if (arr[i][j] > arr[i + 1][j] && arr[i][j] > arr[i][j - 1]) { return arr[i][j]; } } else if (i == rows - 1 && j == 0) { if (arr[i][j] > arr[i - 1][j] && arr[i][j] > arr[i][j + 1]) { return arr[i][j]; } } else if (i == rows - 1 && j == columns - 1) { if (arr[i][j] > arr[i - 1][j] && arr[i][j] > arr[i][j - 1]) { return arr[i][j]; } } else if (i == 0) { if (arr[i][j] > arr[i][j - 1] && arr[i][j] > arr[i][j + 1] && arr[i][j] > arr[i + 1][j]) { return arr[i][j]; } } else if (i == rows - 1) { if (arr[i][j] > arr[i][j - 1] && arr[i][j] > arr[i][j + 1] && arr[i][j] > arr[i - 1][j]) { return arr[i][j]; } } else if (j == 0) { if (arr[i][j] > arr[i - 1][j] && arr[i][j] > arr[i + 1][j] && arr[i][j] > arr[i][j + 1]) { return arr[i][j]; } } else if (j == columns - 1) { if (arr[i][j] > arr[i - 1][j] && arr[i][j] > arr[i + 1][j] && arr[i][j] > arr[i][j - 1]) { return arr[i][j]; } } else { if (arr[i][j] > arr[i][j - 1] && arr[i][j] > arr[i][j + 1] && arr[i][j] > arr[i - 1][j] && arr[i][j] > arr[i + 1][j]) { return arr[i][j]; } } } } return -1; } int main() { int arr[][MAX] = { { 1, 2, 3, 4 }, { 2, 3, 4, 5 }, { 1, 3, 7, 5 }, { 1, 2, 6, 6 } }; int rows = 4, columns = 4; cout << findPeakElement(arr, rows, columns) << endl; return 0; } If you run the above code, then you will get the following result. 7 If you have any queries in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1155, "s": 1062, "text": "In this tutorial, we are going to write a program that finds the peak element in a 2D array." }, { "code": null, "e": 1251, "s": 1155, "text": "An element is called a peak element if all the elements around it are smaller than the element." }, { "code": null, "e": 1293, "s": 1251, "text": "Let's see the steps to solve the problem." }, { "code": null, "e": 1334, "s": 1293, "text": "Initialize the 2D array with dummy data." }, { "code": null, "e": 1375, "s": 1334, "text": "Initialize the 2D array with dummy data." }, { "code": null, "e": 1789, "s": 1375, "text": "Iterate over the 2D array.First, check the corner elements of the 2D array.Next, write the conditions for the first and last rows of the 2D array.Now, check for the first and last columns of the 2D array.And finally, check the middle elements.In each case, we have to compare the current element with its surrounding elements. It varies based on the above conditions.Return the value wherever you find the result." }, { "code": null, "e": 1816, "s": 1789, "text": "Iterate over the 2D array." }, { "code": null, "e": 1866, "s": 1816, "text": "First, check the corner elements of the 2D array." }, { "code": null, "e": 1916, "s": 1866, "text": "First, check the corner elements of the 2D array." }, { "code": null, "e": 1988, "s": 1916, "text": "Next, write the conditions for the first and last rows of the 2D array." }, { "code": null, "e": 2060, "s": 1988, "text": "Next, write the conditions for the first and last rows of the 2D array." }, { "code": null, "e": 2119, "s": 2060, "text": "Now, check for the first and last columns of the 2D array." }, { "code": null, "e": 2178, "s": 2119, "text": "Now, check for the first and last columns of the 2D array." }, { "code": null, "e": 2218, "s": 2178, "text": "And finally, check the middle elements." }, { "code": null, "e": 2258, "s": 2218, "text": "And finally, check the middle elements." }, { "code": null, "e": 2383, "s": 2258, "text": "In each case, we have to compare the current element with its surrounding elements. It varies based on the above conditions." }, { "code": null, "e": 2508, "s": 2383, "text": "In each case, we have to compare the current element with its surrounding elements. It varies based on the above conditions." }, { "code": null, "e": 2555, "s": 2508, "text": "Return the value wherever you find the result." }, { "code": null, "e": 2602, "s": 2555, "text": "Return the value wherever you find the result." }, { "code": null, "e": 2622, "s": 2602, "text": "Let's see the code." }, { "code": null, "e": 2633, "s": 2622, "text": " Live Demo" }, { "code": null, "e": 4782, "s": 2633, "text": "#include <bits/stdc++.h>\nusing namespace std;\nconst int MAX = 256;\nint findPeakElement(int arr[][MAX], int rows, int columns) {\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < columns; j++) {\n if (i == 0 && j == 0) {\n if (arr[i][j] > arr[i + 1][j] && arr[i][j] > arr[i][j + 1]) {\n return arr[i][j];\n }\n }\n else if (i == 0 && j == columns - 1) {\n if (arr[i][j] > arr[i + 1][j] && arr[i][j] > arr[i][j - 1]) {\n return arr[i][j];\n }\n }\n else if (i == rows - 1 && j == 0) {\n if (arr[i][j] > arr[i - 1][j] && arr[i][j] > arr[i][j + 1]) {\n return arr[i][j];\n }\n }\n else if (i == rows - 1 && j == columns - 1) {\n if (arr[i][j] > arr[i - 1][j] && arr[i][j] > arr[i][j - 1]) {\n return arr[i][j];\n }\n }\n else if (i == 0) {\n if (arr[i][j] > arr[i][j - 1] && arr[i][j] > arr[i][j + 1] && arr[i][j] > arr[i + 1][j]) {\n return arr[i][j];\n }\n }\n else if (i == rows - 1) {\n if (arr[i][j] > arr[i][j - 1] && arr[i][j] > arr[i][j + 1] && arr[i][j] > arr[i - 1][j]) {\n return arr[i][j];\n }\n }\n else if (j == 0) {\n if (arr[i][j] > arr[i - 1][j] && arr[i][j] > arr[i + 1][j] && arr[i][j] > arr[i][j + 1]) {\n return arr[i][j];\n }\n }\n else if (j == columns - 1) {\n if (arr[i][j] > arr[i - 1][j] && arr[i][j] > arr[i + 1][j] && arr[i][j] > arr[i][j - 1]) {\n return arr[i][j];\n }\n }\n else {\n if (arr[i][j] > arr[i][j - 1] && arr[i][j] > arr[i][j + 1] && arr[i][j] > arr[i - 1][j] && arr[i][j] > arr[i + 1][j]) {\n return arr[i][j];\n }\n }\n }\n }\n return -1;\n}\nint main() {\n int arr[][MAX] = {\n { 1, 2, 3, 4 },\n { 2, 3, 4, 5 },\n { 1, 3, 7, 5 },\n { 1, 2, 6, 6 } };\n int rows = 4, columns = 4;\n cout << findPeakElement(arr, rows, columns) << endl;\n return 0;\n}" }, { "code": null, "e": 4849, "s": 4782, "text": "If you run the above code, then you will get the following result." }, { "code": null, "e": 4851, "s": 4849, "text": "7" }, { "code": null, "e": 4929, "s": 4851, "text": "If you have any queries in the tutorial, mention them in the comment section." } ]
Count the number of ways to reach Nth stair by taking jumps of 1 to N - GeeksforGeeks
10 Jan, 2022 Given an integer N which depicts the number of stairs, the task is to count the number of ways to reach Nth stair by taking jumps of 1 to N. Examples: Input: N = 2Output: 2Explanation: Two ways to reach are: (1, 1) & (2) Input: N = 3Output: 4 Input: N = 4Output: 8 Approach: In this problem, the number of ways to reach the ith stair is: Ways to reach ith stair = (Sum of ways to reach stairs 1 to i-1)+1As for any stair before i, ith stair can be reached in a single jump. And +1 for jumping directly to i. Now to solve this problem: Create a variable sum to store the number of ways to reach on a particular stair. Initialise it with 0.Run a loop from i=1 to i=N-1 and for each iteration:Create a variable, say cur to store the number of ways to the current stair. So, cur = sum + 1.Change sum to sum = sum + cur.Return sum + 1 after the loop ends as the answer to this problem. Create a variable sum to store the number of ways to reach on a particular stair. Initialise it with 0. Run a loop from i=1 to i=N-1 and for each iteration:Create a variable, say cur to store the number of ways to the current stair. So, cur = sum + 1.Change sum to sum = sum + cur. Create a variable, say cur to store the number of ways to the current stair. So, cur = sum + 1.Change sum to sum = sum + cur. Create a variable, say cur to store the number of ways to the current stair. So, cur = sum + 1. Change sum to sum = sum + cur. Return sum + 1 after the loop ends as the answer to this problem. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ code for the above approach #include <bits/stdc++.h>using namespace std; // Function to count the number of ways// to reach Nth stairint findWays(int N){ int sum = 0; for (int i = 1; i < N; i++) { int cur = sum + 1; sum += cur; } return sum + 1;} // Driver Codeint main(){ int N = 10; cout << findWays(N);} // Java code for the above approachimport java.util.*;public class GFG{ // Function to count the number of ways // to reach Nth stair static int findWays(int N) { int sum = 0; for (int i = 1; i < N; i++) { int cur = sum + 1; sum += cur; } return sum + 1; } // Driver Code public static void main(String args[]) { int N = 10; System.out.print(findWays(N)); }} // This code is contributed by Samim Hossain Mondal. # python3 code for the above approach # Function to count the number of ways# to reach Nth stairdef findWays(N): sum = 0 for i in range(1, N): cur = sum + 1 sum += cur return sum + 1 # Driver Codeif __name__ == "__main__": N = 10 print(findWays(N)) # This code is contributed by rakeshsahni // C# code to implement above approachusing System;class GFG{ // Function to count the number of ways // to reach Nth stair static int findWays(int N) { int sum = 0; for (int i = 1; i < N; i++) { int cur = sum + 1; sum += cur; } return sum + 1; } // Driver code public static void Main() { int N = 10; Console.Write(findWays(N)); }} // This code is contributed by Samim Hossain Mondal. <script> // JavaScript code for the above approach // Function to count the number of ways // to reach Nth stair function findWays(N) { let sum = 0; for (let i = 1; i < N; i++) { let cur = sum + 1; sum += cur; } return sum + 1; } // Driver Code let N = 10; document.write(findWays(N)); // This code is contributed by Potta Lokesh </script> 512 Time Complexity: O(N)Auxiliary Space: O(1) lokeshpotta20 rakeshsahni samim2000 Combinatorial Mathematical Pattern Searching Mathematical Combinatorial Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Combinations with repetitions Number of handshakes such that a person shakes hands only once 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 Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7 Program to find GCD or HCF of two numbers
[ { "code": null, "e": 25452, "s": 25424, "text": "\n10 Jan, 2022" }, { "code": null, "e": 25593, "s": 25452, "text": "Given an integer N which depicts the number of stairs, the task is to count the number of ways to reach Nth stair by taking jumps of 1 to N." }, { "code": null, "e": 25604, "s": 25593, "text": "Examples: " }, { "code": null, "e": 25674, "s": 25604, "text": "Input: N = 2Output: 2Explanation: Two ways to reach are: (1, 1) & (2)" }, { "code": null, "e": 25696, "s": 25674, "text": "Input: N = 3Output: 4" }, { "code": null, "e": 25718, "s": 25696, "text": "Input: N = 4Output: 8" }, { "code": null, "e": 25791, "s": 25718, "text": "Approach: In this problem, the number of ways to reach the ith stair is:" }, { "code": null, "e": 25961, "s": 25791, "text": "Ways to reach ith stair = (Sum of ways to reach stairs 1 to i-1)+1As for any stair before i, ith stair can be reached in a single jump. And +1 for jumping directly to i." }, { "code": null, "e": 25989, "s": 25961, "text": "Now to solve this problem: " }, { "code": null, "e": 26335, "s": 25989, "text": "Create a variable sum to store the number of ways to reach on a particular stair. Initialise it with 0.Run a loop from i=1 to i=N-1 and for each iteration:Create a variable, say cur to store the number of ways to the current stair. So, cur = sum + 1.Change sum to sum = sum + cur.Return sum + 1 after the loop ends as the answer to this problem." }, { "code": null, "e": 26439, "s": 26335, "text": "Create a variable sum to store the number of ways to reach on a particular stair. Initialise it with 0." }, { "code": null, "e": 26617, "s": 26439, "text": "Run a loop from i=1 to i=N-1 and for each iteration:Create a variable, say cur to store the number of ways to the current stair. So, cur = sum + 1.Change sum to sum = sum + cur." }, { "code": null, "e": 26743, "s": 26617, "text": "Create a variable, say cur to store the number of ways to the current stair. So, cur = sum + 1.Change sum to sum = sum + cur." }, { "code": null, "e": 26839, "s": 26743, "text": "Create a variable, say cur to store the number of ways to the current stair. So, cur = sum + 1." }, { "code": null, "e": 26870, "s": 26839, "text": "Change sum to sum = sum + cur." }, { "code": null, "e": 26936, "s": 26870, "text": "Return sum + 1 after the loop ends as the answer to this problem." }, { "code": null, "e": 26987, "s": 26936, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26991, "s": 26987, "text": "C++" }, { "code": null, "e": 26996, "s": 26991, "text": "Java" }, { "code": null, "e": 27004, "s": 26996, "text": "Python3" }, { "code": null, "e": 27007, "s": 27004, "text": "C#" }, { "code": null, "e": 27018, "s": 27007, "text": "Javascript" }, { "code": "// C++ code for the above approach #include <bits/stdc++.h>using namespace std; // Function to count the number of ways// to reach Nth stairint findWays(int N){ int sum = 0; for (int i = 1; i < N; i++) { int cur = sum + 1; sum += cur; } return sum + 1;} // Driver Codeint main(){ int N = 10; cout << findWays(N);}", "e": 27366, "s": 27018, "text": null }, { "code": "// Java code for the above approachimport java.util.*;public class GFG{ // Function to count the number of ways // to reach Nth stair static int findWays(int N) { int sum = 0; for (int i = 1; i < N; i++) { int cur = sum + 1; sum += cur; } return sum + 1; } // Driver Code public static void main(String args[]) { int N = 10; System.out.print(findWays(N)); }} // This code is contributed by Samim Hossain Mondal.", "e": 27819, "s": 27366, "text": null }, { "code": "# python3 code for the above approach # Function to count the number of ways# to reach Nth stairdef findWays(N): sum = 0 for i in range(1, N): cur = sum + 1 sum += cur return sum + 1 # Driver Codeif __name__ == \"__main__\": N = 10 print(findWays(N)) # This code is contributed by rakeshsahni", "e": 28142, "s": 27819, "text": null }, { "code": "// C# code to implement above approachusing System;class GFG{ // Function to count the number of ways // to reach Nth stair static int findWays(int N) { int sum = 0; for (int i = 1; i < N; i++) { int cur = sum + 1; sum += cur; } return sum + 1; } // Driver code public static void Main() { int N = 10; Console.Write(findWays(N)); }} // This code is contributed by Samim Hossain Mondal.", "e": 28569, "s": 28142, "text": null }, { "code": "<script> // JavaScript code for the above approach // Function to count the number of ways // to reach Nth stair function findWays(N) { let sum = 0; for (let i = 1; i < N; i++) { let cur = sum + 1; sum += cur; } return sum + 1; } // Driver Code let N = 10; document.write(findWays(N)); // This code is contributed by Potta Lokesh </script>", "e": 29017, "s": 28569, "text": null }, { "code": null, "e": 29024, "s": 29020, "text": "512" }, { "code": null, "e": 29069, "s": 29026, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 29085, "s": 29071, "text": "lokeshpotta20" }, { "code": null, "e": 29097, "s": 29085, "text": "rakeshsahni" }, { "code": null, "e": 29107, "s": 29097, "text": "samim2000" }, { "code": null, "e": 29121, "s": 29107, "text": "Combinatorial" }, { "code": null, "e": 29134, "s": 29121, "text": "Mathematical" }, { "code": null, "e": 29152, "s": 29134, "text": "Pattern Searching" }, { "code": null, "e": 29165, "s": 29152, "text": "Mathematical" }, { "code": null, "e": 29179, "s": 29165, "text": "Combinatorial" }, { "code": null, "e": 29197, "s": 29179, "text": "Pattern Searching" }, { "code": null, "e": 29295, "s": 29197, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29325, "s": 29295, "text": "Combinations with repetitions" }, { "code": null, "e": 29388, "s": 29325, "text": "Number of handshakes such that a person shakes hands only once" }, { "code": null, "e": 29460, "s": 29388, "text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed" }, { "code": null, "e": 29538, "s": 29460, "text": "Generate all possible combinations of at most X characters from a given array" }, { "code": null, "e": 29577, "s": 29538, "text": "Largest substring with same Characters" }, { "code": null, "e": 29607, "s": 29577, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 29622, "s": 29607, "text": "C++ Data Types" }, { "code": null, "e": 29665, "s": 29622, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 29684, "s": 29665, "text": "Coin Change | DP-7" } ]
Types of Graph
There are various types of graphs depending upon the number of vertices, number of edges, interconnectivity, and their overall structure. We will discuss only a certain few important types of graphs in this chapter. A graph having no edges is called a Null Graph. In the above graph, there are three vertices named 'a', 'b', and 'c', but there are no edges among them. Hence it is a Null Graph. A graph with only one vertex is called a Trivial Graph. In the above shown graph, there is only one vertex 'a' with no other edges. Hence it is a Trivial graph. A non-directed graph contains edges but the edges are not directed ones. In this graph, 'a', 'b', 'c', 'd', 'e', 'f', 'g' are the vertices, and 'ab', 'bc', 'cd', 'da', 'ag', 'gf', 'ef' are the edges of the graph. Since it is a non-directed graph, the edges 'ab' and 'ba' are same. Similarly other edges also considered in the same way. In a directed graph, each edge has a direction. In the above graph, we have seven vertices 'a', 'b', 'c', 'd', 'e', 'f', and 'g', and eight edges 'ab', 'cb', 'dc', 'ad', 'ec', 'fe', 'gf', and 'ga'. As it is a directed graph, each edge bears an arrow mark that shows its direction. Note that in a directed graph, 'ab' is different from 'ba'. A graph with no loops and no parallel edges is called a simple graph. The maximum number of edges possible in a single graph with 'n' vertices is nC2 where nC2 = n(n – 1)/2. The maximum number of edges possible in a single graph with 'n' vertices is nC2 where nC2 = n(n – 1)/2. The number of simple graphs possible with 'n' vertices = 2nc2 = 2n(n-1)/2. The number of simple graphs possible with 'n' vertices = 2nc2 = 2n(n-1)/2. In the following graph, there are 3 vertices with 3 edges which is maximum excluding the parallel edges and loops. This can be proved by using the above formulae. The maximum number of edges with n=3 vertices − nC2 = n(n–1)/2 = 3(3–1)/2 = 6/2 = 3 edges The maximum number of simple graphs with n = 3 vertices − 2nC2 = 2n(n-1)/2 = 23(3-1)/2 = 23 = 8 These 8 graphs are as shown below − A graph G is said to be connected if there exists a path between every pair of vertices. There should be at least one edge for every vertex in the graph. So that we can say that it is connected to some other vertex at the other side of the edge. In the following graph, each vertex has its own edge connected to other edge. Hence it is a connected graph. A graph G is disconnected, if it does not contain at least two connected vertices. The following graph is an example of a Disconnected Graph, where there are two components, one with 'a', 'b', 'c', 'd' vertices and another with 'e', 'f', 'g', 'h' vertices. The two components are independent and not connected to each other. Hence it is called disconnected graph. In this example, there are two independent components, a-b-f-e and c-d, which are not connected to each other. Hence this is a disconnected graph. A graph G is said to be regular, if all its vertices have the same degree. In a graph, if the degree of each vertex is 'k', then the graph is called a 'k-regular graph'. In the following graphs, all the vertices have the same degree. So these graphs are called regular graphs. In both the graphs, all the vertices have degree 2. They are called 2-Regular Graphs. A simple graph with 'n' mutual vertices is called a complete graph and it is denoted by 'Kn'. In the graph, a vertex should have edges with all other vertices, then it called a complete graph. In other words, if a vertex is connected to all other vertices in a graph, then it is called a complete graph. In the following graphs, each vertex in the graph is connected with all the remaining vertices in the graph except by itself. In graph I, In graph II, A simple graph with 'n' vertices (n >= 3) and 'n' edges is called a cycle graph if all its edges form a cycle of length 'n'. If the degree of each vertex in the graph is two, then it is called a Cycle Graph. Notation − Cn Take a look at the following graphs − Graph I has 3 vertices with 3 edges which is forming a cycle 'ab-bc-ca'. Graph I has 3 vertices with 3 edges which is forming a cycle 'ab-bc-ca'. Graph II has 4 vertices with 4 edges which is forming a cycle 'pq-qs-sr-rp'. Graph II has 4 vertices with 4 edges which is forming a cycle 'pq-qs-sr-rp'. Graph III has 5 vertices with 5 edges which is forming a cycle 'ik-km-ml-lj-ji'. Graph III has 5 vertices with 5 edges which is forming a cycle 'ik-km-ml-lj-ji'. Hence all the given graphs are cycle graphs. A wheel graph is obtained from a cycle graph Cn-1 by adding a new vertex. That new vertex is called a Hub which is connected to all the vertices of Cn. Notation − Wn No. of edges in Wn = No. of edges from hub to all other vertices + No. of edges from all other nodes in cycle graph without a hub. = (n–1) + (n–1) = 2(n–1) Take a look at the following graphs. They are all wheel graphs. In graph I, it is obtained from C3 by adding an vertex at the middle named as 'd'. It is denoted as W4. Number of edges in W4 = 2(n-1) = 2(3) = 6 In graph II, it is obtained from C4 by adding a vertex at the middle named as 't'. It is denoted as W5. Number of edges in W5 = 2(n-1) = 2(4) = 8 In graph III, it is obtained from C6 by adding a vertex at the middle named as 'o'. It is denoted as W7. Number of edges in W4 = 2(n-1) = 2(6) = 12 A graph with at least one cycle is called a cyclic graph. In the above example graph, we have two cycles a-b-c-d-a and c-f-g-e-c. Hence it is called a cyclic graph. A graph with no cycles is called an acyclic graph. In the above example graph, we do not have any cycles. Hence it is a non-cyclic graph. A simple graph G = (V, E) with vertex partition V = {V1, V2} is called a bipartite graph if every edge of E joins a vertex in V1 to a vertex in V2. In general, a Bipertite graph has two sets of vertices, let us say, V1 and V2, and if an edge is drawn, it should connect any vertex in set V1 to any vertex in set V2. In this graph, you can observe two sets of vertices − V1 and V2. Here, two edges named 'ae' and 'bd' are connecting the vertices of two sets V1 and V2. A bipartite graph 'G', G = (V, E) with partition V = {V1, V2} is said to be a complete bipartite graph if every vertex in V1 is connected to every vertex of V2. In general, a complete bipartite graph connects each vertex from set V1 to each vertex from set V2. The following graph is a complete bipartite graph because it has edges connecting each vertex from set V1 to each vertex from set V2. If |V1| = m and |V2| = n, then the complete bipartite graph is denoted by Km, n. Km,n has (m+n) vertices and (mn) edges. Km,n has (m+n) vertices and (mn) edges. Km,n is a regular graph if m=n. Km,n is a regular graph if m=n. In general, a complete bipartite graph is not a complete graph. Km,n is a complete graph if m = n = 1. The maximum number of edges in a bipartite graph with n vertices is If n = 10, k5, 5 = ⌊ n2 / 4 ⌋ = ⌊ 102 / 4 ⌋ = 25 Similarly K6, 4=24 K7, 3=21 K8, 2=16 K9, 1=9 If n=9, k5, 4 = ⌊ n2 / 4 ⌋ = ⌊ 92 / 4 ⌋ = 20 Similarly K6, 3=18 K7, 2=14 K8, 1=8 'G' is a bipartite graph if 'G' has no cycles of odd length. A special case of bipartite graph is a star graph. A complete bipartite graph of the form K1, n-1 is a star graph with n-vertices. A star graph is a complete bipartite graph if a single vertex belongs to one set and all the remaining vertices belong to the other set. In the above graphs, out of 'n' vertices, all the 'n–1' vertices are connected to a single vertex. Hence it is in the form of K1, n-1 which are star graphs.
[ { "code": null, "e": 1278, "s": 1062, "text": "There are various types of graphs depending upon the number of vertices, number of edges, interconnectivity, and their overall structure. We will discuss only a certain few important types of graphs in this chapter." }, { "code": null, "e": 1326, "s": 1278, "text": "A graph having no edges is called a Null Graph." }, { "code": null, "e": 1457, "s": 1326, "text": "In the above graph, there are three vertices named 'a', 'b', and 'c', but there are no edges among them. Hence it is a Null Graph." }, { "code": null, "e": 1513, "s": 1457, "text": "A graph with only one vertex is called a Trivial Graph." }, { "code": null, "e": 1618, "s": 1513, "text": "In the above shown graph, there is only one vertex 'a' with no other edges. Hence it is a Trivial graph." }, { "code": null, "e": 1691, "s": 1618, "text": "A non-directed graph contains edges but the edges are not directed ones." }, { "code": null, "e": 1954, "s": 1691, "text": "In this graph, 'a', 'b', 'c', 'd', 'e', 'f', 'g' are the vertices, and 'ab', 'bc', 'cd', 'da', 'ag', 'gf', 'ef' are the edges of the graph. Since it is a non-directed graph, the edges 'ab' and 'ba' are same. Similarly other edges also considered in the same way." }, { "code": null, "e": 2002, "s": 1954, "text": "In a directed graph, each edge has a direction." }, { "code": null, "e": 2295, "s": 2002, "text": "In the above graph, we have seven vertices 'a', 'b', 'c', 'd', 'e', 'f', and 'g', and eight edges 'ab', 'cb', 'dc', 'ad', 'ec', 'fe', 'gf', and 'ga'. As it is a directed graph, each edge bears an arrow mark that shows its direction. Note that in a directed graph, 'ab' is different from 'ba'." }, { "code": null, "e": 2365, "s": 2295, "text": "A graph with no loops and no parallel edges is called a simple graph." }, { "code": null, "e": 2469, "s": 2365, "text": "The maximum number of edges possible in a single graph with 'n' vertices is nC2 where nC2 = n(n – 1)/2." }, { "code": null, "e": 2573, "s": 2469, "text": "The maximum number of edges possible in a single graph with 'n' vertices is nC2 where nC2 = n(n – 1)/2." }, { "code": null, "e": 2648, "s": 2573, "text": "The number of simple graphs possible with 'n' vertices = 2nc2 = 2n(n-1)/2." }, { "code": null, "e": 2723, "s": 2648, "text": "The number of simple graphs possible with 'n' vertices = 2nc2 = 2n(n-1)/2." }, { "code": null, "e": 2886, "s": 2723, "text": "In the following graph, there are 3 vertices with 3 edges which is maximum excluding the parallel edges and loops. This can be proved by using the above formulae." }, { "code": null, "e": 2934, "s": 2886, "text": "The maximum number of edges with n=3 vertices −" }, { "code": null, "e": 2976, "s": 2934, "text": "nC2 = n(n–1)/2\n= 3(3–1)/2\n= 6/2\n= 3 edges" }, { "code": null, "e": 3034, "s": 2976, "text": "The maximum number of simple graphs with n = 3 vertices −" }, { "code": null, "e": 3072, "s": 3034, "text": "2nC2 = 2n(n-1)/2\n= 23(3-1)/2\n= 23\n= 8" }, { "code": null, "e": 3108, "s": 3072, "text": "These 8 graphs are as shown below −" }, { "code": null, "e": 3354, "s": 3108, "text": "A graph G is said to be connected if there exists a path between every pair of vertices. There should be at least one edge for every vertex in the graph. So that we can say that it is connected to some other vertex at the other side of the edge." }, { "code": null, "e": 3463, "s": 3354, "text": "In the following graph, each vertex has its own edge connected to other edge. Hence it is a connected graph." }, { "code": null, "e": 3546, "s": 3463, "text": "A graph G is disconnected, if it does not contain at least two connected vertices." }, { "code": null, "e": 3720, "s": 3546, "text": "The following graph is an example of a Disconnected Graph, where there are two components, one with 'a', 'b', 'c', 'd' vertices and another with 'e', 'f', 'g', 'h' vertices." }, { "code": null, "e": 3827, "s": 3720, "text": "The two components are independent and not connected to each other. Hence it is called disconnected graph." }, { "code": null, "e": 3974, "s": 3827, "text": "In this example, there are two independent components, a-b-f-e and c-d, which are not connected to each other. Hence this is a disconnected graph." }, { "code": null, "e": 4144, "s": 3974, "text": "A graph G is said to be regular, if all its vertices have the same degree. In a graph, if the degree of each vertex is 'k', then the graph is called a 'k-regular graph'." }, { "code": null, "e": 4251, "s": 4144, "text": "In the following graphs, all the vertices have the same degree. So these graphs are called regular graphs." }, { "code": null, "e": 4337, "s": 4251, "text": "In both the graphs, all the vertices have degree 2. They are called 2-Regular Graphs." }, { "code": null, "e": 4530, "s": 4337, "text": "A simple graph with 'n' mutual vertices is called a complete graph and it is denoted by 'Kn'. In the graph, a vertex should have edges with all other vertices, then it called a complete graph." }, { "code": null, "e": 4641, "s": 4530, "text": "In other words, if a vertex is connected to all other vertices in a graph, then it is called a complete graph." }, { "code": null, "e": 4767, "s": 4641, "text": "In the following graphs, each vertex in the graph is connected with all the remaining vertices in the graph except by itself." }, { "code": null, "e": 4779, "s": 4767, "text": "In graph I," }, { "code": null, "e": 4792, "s": 4779, "text": "In graph II," }, { "code": null, "e": 4917, "s": 4792, "text": "A simple graph with 'n' vertices (n >= 3) and 'n' edges is called a cycle graph if all its edges form a cycle of length 'n'." }, { "code": null, "e": 5000, "s": 4917, "text": "If the degree of each vertex in the graph is two, then it is called a Cycle Graph." }, { "code": null, "e": 5014, "s": 5000, "text": "Notation − Cn" }, { "code": null, "e": 5052, "s": 5014, "text": "Take a look at the following graphs −" }, { "code": null, "e": 5125, "s": 5052, "text": "Graph I has 3 vertices with 3 edges which is forming a cycle 'ab-bc-ca'." }, { "code": null, "e": 5198, "s": 5125, "text": "Graph I has 3 vertices with 3 edges which is forming a cycle 'ab-bc-ca'." }, { "code": null, "e": 5275, "s": 5198, "text": "Graph II has 4 vertices with 4 edges which is forming a cycle 'pq-qs-sr-rp'." }, { "code": null, "e": 5352, "s": 5275, "text": "Graph II has 4 vertices with 4 edges which is forming a cycle 'pq-qs-sr-rp'." }, { "code": null, "e": 5433, "s": 5352, "text": "Graph III has 5 vertices with 5 edges which is forming a cycle 'ik-km-ml-lj-ji'." }, { "code": null, "e": 5514, "s": 5433, "text": "Graph III has 5 vertices with 5 edges which is forming a cycle 'ik-km-ml-lj-ji'." }, { "code": null, "e": 5559, "s": 5514, "text": "Hence all the given graphs are cycle graphs." }, { "code": null, "e": 5711, "s": 5559, "text": "A wheel graph is obtained from a cycle graph Cn-1 by adding a new vertex. That new vertex is called a Hub which is connected to all the vertices of Cn." }, { "code": null, "e": 5725, "s": 5711, "text": "Notation − Wn" }, { "code": null, "e": 5881, "s": 5725, "text": "No. of edges in Wn = No. of edges from hub to all other vertices +\nNo. of edges from all other nodes in cycle graph without a hub.\n= (n–1) + (n–1)\n= 2(n–1)" }, { "code": null, "e": 5945, "s": 5881, "text": "Take a look at the following graphs. They are all wheel graphs." }, { "code": null, "e": 6049, "s": 5945, "text": "In graph I, it is obtained from C3 by adding an vertex at the middle named as 'd'. It is denoted as W4." }, { "code": null, "e": 6091, "s": 6049, "text": "Number of edges in W4 = 2(n-1) = 2(3) = 6" }, { "code": null, "e": 6195, "s": 6091, "text": "In graph II, it is obtained from C4 by adding a vertex at the middle named as 't'. It is denoted as W5." }, { "code": null, "e": 6237, "s": 6195, "text": "Number of edges in W5 = 2(n-1) = 2(4) = 8" }, { "code": null, "e": 6342, "s": 6237, "text": "In graph III, it is obtained from C6 by adding a vertex at the middle named as 'o'. It is denoted as W7." }, { "code": null, "e": 6385, "s": 6342, "text": "Number of edges in W4 = 2(n-1) = 2(6) = 12" }, { "code": null, "e": 6443, "s": 6385, "text": "A graph with at least one cycle is called a cyclic graph." }, { "code": null, "e": 6550, "s": 6443, "text": "In the above example graph, we have two cycles a-b-c-d-a and c-f-g-e-c. Hence it is called a cyclic graph." }, { "code": null, "e": 6601, "s": 6550, "text": "A graph with no cycles is called an acyclic graph." }, { "code": null, "e": 6688, "s": 6601, "text": "In the above example graph, we do not have any cycles. Hence it is a non-cyclic graph." }, { "code": null, "e": 6836, "s": 6688, "text": "A simple graph G = (V, E) with vertex partition V = {V1, V2} is called a bipartite graph if every edge of E joins a vertex in V1 to a vertex in V2." }, { "code": null, "e": 7004, "s": 6836, "text": "In general, a Bipertite graph has two sets of vertices, let us say, V1 and V2, and if an edge is drawn, it should connect any vertex in set V1 to any vertex in set V2." }, { "code": null, "e": 7156, "s": 7004, "text": "In this graph, you can observe two sets of vertices − V1 and V2. Here, two edges named 'ae' and 'bd' are connecting the vertices of two sets V1 and V2." }, { "code": null, "e": 7317, "s": 7156, "text": "A bipartite graph 'G', G = (V, E) with partition V = {V1, V2} is said to be a complete bipartite graph if every vertex in V1 is connected to every vertex of V2." }, { "code": null, "e": 7417, "s": 7317, "text": "In general, a complete bipartite graph connects each vertex from set V1 to each vertex from set V2." }, { "code": null, "e": 7551, "s": 7417, "text": "The following graph is a complete bipartite graph because it has edges connecting each vertex from set V1 to each vertex from set V2." }, { "code": null, "e": 7632, "s": 7551, "text": "If |V1| = m and |V2| = n, then the complete bipartite graph is denoted by Km, n." }, { "code": null, "e": 7672, "s": 7632, "text": "Km,n has (m+n) vertices and (mn) edges." }, { "code": null, "e": 7712, "s": 7672, "text": "Km,n has (m+n) vertices and (mn) edges." }, { "code": null, "e": 7744, "s": 7712, "text": "Km,n is a regular graph if m=n." }, { "code": null, "e": 7776, "s": 7744, "text": "Km,n is a regular graph if m=n." }, { "code": null, "e": 7840, "s": 7776, "text": "In general, a complete bipartite graph is not a complete graph." }, { "code": null, "e": 7879, "s": 7840, "text": "Km,n is a complete graph if m = n = 1." }, { "code": null, "e": 7947, "s": 7879, "text": "The maximum number of edges in a bipartite graph with n vertices is" }, { "code": null, "e": 7996, "s": 7947, "text": "If n = 10, k5, 5 = ⌊ n2 / 4 ⌋ = ⌊ 102 / 4 ⌋ = 25" }, { "code": null, "e": 8015, "s": 7996, "text": "Similarly K6, 4=24" }, { "code": null, "e": 8024, "s": 8015, "text": "K7, 3=21" }, { "code": null, "e": 8033, "s": 8024, "text": "K8, 2=16" }, { "code": null, "e": 8041, "s": 8033, "text": "K9, 1=9" }, { "code": null, "e": 8086, "s": 8041, "text": "If n=9, k5, 4 = ⌊ n2 / 4 ⌋ = ⌊ 92 / 4 ⌋ = 20" }, { "code": null, "e": 8105, "s": 8086, "text": "Similarly K6, 3=18" }, { "code": null, "e": 8114, "s": 8105, "text": "K7, 2=14" }, { "code": null, "e": 8122, "s": 8114, "text": "K8, 1=8" }, { "code": null, "e": 8234, "s": 8122, "text": "'G' is a bipartite graph if 'G' has no cycles of odd length. A special case of bipartite graph is a star graph." }, { "code": null, "e": 8451, "s": 8234, "text": "A complete bipartite graph of the form K1, n-1 is a star graph with n-vertices. A star graph is a complete bipartite graph if a single vertex belongs to one set and all the remaining vertices belong to the other set." }, { "code": null, "e": 8608, "s": 8451, "text": "In the above graphs, out of 'n' vertices, all the 'n–1' vertices are connected to a single vertex. Hence it is in the form of K1, n-1 which are star graphs." } ]
How could I do simple inference on my Fine-Tuned Transformers NER models? | by Martin Keywood | Towards Data Science
I knew what I wanted to do. I wanted to generate NER in a biomedical domain. I had done it in the wonderful scispaCy package, and even in Transformers via the amazing Simple Transformers, but I wanted to do it in the raw HuggingFace Transformers package. Why? I had it working in scispaCy out the box with their pre-trained models, and in Simple Transformers with only a couple of lines of code and some preprocessing of data, so wasn’t that enough? Of course not. I wanted to understand ‘how’ it worked. How to do it myself in Transformers, and then push the boundaries of what I could do. I found so so many examples of how to train and / or fine-tune a Transformer model. By a lot of experimenting and dark magic I was able to make some sense of the preprocessing of the data and ‘thought’ I had it right. After all, I had a model that trained. The loss going down sensibly. Awesome. Done, right? Sadly, not. I want to use that model. Easily and sensibly. So how do I do simple inference on the model? In Simple Transformers I could just call something: model.predict(["the text I was to predict on"]) and get my predictions back. No preprocessing the text and just so, well, simple. I guess that's why it was called Simple Transformers :) Most other ML libraries I had used in the past (sklearn, fast.ai, etc) all had something similar. a ‘predict’ method on the model. And trying to figure out how to do this in raw Transformers was where my problems started :( OK so firstly I needed some data. I thought I’d start with a well understood Biomedical NER dataset, BC5CDR, and a little Pre-Processing to get the data into a format to make it easier to manipulate the sentences. import pandas as pd with open('train.tsv', 'r') as f: data = f.readlines() sentence_id = 1sentence_id_array = []word_array = []label_array = [] for line in data: line = line.strip() if len(line): word, label = line.split('\t') sentence_id_array.append(sentence_id) word_array.append(word) label_array.append(label) else: sentence_id += 1 df = pd.DataFrame({ 'sentence_id': sentence_id_array, 'words': word_array, 'labels': label_array}) df.to_csv('train_clean.csv', index=False) Firstly make sure everything is installed, and define some defaults settings that will help. (note: a lot of the Train section here was inspired by the wonderful run_ner example in Transformers) !pip install transformers!pip install datasets!pip install seqevalimport osimport sysimport pandas as pdimport numpy as npfrom seqeval.metrics import accuracy_score, f1_score, precision_score, recall_scoreimport torchimport transformersfrom transformers import (AutoConfig, AutoModelForTokenClassification, AutoTokenizer, Trainer, TrainingArguments, set_seed)task_name = "ner"model_name_or_path = 'bert-base-cased'output_dir = 'tmp'overwrite_output_dir = Truenum_train_epochs = 1train_file = "train_clean.csv"preprocessing_num_workers = Nonepadding = "max_length"label_all_tokens = Trueseed = 42set_seed(seed)training_args = TrainingArguments(output_dir=output_dir, do_train=True, do_eval=True, num_train_epochs=num_train_epochs) OK so let’s load the data and create some simple lookups of the associated labels. df_train = pd.read_csv(train_file)df_train[‘sentence_id’] = df_train[‘sentence_id’].astype(int)text_column_name = “words”label_column_name = “labels”label_list = list(set(df_train[label_column_name]))label_to_id = {l: i for i, l in enumerate(label_list)}id_to_label = {label_to_id[x]: x for x in label_to_id}num_labels = len(label_list)num_labels, label_list, label_to_id, id_to_label [‘B-Disease’, ‘I-Disease’, ‘I-Chemical’, ‘B-Chemical’, ‘O’] {‘B-Chemical’: 3, ‘B-Disease’: 0, ‘I-Chemical’: 2, ‘I-Disease’: 1, ‘O’: 4} {0: ‘B-Disease’, 1: ‘I-Disease’, 2: ‘I-Chemical’, 3: ‘B-Chemical’, 4: ‘O’} Load the pre-trained model and tokenizer. config = AutoConfig.from_pretrained(model_name_or_path, num_labels=num_labels, finetuning_task=task_name)tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, use_fast=True)model = AutoModelForTokenClassification.from_pretrained( model_name_or_path, from_tf=bool(".ckpt" in model_name_or_path), config=config) We are doing ‘max length’ padding and need a little helper function to Tokenize all texts and align the labels with them. Why?? The words are already separated into ‘tokens’ aren’t they? One per line, with a label for each word? We can just use those by passing in is_split_into_words = True and it's all fine, right? On the surface that seems true, however given the tokenizer is based on the model, and it may be a Byte Pair Encoding Tokenizer (extremely likely) then the words are potentially split further. So ['Selegiline', '-', 'induced', 'postural', 'hypotension', 'in', 'Parkinson', "'", 's', 'disease', ':', 'a', 'longitudinal', 'study', 'on', 'the', 'effects', 'of', 'drug', 'withdrawal', '.'] becomes ['[CLS]', 'Se', '##leg', '##ili', '##ne', '-', 'induced', 'post', '##ural', 'h', '##y', '##pot', '##ens', '##ion', 'in', 'Parkinson', "'", 's', 'disease', ':', 'a', 'longitudinal', 'study', 'on', 'the', 'effects', 'of', 'drug', 'withdrawal', '.', '[SEP]'] So regardless of the special tokens, the number of tokens goes from 21 to 29 in this example. And so the labels need to be rejigged to continue to align with the base words. # Tokenize all texts and align the labels with them.def tokenize_and_align_labels(df): inputs = [] labels = [] for sid in range(1, max(df['sentence_id'])+1): examples = list(df.loc[df['sentence_id'] == sid, text_column_name]) try: tokenized_inputs = tokenizer(examples, padding=padding, truncation=True, is_split_into_words=True) sentence_labels = list(df.loc[df['sentence_id'] == sid, label_column_name]) label_ids = [] for word_idx in tokenized_inputs.word_ids(): # Special tokens have a word id that is None. We set the label to -100 so they are automatically ignored in the loss function. if word_idx is None: label_ids.append(-100) # We set the label for the first token of each word. elif word_idx != previous_word_idx: label_ids.append(label_to_id[sentence_labels[word_idx]]) # For the other tokens in a word, we set the label to either the current label or -100, depending on the label_all_tokens flag. else: label_ids.append(label_to_id[sentence_labels[word_idx]] if label_all_tokens else -100) previous_word_idx = word_idxinputs.append(tokenized_inputs) labels.append(torch.tensor(label_ids)) except: pass return inputs, labelsencodings, labels = tokenize_and_align_labels(df_train) Use tried and tested methods to split into train / val sets, and use those to generate some Transformer Datasets, ensuring we make them all Tensors along the way. class MakeDataset(torch.utils.data.Dataset): def __init__(self, encodings, labels): self.encodings = encodings self.labels = labelsdef __getitem__(self, idx): item = dict() item[‘input_ids’] = torch.tensor(self.encodings[idx][‘input_ids’]) item[‘token_type_ids’] = torch.tensor(self.encodings[idx][‘token_type_ids’]) item[‘attention_mask’] = torch.tensor(self.encodings[idx][‘attention_mask’]) item[‘labels’] = torch.tensor(self.labels[idx]) return itemdef __len__(self): return len(self.labels)train_dataset = MakeDataset(train_encodings, train_labels)val_dataset = MakeDataset(val_encodings, val_labels) And define some helpful metrics. def compute_metrics(p): predictions, labels = p predictions = np.argmax(predictions, axis=2)# Remove ignored index (special tokens) true_predictions = [ [label_list[p] for (p, l) in zip(prediction, label) if l != -100] for prediction, label in zip(predictions, labels) ] true_labels = [ [label_list[l] for (p, l) in zip(prediction, label) if l != -100] for prediction, label in zip(predictions, labels) ]return { "accuracy_score": accuracy_score(true_labels, true_predictions), "precision": precision_score(true_labels, true_predictions), "recall": recall_score(true_labels, true_predictions), "f1": f1_score(true_labels, true_predictions), } OK let’s train. # Initialize our Trainertrainer = Trainer( model=model, args=training_args, train_dataset=train_dataset, eval_dataset=val_dataset, compute_metrics=compute_metrics)# Trainingtrainer.train(model_path=model_name_or_path)trainer.save_model() # Saves the tokenizer too for easy upload# Evaluationresults = trainer.evaluate()output_eval_file = os.path.join(training_args.output_dir, "eval_results_ner.txt")if trainer.is_world_process_zero(): with open(output_eval_file, "w") as writer: for key, value in results.items(): writer.write(f"{key} = {value}\n") eval_loss = 0.11932332068681717 eval_accuracy_score = 0.9635168195718654 eval_precision = 0.9027568922305764 eval_recall = 0.9226434426229508 eval_f1 = 0.9125918419052444 Not bad after only 1 epoch :) And this was where my problems started. I could find nothing, nada, zero, nowt, zilch that could explain to me ‘simply’ how to do it. There was no predict method on the model. The predict method on the Trainer just made no sense to me and required DataSets creating and I wanted to do inference on just a single string: “heart disease, a new house, a dose of penicillin, and bowel cancer. The diagnosis of COPD, a flashy new car and a skin rash.” Was it badly written Transformers libraries? Not at all. It’s amazing. Was it me just me being daft? Not enough coffee? Yeah I think so. One thing that was clear was it was ‘user error’ and when I finally discovered the answer I kicked myself: Firstly, tokenize the same way we did for the training data Then put the model in eval mode and just call the model passing in the ‘input_ids’ and ‘attention_mask’ (note, I am explicitly pushing them to cuda to be on the GPU, where my model was trained, but obviously remove the cuda calls if all on CPU), taking the argmax of the results And decode that back to the original tokens and labels test_encodings = tokenizer(["heart disease, a new house, a dose of penicillin, and bowel cancer. The diagnosis of COPD, a flashy new car and a skin rash."], padding=padding, truncation=True)model.eval()res = model(torch.tensor(test_encodings["input_ids"]).cuda(), attention_mask=torch.tensor(test_encodings["attention_mask"]).cuda())[0].argmax(dim=2)for i, enc in enumerate(test_encodings['input_ids'][0]): if enc: print(tokenizer.decode(enc), "\t", id_to_label[res[0][i].item()]) And the results: [CLS] Oheart B-Diseasedisease I-Disease, Oa Onew Ohouse O, Oa Odose Oof Open B-Chemical##ici B-Chemical##llin B-Chemical, Oand Obow B-Disease##el B-Diseasecancer I-Disease. OThe Odiagnosis Oof OCO B-Disease##PD B-Disease, Oa Oflash O##y Onew Ocar Oand Oa Oskin B-Diseaser I-Disease##ash I-Disease. O[SEP] O Well that is just amazing. I mean, mind blowingly ace :) It’s picked out the diseases and the medication (chemicals). And it got better. I could misspell ‘cancer’ as ‘canrce’, or ‘bowel’ as ‘bowl’ and it still found it. This was all really exciting for me and has opened up the door to me exploring a lot more in this area. Who’s laughing now, eh!! My hope is this will help someone else in a similar situation and a similar stage on their NLP journey, where they follow all the tutorials to train and fine-tune and then say ‘now what? how do I use it’ :) That’s certainly where I was. And if you’re interested and like it, please let me know and I will be sure to write up future experiments too :)
[ { "code": null, "e": 249, "s": 172, "text": "I knew what I wanted to do. I wanted to generate NER in a biomedical domain." }, { "code": null, "e": 427, "s": 249, "text": "I had done it in the wonderful scispaCy package, and even in Transformers via the amazing Simple Transformers, but I wanted to do it in the raw HuggingFace Transformers package." }, { "code": null, "e": 622, "s": 427, "text": "Why? I had it working in scispaCy out the box with their pre-trained models, and in Simple Transformers with only a couple of lines of code and some preprocessing of data, so wasn’t that enough?" }, { "code": null, "e": 763, "s": 622, "text": "Of course not. I wanted to understand ‘how’ it worked. How to do it myself in Transformers, and then push the boundaries of what I could do." }, { "code": null, "e": 847, "s": 763, "text": "I found so so many examples of how to train and / or fine-tune a Transformer model." }, { "code": null, "e": 1072, "s": 847, "text": "By a lot of experimenting and dark magic I was able to make some sense of the preprocessing of the data and ‘thought’ I had it right. After all, I had a model that trained. The loss going down sensibly. Awesome. Done, right?" }, { "code": null, "e": 1177, "s": 1072, "text": "Sadly, not. I want to use that model. Easily and sensibly. So how do I do simple inference on the model?" }, { "code": null, "e": 1415, "s": 1177, "text": "In Simple Transformers I could just call something: model.predict([\"the text I was to predict on\"]) and get my predictions back. No preprocessing the text and just so, well, simple. I guess that's why it was called Simple Transformers :)" }, { "code": null, "e": 1546, "s": 1415, "text": "Most other ML libraries I had used in the past (sklearn, fast.ai, etc) all had something similar. a ‘predict’ method on the model." }, { "code": null, "e": 1639, "s": 1546, "text": "And trying to figure out how to do this in raw Transformers was where my problems started :(" }, { "code": null, "e": 1673, "s": 1639, "text": "OK so firstly I needed some data." }, { "code": null, "e": 1853, "s": 1673, "text": "I thought I’d start with a well understood Biomedical NER dataset, BC5CDR, and a little Pre-Processing to get the data into a format to make it easier to manipulate the sentences." }, { "code": null, "e": 2337, "s": 1853, "text": "import pandas as pd with open('train.tsv', 'r') as f: data = f.readlines() sentence_id = 1sentence_id_array = []word_array = []label_array = [] for line in data: line = line.strip() if len(line): word, label = line.split('\\t') sentence_id_array.append(sentence_id) word_array.append(word) label_array.append(label) else: sentence_id += 1 df = pd.DataFrame({ 'sentence_id': sentence_id_array, 'words': word_array, 'labels': label_array}) df.to_csv('train_clean.csv', index=False)" }, { "code": null, "e": 2532, "s": 2337, "text": "Firstly make sure everything is installed, and define some defaults settings that will help. (note: a lot of the Train section here was inspired by the wonderful run_ner example in Transformers)" }, { "code": null, "e": 3262, "s": 2532, "text": "!pip install transformers!pip install datasets!pip install seqevalimport osimport sysimport pandas as pdimport numpy as npfrom seqeval.metrics import accuracy_score, f1_score, precision_score, recall_scoreimport torchimport transformersfrom transformers import (AutoConfig, AutoModelForTokenClassification, AutoTokenizer, Trainer, TrainingArguments, set_seed)task_name = \"ner\"model_name_or_path = 'bert-base-cased'output_dir = 'tmp'overwrite_output_dir = Truenum_train_epochs = 1train_file = \"train_clean.csv\"preprocessing_num_workers = Nonepadding = \"max_length\"label_all_tokens = Trueseed = 42set_seed(seed)training_args = TrainingArguments(output_dir=output_dir, do_train=True, do_eval=True, num_train_epochs=num_train_epochs)" }, { "code": null, "e": 3345, "s": 3262, "text": "OK so let’s load the data and create some simple lookups of the associated labels." }, { "code": null, "e": 3731, "s": 3345, "text": "df_train = pd.read_csv(train_file)df_train[‘sentence_id’] = df_train[‘sentence_id’].astype(int)text_column_name = “words”label_column_name = “labels”label_list = list(set(df_train[label_column_name]))label_to_id = {l: i for i, l in enumerate(label_list)}id_to_label = {label_to_id[x]: x for x in label_to_id}num_labels = len(label_list)num_labels, label_list, label_to_id, id_to_label" }, { "code": null, "e": 3791, "s": 3731, "text": "[‘B-Disease’, ‘I-Disease’, ‘I-Chemical’, ‘B-Chemical’, ‘O’]" }, { "code": null, "e": 3866, "s": 3791, "text": "{‘B-Chemical’: 3, ‘B-Disease’: 0, ‘I-Chemical’: 2, ‘I-Disease’: 1, ‘O’: 4}" }, { "code": null, "e": 3941, "s": 3866, "text": "{0: ‘B-Disease’, 1: ‘I-Disease’, 2: ‘I-Chemical’, 3: ‘B-Chemical’, 4: ‘O’}" }, { "code": null, "e": 3983, "s": 3941, "text": "Load the pre-trained model and tokenizer." }, { "code": null, "e": 4301, "s": 3983, "text": "config = AutoConfig.from_pretrained(model_name_or_path, num_labels=num_labels, finetuning_task=task_name)tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, use_fast=True)model = AutoModelForTokenClassification.from_pretrained( model_name_or_path, from_tf=bool(\".ckpt\" in model_name_or_path), config=config)" }, { "code": null, "e": 4423, "s": 4301, "text": "We are doing ‘max length’ padding and need a little helper function to Tokenize all texts and align the labels with them." }, { "code": null, "e": 4429, "s": 4423, "text": "Why??" }, { "code": null, "e": 4619, "s": 4429, "text": "The words are already separated into ‘tokens’ aren’t they? One per line, with a label for each word? We can just use those by passing in is_split_into_words = True and it's all fine, right?" }, { "code": null, "e": 4812, "s": 4619, "text": "On the surface that seems true, however given the tokenizer is based on the model, and it may be a Byte Pair Encoding Tokenizer (extremely likely) then the words are potentially split further." }, { "code": null, "e": 5005, "s": 4812, "text": "So ['Selegiline', '-', 'induced', 'postural', 'hypotension', 'in', 'Parkinson', \"'\", 's', 'disease', ':', 'a', 'longitudinal', 'study', 'on', 'the', 'effects', 'of', 'drug', 'withdrawal', '.']" }, { "code": null, "e": 5269, "s": 5005, "text": "becomes ['[CLS]', 'Se', '##leg', '##ili', '##ne', '-', 'induced', 'post', '##ural', 'h', '##y', '##pot', '##ens', '##ion', 'in', 'Parkinson', \"'\", 's', 'disease', ':', 'a', 'longitudinal', 'study', 'on', 'the', 'effects', 'of', 'drug', 'withdrawal', '.', '[SEP]']" }, { "code": null, "e": 5443, "s": 5269, "text": "So regardless of the special tokens, the number of tokens goes from 21 to 29 in this example. And so the labels need to be rejigged to continue to align with the base words." }, { "code": null, "e": 6685, "s": 5443, "text": "# Tokenize all texts and align the labels with them.def tokenize_and_align_labels(df): inputs = [] labels = [] for sid in range(1, max(df['sentence_id'])+1): examples = list(df.loc[df['sentence_id'] == sid, text_column_name]) try: tokenized_inputs = tokenizer(examples, padding=padding, truncation=True, is_split_into_words=True) sentence_labels = list(df.loc[df['sentence_id'] == sid, label_column_name]) label_ids = [] for word_idx in tokenized_inputs.word_ids(): # Special tokens have a word id that is None. We set the label to -100 so they are automatically ignored in the loss function. if word_idx is None: label_ids.append(-100) # We set the label for the first token of each word. elif word_idx != previous_word_idx: label_ids.append(label_to_id[sentence_labels[word_idx]]) # For the other tokens in a word, we set the label to either the current label or -100, depending on the label_all_tokens flag. else: label_ids.append(label_to_id[sentence_labels[word_idx]] if label_all_tokens else -100) previous_word_idx = word_idxinputs.append(tokenized_inputs) labels.append(torch.tensor(label_ids)) except: pass return inputs, labelsencodings, labels = tokenize_and_align_labels(df_train)" }, { "code": null, "e": 6848, "s": 6685, "text": "Use tried and tested methods to split into train / val sets, and use those to generate some Transformer Datasets, ensuring we make them all Tensors along the way." }, { "code": null, "e": 7454, "s": 6848, "text": "class MakeDataset(torch.utils.data.Dataset): def __init__(self, encodings, labels): self.encodings = encodings self.labels = labelsdef __getitem__(self, idx): item = dict() item[‘input_ids’] = torch.tensor(self.encodings[idx][‘input_ids’]) item[‘token_type_ids’] = torch.tensor(self.encodings[idx][‘token_type_ids’]) item[‘attention_mask’] = torch.tensor(self.encodings[idx][‘attention_mask’]) item[‘labels’] = torch.tensor(self.labels[idx]) return itemdef __len__(self): return len(self.labels)train_dataset = MakeDataset(train_encodings, train_labels)val_dataset = MakeDataset(val_encodings, val_labels)" }, { "code": null, "e": 7487, "s": 7454, "text": "And define some helpful metrics." }, { "code": null, "e": 8146, "s": 7487, "text": "def compute_metrics(p): predictions, labels = p predictions = np.argmax(predictions, axis=2)# Remove ignored index (special tokens) true_predictions = [ [label_list[p] for (p, l) in zip(prediction, label) if l != -100] for prediction, label in zip(predictions, labels) ] true_labels = [ [label_list[l] for (p, l) in zip(prediction, label) if l != -100] for prediction, label in zip(predictions, labels) ]return { \"accuracy_score\": accuracy_score(true_labels, true_predictions), \"precision\": precision_score(true_labels, true_predictions), \"recall\": recall_score(true_labels, true_predictions), \"f1\": f1_score(true_labels, true_predictions), }" }, { "code": null, "e": 8162, "s": 8146, "text": "OK let’s train." }, { "code": null, "e": 8716, "s": 8162, "text": "# Initialize our Trainertrainer = Trainer( model=model, args=training_args, train_dataset=train_dataset, eval_dataset=val_dataset, compute_metrics=compute_metrics)# Trainingtrainer.train(model_path=model_name_or_path)trainer.save_model() # Saves the tokenizer too for easy upload# Evaluationresults = trainer.evaluate()output_eval_file = os.path.join(training_args.output_dir, \"eval_results_ner.txt\")if trainer.is_world_process_zero(): with open(output_eval_file, \"w\") as writer: for key, value in results.items(): writer.write(f\"{key} = {value}\\n\")" }, { "code": null, "e": 8748, "s": 8716, "text": "eval_loss = 0.11932332068681717" }, { "code": null, "e": 8789, "s": 8748, "text": "eval_accuracy_score = 0.9635168195718654" }, { "code": null, "e": 8825, "s": 8789, "text": "eval_precision = 0.9027568922305764" }, { "code": null, "e": 8858, "s": 8825, "text": "eval_recall = 0.9226434426229508" }, { "code": null, "e": 8887, "s": 8858, "text": "eval_f1 = 0.9125918419052444" }, { "code": null, "e": 8917, "s": 8887, "text": "Not bad after only 1 epoch :)" }, { "code": null, "e": 8957, "s": 8917, "text": "And this was where my problems started." }, { "code": null, "e": 9051, "s": 8957, "text": "I could find nothing, nada, zero, nowt, zilch that could explain to me ‘simply’ how to do it." }, { "code": null, "e": 9364, "s": 9051, "text": "There was no predict method on the model. The predict method on the Trainer just made no sense to me and required DataSets creating and I wanted to do inference on just a single string: “heart disease, a new house, a dose of penicillin, and bowel cancer. The diagnosis of COPD, a flashy new car and a skin rash.”" }, { "code": null, "e": 9435, "s": 9364, "text": "Was it badly written Transformers libraries? Not at all. It’s amazing." }, { "code": null, "e": 9608, "s": 9435, "text": "Was it me just me being daft? Not enough coffee? Yeah I think so. One thing that was clear was it was ‘user error’ and when I finally discovered the answer I kicked myself:" }, { "code": null, "e": 9668, "s": 9608, "text": "Firstly, tokenize the same way we did for the training data" }, { "code": null, "e": 9947, "s": 9668, "text": "Then put the model in eval mode and just call the model passing in the ‘input_ids’ and ‘attention_mask’ (note, I am explicitly pushing them to cuda to be on the GPU, where my model was trained, but obviously remove the cuda calls if all on CPU), taking the argmax of the results" }, { "code": null, "e": 10002, "s": 9947, "text": "And decode that back to the original tokens and labels" }, { "code": null, "e": 10484, "s": 10002, "text": "test_encodings = tokenizer([\"heart disease, a new house, a dose of penicillin, and bowel cancer. The diagnosis of COPD, a flashy new car and a skin rash.\"], padding=padding, truncation=True)model.eval()res = model(torch.tensor(test_encodings[\"input_ids\"]).cuda(), attention_mask=torch.tensor(test_encodings[\"attention_mask\"]).cuda())[0].argmax(dim=2)for i, enc in enumerate(test_encodings['input_ids'][0]): if enc: print(tokenizer.decode(enc), \"\\t\", id_to_label[res[0][i].item()])" }, { "code": null, "e": 10501, "s": 10484, "text": "And the results:" }, { "code": null, "e": 10953, "s": 10501, "text": "[CLS] Oheart B-Diseasedisease I-Disease, Oa Onew Ohouse O, Oa Odose Oof Open B-Chemical##ici B-Chemical##llin B-Chemical, Oand Obow B-Disease##el B-Diseasecancer I-Disease. OThe Odiagnosis Oof OCO B-Disease##PD B-Disease, Oa Oflash O##y Onew Ocar Oand Oa Oskin B-Diseaser I-Disease##ash I-Disease. O[SEP] O" }, { "code": null, "e": 11071, "s": 10953, "text": "Well that is just amazing. I mean, mind blowingly ace :) It’s picked out the diseases and the medication (chemicals)." }, { "code": null, "e": 11173, "s": 11071, "text": "And it got better. I could misspell ‘cancer’ as ‘canrce’, or ‘bowel’ as ‘bowl’ and it still found it." }, { "code": null, "e": 11277, "s": 11173, "text": "This was all really exciting for me and has opened up the door to me exploring a lot more in this area." }, { "code": null, "e": 11302, "s": 11277, "text": "Who’s laughing now, eh!!" }, { "code": null, "e": 11539, "s": 11302, "text": "My hope is this will help someone else in a similar situation and a similar stage on their NLP journey, where they follow all the tutorials to train and fine-tune and then say ‘now what? how do I use it’ :) That’s certainly where I was." } ]
Conversational AI with BERT Made Easy | by Brandon Janes | Towards Data Science
For over a year I have been trying to automate appointment scheduling using NLP and python, and I finally got it to work thanks to an amazing free open-source dialogue tool called Rasa. The truth is a year ago, when I started this project, the tools I am using now were hardly available. Certainly not in the easy-to-use form that we find them today. As a testament to how quickly this science of artificial intelligence and NLP is moving, this time last year (June 2019) transformers like BERT had barely left the domain of academic research and were just beginning to be seen in production at tech giants like Google and Facebook. The BERT paper itself was only published in October 2018 (links to papers below). Today, thanks to open-source platforms like Rasa and HuggingFace, BERT and other transformer architectures are available in an easy plug-and-play manner. Moreover, the data scientists at Rasa have developed a special transformer-based classifier called the Dual Intent Entity Transformer or DIET classifier that is tailor-made for the task of extracting entities and classifying intents simultaneously, which is exactly what we do with our product MyTurn, an appointment scheduling virtual assistant developed with my team at Kunan S.A. in Argentina. For quantitative folks out there, after I replaced ye ole Sklearn-based classifier with DIET my F1 score surged in both entity extraction and intent classification by more than 30 percent!!!! Compare SklearnIntentClassifier with diet_BERT_combined in the figures below. If you have ever designed machine learning models, you’d know that 30 percent is huge. Like that time you realized you had parked your car on the hose to the sprinkler. What a wonderful surprise when things work the way they should! Is it science or art? It’s neither. It’s trying every possible combination of hyperparameters and choosing the configuration that gives you the highest metrics. It’s called grid search. It’s important to note that BERT is not a magic pill. In fact, for my specific task and training data, the BERT pretrained word embeddings alone did not provide good results (see diet_BERT_only above). These results were significantly worse than the old Sklearn-based classifier of 2019. Perhaps this can be explained by the regional jargon and colloquialisms found in the informal Spanish chats of Córdoba, Argentina, from where our training data was generated. The multilingual pretrained BERT embeddings we used were “trained on cased text in the top 104 languages with the largest Wikipedias,” according to HuggingFace documentation. However, the highest performing model we obtained was by training custom features on our own Córdoba data using DIET and then combining these supervised embeddings with the BERT pretrained embeddings in a feed forward layer (see results in diet_BERT_combined above). The small diagram below shows how “sparse features,” trained on Córdoba data, can be combined with BERT “pretrained embeddings” in a feed forward layer. This option is ideal for Spanish language projects with little training data. That being said, the combined model performed only slightly better than the model that used DIET with no BERT pretrained embeddings (see results for diet_without_BERT above). This means for non-English language chatbots with a moderate amount of training data, the DIET architecture is probably all you need. After installing Rasa, and building an assistant to your needs (I suggest watching Rasa’s YouTube tutorial before doing this), the implementation of BERT embeddings is so easy it is almost disappointing. Below is an example of the configuration file we used. The long list of hyperparameters may seem overwhelming, but trust me, this is much easier than it was a year ago. You must download the BERT dependencies: pip install "rasa[transformers]" To integrate BERT or any of the other pretrained models available on the HuggingFace website, just replace the model_weights hyperparemeter in following line with whatever pretrainined embeddings you want to use. - name: HFTransformers NLP model_weights: “bert-base-multilingual-cased” model_name: “bert” We used bert-base-multilingual-cased because is was the best model available for Spanish. See our github for full examples of configuration files mentioned in this article and additional links. The beauty of Rasa is that it streamlines model training for Natural Language Understanding (NLU), Named Entity Recognition (NER) and Dialogue Management (DM), the three essential tools needed for task-oriented dialogue systems. Although we did a lot of good programming to make our system work as well as it does, you could probably get away with about 80 percent of building a Rasa virtual assistant without any real Python skills. With exciting advancements in NLP, such as transformers and pretrained word embeddings, the field of conversational AI has leaped forward in recent years, from bots that say, “Sorry, I don’t understand,” to truly becoming feasible solutions to daily tasks that once required tedious human work. Philosophically, the goal of this technology is not to replace humans with robots, but rather to assign the repetitive and “robotic” daily tasks, such as data entry or appointment scheduling, to virtual assistants, and reserve the brainspace of humans for the types of work that require skills that only humans have, such as creativity and critical thinking. MyTurn is a simple but prescient example of how conversational AI is not a tool reserved for Big Tech companies, but is in fact accessible to everybody through free and open-source technologies like Rasa and HuggingFace. Suggested readings: Tom Bocklisch, Joey Faulkner, Nick Pawlowski, Alan Nichol, Rasa: Open Source Language Understanding and Dialogue Management,15 December 2017 Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Attention Is All You Need, 6 December 2017 Jianfeng Gao (Microsoft), Micahel Galley (Microsoft), Lihong Li (Google), Neural Approaches to Conversational AI: Question Answering, Task-Oriented Dialogues and Social Chatbots, 10 September 2019 Jacob Devlin Ming-Wei Chang Kenton Lee Kristina Toutanova Google AI Language, BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding, 11 October 2018
[ { "code": null, "e": 358, "s": 172, "text": "For over a year I have been trying to automate appointment scheduling using NLP and python, and I finally got it to work thanks to an amazing free open-source dialogue tool called Rasa." }, { "code": null, "e": 887, "s": 358, "text": "The truth is a year ago, when I started this project, the tools I am using now were hardly available. Certainly not in the easy-to-use form that we find them today. As a testament to how quickly this science of artificial intelligence and NLP is moving, this time last year (June 2019) transformers like BERT had barely left the domain of academic research and were just beginning to be seen in production at tech giants like Google and Facebook. The BERT paper itself was only published in October 2018 (links to papers below)." }, { "code": null, "e": 1438, "s": 887, "text": "Today, thanks to open-source platforms like Rasa and HuggingFace, BERT and other transformer architectures are available in an easy plug-and-play manner. Moreover, the data scientists at Rasa have developed a special transformer-based classifier called the Dual Intent Entity Transformer or DIET classifier that is tailor-made for the task of extracting entities and classifying intents simultaneously, which is exactly what we do with our product MyTurn, an appointment scheduling virtual assistant developed with my team at Kunan S.A. in Argentina." }, { "code": null, "e": 1941, "s": 1438, "text": "For quantitative folks out there, after I replaced ye ole Sklearn-based classifier with DIET my F1 score surged in both entity extraction and intent classification by more than 30 percent!!!! Compare SklearnIntentClassifier with diet_BERT_combined in the figures below. If you have ever designed machine learning models, you’d know that 30 percent is huge. Like that time you realized you had parked your car on the hose to the sprinkler. What a wonderful surprise when things work the way they should!" }, { "code": null, "e": 2127, "s": 1941, "text": "Is it science or art? It’s neither. It’s trying every possible combination of hyperparameters and choosing the configuration that gives you the highest metrics. It’s called grid search." }, { "code": null, "e": 2766, "s": 2127, "text": "It’s important to note that BERT is not a magic pill. In fact, for my specific task and training data, the BERT pretrained word embeddings alone did not provide good results (see diet_BERT_only above). These results were significantly worse than the old Sklearn-based classifier of 2019. Perhaps this can be explained by the regional jargon and colloquialisms found in the informal Spanish chats of Córdoba, Argentina, from where our training data was generated. The multilingual pretrained BERT embeddings we used were “trained on cased text in the top 104 languages with the largest Wikipedias,” according to HuggingFace documentation." }, { "code": null, "e": 3575, "s": 2766, "text": "However, the highest performing model we obtained was by training custom features on our own Córdoba data using DIET and then combining these supervised embeddings with the BERT pretrained embeddings in a feed forward layer (see results in diet_BERT_combined above). The small diagram below shows how “sparse features,” trained on Córdoba data, can be combined with BERT “pretrained embeddings” in a feed forward layer. This option is ideal for Spanish language projects with little training data. That being said, the combined model performed only slightly better than the model that used DIET with no BERT pretrained embeddings (see results for diet_without_BERT above). This means for non-English language chatbots with a moderate amount of training data, the DIET architecture is probably all you need." }, { "code": null, "e": 3779, "s": 3575, "text": "After installing Rasa, and building an assistant to your needs (I suggest watching Rasa’s YouTube tutorial before doing this), the implementation of BERT embeddings is so easy it is almost disappointing." }, { "code": null, "e": 3948, "s": 3779, "text": "Below is an example of the configuration file we used. The long list of hyperparameters may seem overwhelming, but trust me, this is much easier than it was a year ago." }, { "code": null, "e": 3989, "s": 3948, "text": "You must download the BERT dependencies:" }, { "code": null, "e": 4022, "s": 3989, "text": "pip install \"rasa[transformers]\"" }, { "code": null, "e": 4235, "s": 4022, "text": "To integrate BERT or any of the other pretrained models available on the HuggingFace website, just replace the model_weights hyperparemeter in following line with whatever pretrainined embeddings you want to use." }, { "code": null, "e": 4331, "s": 4235, "text": "- name: HFTransformers NLP model_weights: “bert-base-multilingual-cased” model_name: “bert”" }, { "code": null, "e": 4421, "s": 4331, "text": "We used bert-base-multilingual-cased because is was the best model available for Spanish." }, { "code": null, "e": 4525, "s": 4421, "text": "See our github for full examples of configuration files mentioned in this article and additional links." }, { "code": null, "e": 4959, "s": 4525, "text": "The beauty of Rasa is that it streamlines model training for Natural Language Understanding (NLU), Named Entity Recognition (NER) and Dialogue Management (DM), the three essential tools needed for task-oriented dialogue systems. Although we did a lot of good programming to make our system work as well as it does, you could probably get away with about 80 percent of building a Rasa virtual assistant without any real Python skills." }, { "code": null, "e": 5254, "s": 4959, "text": "With exciting advancements in NLP, such as transformers and pretrained word embeddings, the field of conversational AI has leaped forward in recent years, from bots that say, “Sorry, I don’t understand,” to truly becoming feasible solutions to daily tasks that once required tedious human work." }, { "code": null, "e": 5834, "s": 5254, "text": "Philosophically, the goal of this technology is not to replace humans with robots, but rather to assign the repetitive and “robotic” daily tasks, such as data entry or appointment scheduling, to virtual assistants, and reserve the brainspace of humans for the types of work that require skills that only humans have, such as creativity and critical thinking. MyTurn is a simple but prescient example of how conversational AI is not a tool reserved for Big Tech companies, but is in fact accessible to everybody through free and open-source technologies like Rasa and HuggingFace." }, { "code": null, "e": 5854, "s": 5834, "text": "Suggested readings:" }, { "code": null, "e": 5995, "s": 5854, "text": "Tom Bocklisch, Joey Faulkner, Nick Pawlowski, Alan Nichol, Rasa: Open Source Language Understanding and Dialogue Management,15 December 2017" }, { "code": null, "e": 6111, "s": 5995, "text": "Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Attention Is All You Need, 6 December 2017" }, { "code": null, "e": 6308, "s": 6111, "text": "Jianfeng Gao (Microsoft), Micahel Galley (Microsoft), Lihong Li (Google), Neural Approaches to Conversational AI: Question Answering, Task-Oriented Dialogues and Social Chatbots, 10 September 2019" } ]
GATE-CS-2015 (Set 1) - GeeksforGeeks
11 Oct, 2021 She enjoyed herself immensely at the party. (2, 14) (3, 13) (4, 12) (5, 11) Probability = Favorable Outcomes/Total Outcomes Probability = 4/20 = 0.20 Therefore option A is correct Statements: 1. Each step is 3/4 foot high. 2. Each step is 1 foot wide. Flippancy ---> lack of respect or seriousness. Acquiescence ---> the reluctant acceptance of something without protest. Wheedle ---> use endearments or flattery to persuade someone to do something or Profligate ---> recklessly extravagant Q.No. Marks Answered-Correctly Answered-Wrongly Not-Attempted 1 2 21 17 6 2 3 15 27 2 3 1 11 29 4 4 2 23 18 3 5 5 31 12 1 Total marks = 2*21 + 3*15 + 1*11 + 2*23 + 5*31 = 299 Average marks = 299/44 = 6.795 Statement: There has been a significant drop in the water level in the lakes supplying water to the city. Course of action: 1. The water supply authority should impose a partial cut in supply to tackle the situation. 2. The government should appeal to all the residents through mass media for minimal use of water. 3. The government should ban the water supply in lower areas 1. p + m + c = 27/20 2. p + m + c = 13/20 3. (p) × (m) × (c) = 1/10 1 - (1 - m) (1 - p) (1 - c) = 0.75 -------(1) (1 - m)pc + (1 - p)mc + (1 - c)mp + mpc = 0.5 -------(2) (1 - m)pc + (1 - p)mc + (1 - c)mp = 0.4 -------(3) From last 2 equations, we can derive mpc = 0.1 After simplifying equation 1, we get. p + c + m - (mp + mc + pc) + mpc = 0.75 p + c + m - (mp + mc + pc) = 0.65 -------(4) After simplifying equation 3, we get pc + mc + mp - 3mpc = 0.4 Putting value of mpc, we get pc + mc + mp = 0.7 After putting above value in equation 4, we get p + c + m - 0.7 = 0.65 p + c + m = 1.35 = 27/20 See GATE Corner for all papers, notes and other important information. Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Product Based Companies Get Hired With GeeksforGeeks and Win Exciting Rewards! Difference between var, let and const keywords in JavaScript Array of Objects in C++ with Examples How to Replace Values in Column Based on Condition in Pandas? How to Fix: SyntaxError: positional argument follows keyword argument in Python C Program to read contents of Whole File How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE? How to Replace Values in a List in Python? Spring - REST Controller
[ { "code": null, "e": 27610, "s": 27582, "text": "\n11 Oct, 2021" }, { "code": null, "e": 27654, "s": 27610, "text": "She enjoyed herself immensely at the party." }, { "code": null, "e": 27793, "s": 27654, "text": "(2, 14)\n(3, 13)\n(4, 12)\n(5, 11) \n\nProbability = Favorable Outcomes/Total Outcomes\nProbability = 4/20 = 0.20\n\nTherefore option A is correct" }, { "code": null, "e": 27865, "s": 27793, "text": "Statements:\n1. Each step is 3/4 foot high.\n2. Each step is 1 foot wide." }, { "code": null, "e": 28159, "s": 27865, "text": "Flippancy ---> lack of respect or seriousness.\nAcquiescence ---> the reluctant acceptance of \n something without protest.\nWheedle ---> use endearments or flattery to \n persuade someone to do something or \nProfligate ---> recklessly extravagant " }, { "code": null, "e": 28502, "s": 28159, "text": "Q.No. Marks Answered-Correctly Answered-Wrongly Not-Attempted\n 1 2 21 17 6 \n 2 3 15 27 2 \n 3 1 11 29 4\n 4 2 23 18 3\n 5 5 31 12 1 " }, { "code": null, "e": 28601, "s": 28502, "text": "Total marks = 2*21 + 3*15 + 1*11 + 2*23 + 5*31\n = 299\nAverage marks = 299/44 = 6.795 " }, { "code": null, "e": 28992, "s": 28601, "text": "Statement: \nThere has been a significant drop in the water level \nin the lakes supplying water to the city.\n\nCourse of action:\n1. The water supply authority should impose a partial \n cut in supply to tackle the situation.\n2. The government should appeal to all the residents \n through mass media for minimal use of water.\n3. The government should ban the water supply in lower \n areas" }, { "code": null, "e": 29062, "s": 28992, "text": "1. p + m + c = 27/20 \n2. p + m + c = 13/20\n3. (p) × (m) × (c) = 1/10 " }, { "code": null, "e": 29643, "s": 29062, "text": "1 - (1 - m) (1 - p) (1 - c) = 0.75 -------(1)\n(1 - m)pc + (1 - p)mc + (1 - c)mp + mpc = 0.5 -------(2)\n(1 - m)pc + (1 - p)mc + (1 - c)mp = 0.4 -------(3)\n\nFrom last 2 equations, we can derive mpc = 0.1\n\nAfter simplifying equation 1, we get.\np + c + m - (mp + mc + pc) + mpc = 0.75 \np + c + m - (mp + mc + pc) = 0.65 -------(4)\n\nAfter simplifying equation 3, we get\npc + mc + mp - 3mpc = 0.4\n\nPutting value of mpc, we get\npc + mc + mp = 0.7\n\nAfter putting above value in equation 4, we get\n p + c + m - 0.7 = 0.65\n p + c + m = 1.35 = 27/20 " }, { "code": null, "e": 29714, "s": 29643, "text": "See GATE Corner for all papers, notes and other important information." }, { "code": null, "e": 29812, "s": 29714, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 29865, "s": 29812, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 29920, "s": 29865, "text": "Get Hired With GeeksforGeeks and Win Exciting Rewards!" }, { "code": null, "e": 29981, "s": 29920, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30019, "s": 29981, "text": "Array of Objects in C++ with Examples" }, { "code": null, "e": 30081, "s": 30019, "text": "How to Replace Values in Column Based on Condition in Pandas?" }, { "code": null, "e": 30161, "s": 30081, "text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python" }, { "code": null, "e": 30202, "s": 30161, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 30282, "s": 30202, "text": "How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?" }, { "code": null, "e": 30325, "s": 30282, "text": "How to Replace Values in a List in Python?" } ]
How to add help in the PowerShell function?
When we write a program, people from a non-programming background often expect to get much possible help related to the program. When we write the function and we declare the parameters, people who are unaware of what kind of input the parameter need, generally search for the help first using the Get-Help command and then they find only the parameters but not the description of it. For example, function TestFunct{ param( #16 Digit Application ID [parameter(Mandatory=$true)] [String]$AppID, #Date in the Unix Format - 2020-10-31T17:12:10+0530 [String]$Date ) } In the above example, there are two parameters specified and when the user gets help with the function, it doesn’t specify the comments where the parameter description is given. For example, PS C:\> help TestFunct -Parameter * -AppID <string> Required? true Position? 0 Accept pipeline input? false Parameter set name (All) Aliases None Dynamic? false -Date <string> Required? false Position? 1 Accept pipeline input? false Parameter set name (All) Aliases None Dynamic? false To add the description from the comment, we need to add the comment-based help and need to use SYNOPSIS from the comment-based help. Example function TestFunct{ <# .SYNOPSIS This is test function for parameter based help #> param( #16 Digit Application ID [parameter(Mandatory=$true)] [String]$AppID, #Date in the Unix Format - 2020-10-31T17:12:10+0530 [String]$Date ) } Now when we check the parameter, we get the comment based description. PS C:\> help TestFunct -Parameter * -AppID <String> 16 Digit Application ID Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -Date <String> Date in the Unix Format - 2020-10-31T17:12:10+0530 Required? false Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false
[ { "code": null, "e": 1460, "s": 1062, "text": "When we write a program, people from a non-programming background often expect to get much possible help related to the program. When we write the function and we declare the parameters, people who are unaware of what kind of input the parameter need, generally search for the help first using the Get-Help command and then they find only the parameters but not the description of it. For example," }, { "code": null, "e": 1663, "s": 1460, "text": "function TestFunct{\n param(\n #16 Digit Application ID\n [parameter(Mandatory=$true)]\n [String]$AppID,\n #Date in the Unix Format - 2020-10-31T17:12:10+0530\n [String]$Date\n )\n}" }, { "code": null, "e": 1854, "s": 1663, "text": "In the above example, there are two parameters specified and when the user gets help with the function, it doesn’t specify the comments where the parameter description is given. For example," }, { "code": null, "e": 2357, "s": 1854, "text": "PS C:\\> help TestFunct -Parameter *\n-AppID <string>\n\n Required? true\n Position? 0\n Accept pipeline input? false\n Parameter set name (All)\n Aliases None\n Dynamic? false\n\n-Date <string>\n\n Required? false\n Position? 1\n Accept pipeline input? false\n Parameter set name (All)\n Aliases None\n Dynamic? false" }, { "code": null, "e": 2490, "s": 2357, "text": "To add the description from the comment, we need to add the comment-based help and need to use SYNOPSIS from the comment-based help." }, { "code": null, "e": 2498, "s": 2490, "text": "Example" }, { "code": null, "e": 2782, "s": 2498, "text": "function TestFunct{\n <#\n .SYNOPSIS\n This is test function for parameter based help\n #>\n param(\n #16 Digit Application ID\n [parameter(Mandatory=$true)]\n [String]$AppID,\n #Date in the Unix Format - 2020-10-31T17:12:10+0530\n [String]$Date\n )\n}" }, { "code": null, "e": 2853, "s": 2782, "text": "Now when we check the parameter, we get the comment based description." }, { "code": null, "e": 3395, "s": 2853, "text": "PS C:\\> help TestFunct -Parameter *\n-AppID <String>\n 16 Digit Application ID\n\n Required? true\n Position? 1\n Default value\n Accept pipeline input? false\n Accept wildcard characters? false\n\n-Date <String>\n Date in the Unix Format - 2020-10-31T17:12:10+0530\n\n Required? false\n Position? 2\n Default value\n Accept pipeline input? false\n Accept wildcard characters? false" } ]
Java Concurrency - Overview
Java is a multi-threaded programming language which means we can develop multi-threaded program using Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs. By definition, multitasking is when multiple processes share common processing resources such as a CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application. Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program. A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life cycle of a thread. Following are the stages of the life cycle − New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task. Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task. Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing. Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing. Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs. Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs. Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates. Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates. Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled. Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5). Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent. If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface. You will need to follow three basic steps − As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of the run() method − public void run( ) As a second step, you will instantiate a Thread object using the following constructor − Thread(Runnable threadObj, String threadName); Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread. Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method − void start(); Example Here is an example that creates a new thread and starts running it − class RunnableDemo implements Runnable { private Thread t; private String threadName; RunnableDemo(String name) { threadName = name; System.out.println("Creating " + threadName ); } public void run() { System.out.println("Running " + threadName ); try { for(int i = 4; i > 0; i--) { System.out.println("Thread: " + threadName + ", " + i); // Let the thread sleep for a while. Thread.sleep(50); } } catch (InterruptedException e) { System.out.println("Thread " + threadName + " interrupted."); } System.out.println("Thread " + threadName + " exiting."); } public void start () { System.out.println("Starting " + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } } public class TestThread { public static void main(String args[]) { RunnableDemo R1 = new RunnableDemo("Thread-1"); R1.start(); RunnableDemo R2 = new RunnableDemo("Thread-2"); R2.start(); } } This will produce the following result − Output Creating Thread-1 Starting Thread-1 Creating Thread-2 Starting Thread-2 Running Thread-1 Thread: Thread-1, 4 Running Thread-2 Thread: Thread-2, 4 Thread: Thread-1, 3 Thread: Thread-2, 3 Thread: Thread-1, 2 Thread: Thread-2, 2 Thread: Thread-1, 1 Thread: Thread-2, 1 Thread Thread-1 exiting. Thread Thread-2 exiting. The second way to create a thread is to create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class. You will need to override run( ) method available in Thread class. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of run() method − public void run( ) Once Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method − void start( ); Example Here is the preceding program rewritten to extend the Thread − class ThreadDemo extends Thread { private Thread t; private String threadName; ThreadDemo(String name) { threadName = name; System.out.println("Creating " + threadName ); } public void run() { System.out.println("Running " + threadName ); try { for(int i = 4; i > 0; i--) { System.out.println("Thread: " + threadName + ", " + i); // Let the thread sleep for a while. Thread.sleep(50); } } catch (InterruptedException e) { System.out.println("Thread " + threadName + " interrupted."); } System.out.println("Thread " + threadName + " exiting."); } public void start () { System.out.println("Starting " + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } } public class TestThread { public static void main(String args[]) { ThreadDemo T1 = new ThreadDemo("Thread-1"); T1.start(); ThreadDemo T2 = new ThreadDemo("Thread-2"); T2.start(); } } This will produce the following result − Output Creating Thread-1 Starting Thread-1 Creating Thread-2 Starting Thread-2 Running Thread-1 Thread: Thread-1, 4 Running Thread-2 Thread: Thread-2, 4 Thread: Thread-1, 3 Thread: Thread-2, 3 Thread: Thread-1, 2 Thread: Thread-2, 2 Thread: Thread-1, 1 Thread: Thread-2, 1 Thread Thread-1 exiting. Thread Thread-2 exiting. 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2996, "s": 2657, "text": "Java is a multi-threaded programming language which means we can develop multi-threaded program using Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs." }, { "code": null, "e": 3425, "s": 2996, "text": "By definition, multitasking is when multiple processes share common processing resources such as a CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application." }, { "code": null, "e": 3543, "s": 3425, "text": "Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program." }, { "code": null, "e": 3725, "s": 3543, "text": "A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life cycle of a thread." }, { "code": null, "e": 3770, "s": 3725, "text": "Following are the stages of the life cycle −" }, { "code": null, "e": 3932, "s": 3770, "text": "New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread." }, { "code": null, "e": 4094, "s": 3932, "text": "New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread." }, { "code": null, "e": 4235, "s": 4094, "text": "Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task." }, { "code": null, "e": 4376, "s": 4235, "text": "Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task." }, { "code": null, "e": 4623, "s": 4376, "text": "Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing." }, { "code": null, "e": 4870, "s": 4623, "text": "Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing." }, { "code": null, "e": 5110, "s": 4870, "text": "Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs." }, { "code": null, "e": 5350, "s": 5110, "text": "Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs." }, { "code": null, "e": 5468, "s": 5350, "text": "Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates." }, { "code": null, "e": 5586, "s": 5468, "text": "Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates." }, { "code": null, "e": 5703, "s": 5586, "text": "Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled." }, { "code": null, "e": 5895, "s": 5703, "text": "Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5)." }, { "code": null, "e": 6143, "s": 5895, "text": "Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent." }, { "code": null, "e": 6304, "s": 6143, "text": "If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface. You will need to follow three basic steps −" }, { "code": null, "e": 6560, "s": 6304, "text": "As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of the run() method −" }, { "code": null, "e": 6580, "s": 6560, "text": "public void run( )\n" }, { "code": null, "e": 6669, "s": 6580, "text": "As a second step, you will instantiate a Thread object using the following constructor −" }, { "code": null, "e": 6717, "s": 6669, "text": "Thread(Runnable threadObj, String threadName);\n" }, { "code": null, "e": 6851, "s": 6717, "text": "Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread." }, { "code": null, "e": 7017, "s": 6851, "text": "Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method −" }, { "code": null, "e": 7032, "s": 7017, "text": "void start();\n" }, { "code": null, "e": 7040, "s": 7032, "text": "Example" }, { "code": null, "e": 7109, "s": 7040, "text": "Here is an example that creates a new thread and starts running it −" }, { "code": null, "e": 8250, "s": 7109, "text": "class RunnableDemo implements Runnable {\n private Thread t;\n private String threadName;\n\n RunnableDemo(String name) {\n threadName = name;\n System.out.println(\"Creating \" + threadName );\n }\n \n public void run() {\n System.out.println(\"Running \" + threadName );\n \n try {\n \n for(int i = 4; i > 0; i--) {\n System.out.println(\"Thread: \" + threadName + \", \" + i);\n \n // Let the thread sleep for a while.\n Thread.sleep(50);\n }\n } catch (InterruptedException e) {\n System.out.println(\"Thread \" + threadName + \" interrupted.\");\n }\n System.out.println(\"Thread \" + threadName + \" exiting.\");\n }\n \n public void start () {\n System.out.println(\"Starting \" + threadName );\n \n if (t == null) {\n t = new Thread (this, threadName);\n t.start ();\n }\n }\n}\n\npublic class TestThread {\n\n public static void main(String args[]) {\n RunnableDemo R1 = new RunnableDemo(\"Thread-1\");\n R1.start();\n \n RunnableDemo R2 = new RunnableDemo(\"Thread-2\");\n R2.start();\n } \n}" }, { "code": null, "e": 8291, "s": 8250, "text": "This will produce the following result −" }, { "code": null, "e": 8298, "s": 8291, "text": "Output" }, { "code": null, "e": 8615, "s": 8298, "text": "Creating Thread-1\nStarting Thread-1\nCreating Thread-2\nStarting Thread-2\nRunning Thread-1\nThread: Thread-1, 4\nRunning Thread-2\nThread: Thread-2, 4\nThread: Thread-1, 3\nThread: Thread-2, 3\nThread: Thread-1, 2\nThread: Thread-2, 2\nThread: Thread-1, 1\nThread: Thread-2, 1\nThread Thread-1 exiting.\nThread Thread-2 exiting.\n" }, { "code": null, "e": 8856, "s": 8615, "text": "The second way to create a thread is to create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class." }, { "code": null, "e": 9087, "s": 8856, "text": "You will need to override run( ) method available in Thread class. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of run() method −" }, { "code": null, "e": 9107, "s": 9087, "text": "public void run( )\n" }, { "code": null, "e": 9271, "s": 9107, "text": "Once Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method −" }, { "code": null, "e": 9287, "s": 9271, "text": "void start( );\n" }, { "code": null, "e": 9295, "s": 9287, "text": "Example" }, { "code": null, "e": 9358, "s": 9295, "text": "Here is the preceding program rewritten to extend the Thread −" }, { "code": null, "e": 10479, "s": 9358, "text": "class ThreadDemo extends Thread {\n private Thread t;\n private String threadName;\n \n ThreadDemo(String name) {\n threadName = name;\n System.out.println(\"Creating \" + threadName );\n }\n \n public void run() {\n System.out.println(\"Running \" + threadName );\n \n try {\n\n for(int i = 4; i > 0; i--) {\n System.out.println(\"Thread: \" + threadName + \", \" + i);\n \n // Let the thread sleep for a while.\n Thread.sleep(50);\n }\n } catch (InterruptedException e) {\n System.out.println(\"Thread \" + threadName + \" interrupted.\");\n }\n System.out.println(\"Thread \" + threadName + \" exiting.\");\n }\n \n public void start () {\n System.out.println(\"Starting \" + threadName );\n \n if (t == null) {\n t = new Thread (this, threadName);\n t.start ();\n }\n }\n}\n\npublic class TestThread {\n\n public static void main(String args[]) {\n ThreadDemo T1 = new ThreadDemo(\"Thread-1\");\n T1.start();\n \n ThreadDemo T2 = new ThreadDemo(\"Thread-2\");\n T2.start();\n } \n}" }, { "code": null, "e": 10520, "s": 10479, "text": "This will produce the following result −" }, { "code": null, "e": 10527, "s": 10520, "text": "Output" }, { "code": null, "e": 10844, "s": 10527, "text": "Creating Thread-1\nStarting Thread-1\nCreating Thread-2\nStarting Thread-2\nRunning Thread-1\nThread: Thread-1, 4\nRunning Thread-2\nThread: Thread-2, 4\nThread: Thread-1, 3\nThread: Thread-2, 3\nThread: Thread-1, 2\nThread: Thread-2, 2\nThread: Thread-1, 1\nThread: Thread-2, 1\nThread Thread-1 exiting.\nThread Thread-2 exiting.\n" }, { "code": null, "e": 10877, "s": 10844, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 10893, "s": 10877, "text": " Malhar Lathkar" }, { "code": null, "e": 10926, "s": 10893, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 10942, "s": 10926, "text": " Malhar Lathkar" }, { "code": null, "e": 10977, "s": 10942, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 10991, "s": 10977, "text": " Anadi Sharma" }, { "code": null, "e": 11025, "s": 10991, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 11039, "s": 11025, "text": " Tushar Kale" }, { "code": null, "e": 11076, "s": 11039, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 11091, "s": 11076, "text": " Monica Mittal" }, { "code": null, "e": 11124, "s": 11091, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 11143, "s": 11124, "text": " Arnab Chakraborty" }, { "code": null, "e": 11150, "s": 11143, "text": " Print" }, { "code": null, "e": 11161, "s": 11150, "text": " Add Notes" } ]
How to use break and continue statements in Java?
The break statement in Java programming language has the following two usages − When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. It can be used to terminate a case in the switch statement (covered in the next chapter). The syntax of a break is a single statement inside any loop − break; Live Demo public class Test { public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { if( x == 30 ) { break; } System.out.print( x ); System.out.print("\n"); } } } This will produce the following result − 10 20 The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop. In a for loop, the continue keyword causes control to immediately jump to the update statement. In a while loop or do/while loop, control immediately jumps to the Boolean expression. The syntax of a continue is a single statement inside any loop − continue; Live Demo public class Test { public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { if( x == 30 ) { continue; } System.out.print( x ); System.out.print("\n"); } } } This will produce the following result − 10 20 40 50
[ { "code": null, "e": 1142, "s": 1062, "text": "The break statement in Java programming language has the following two usages −" }, { "code": null, "e": 1306, "s": 1142, "text": "When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop." }, { "code": null, "e": 1396, "s": 1306, "text": "It can be used to terminate a case in the switch statement (covered in the next chapter)." }, { "code": null, "e": 1458, "s": 1396, "text": "The syntax of a break is a single statement inside any loop −" }, { "code": null, "e": 1465, "s": 1458, "text": "break;" }, { "code": null, "e": 1475, "s": 1465, "text": "Live Demo" }, { "code": null, "e": 1749, "s": 1475, "text": "public class Test {\n public static void main(String args[]) {\n int [] numbers = {10, 20, 30, 40, 50};\n for(int x : numbers ) {\n if( x == 30 ) {\n break;\n }\n System.out.print( x );\n System.out.print(\"\\n\");\n }\n }\n}" }, { "code": null, "e": 1790, "s": 1749, "text": "This will produce the following result −" }, { "code": null, "e": 1796, "s": 1790, "text": "10\n20" }, { "code": null, "e": 1942, "s": 1796, "text": "The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop." }, { "code": null, "e": 2038, "s": 1942, "text": "In a for loop, the continue keyword causes control to immediately jump to the update statement." }, { "code": null, "e": 2125, "s": 2038, "text": "In a while loop or do/while loop, control immediately jumps to the Boolean expression." }, { "code": null, "e": 2190, "s": 2125, "text": "The syntax of a continue is a single statement inside any loop −" }, { "code": null, "e": 2200, "s": 2190, "text": "continue;" }, { "code": null, "e": 2210, "s": 2200, "text": "Live Demo" }, { "code": null, "e": 2487, "s": 2210, "text": "public class Test {\n public static void main(String args[]) {\n int [] numbers = {10, 20, 30, 40, 50};\n for(int x : numbers ) {\n if( x == 30 ) {\n continue;\n }\n System.out.print( x );\n System.out.print(\"\\n\");\n }\n }\n}" }, { "code": null, "e": 2528, "s": 2487, "text": "This will produce the following result −" }, { "code": null, "e": 2540, "s": 2528, "text": "10\n20\n40\n50" } ]
Bayes’ rule with a simple and practical example | by Tirthajyoti Sarkar | Towards Data Science
Bayes’ theorem (alternatively Bayes’ law or Bayes’ rule) has been called the most powerful rule of probability and statistics. It describes the probability of an event, based on prior knowledge of conditions that might be related to the event. For example, if a disease is related to age, then, using Bayes’ theorem, a person’s age can be used to more accurately assess the probability that they have the disease, compared to the assessment of the probability of disease made without knowledge of the person’s age. It is a powerful law of probability that brings in the concept of ‘subjectivity’ or ‘the degree of belief’ into the cold, hard statistical modeling. Bayes’ rule is the only mechanism that can be used to gradually update the probability of an event as the evidence or data is gathered sequentially. Bayes’ theorem is named after Reverend Thomas Bayes, who first used conditional probability to provide an algorithm (his Proposition 9) that uses evidence to calculate limits on an unknown parameter, published as An Essay towards solving a Problem in the Doctrine of Chances (1763). In what he called a scholium, Bayes extended his algorithm to any unknown prior cause. Independently of Bayes, Pierre-Simon Laplace in 1774, and later in his 1812 “Théorie analytique des probabilités” used conditional probability to formulate the relation of an updated posterior probability from a prior probability, given evidence. It is a powerful law of probability that brings in the concept of ‘subjectivity’ or ‘the degree of belief’ into the cold, hard statistical modeling. It is a logical way of doing data science. We start with a hypothesis and a degree of belief in that hypothesis. That means, based on domain expertise or prior knowledge, we assign a non-zero probability to that hypothesis. Then, we gather data and update our initial beliefs. If the data support the hypothesis then the probability goes up, if it does not match, then probability goes down. Sound’s simple and logical, doesn’t it? But traditionally, in the majority of statistical learning, the notion of prior is not used or not looked favorably. Also, the computational intricacies of Bayesian learning have prevented it from being mainstream for more than two hundred years. But things are changing now with the advent of Bayesian inference... If the data support the hypothesis then the probability goes up, if it does not match, then probability goes down. Bayesian statistics and modeling have had a recent resurgence with the global rise of AI and data-driven machine learning systems in all aspects of business, science, and technology. Bayesian inference is being applied to genetics, linguistics, image processing, brain imaging, cosmology, machine learning, epidemiology, psychology, forensic science, human object recognition, evolution, visual perception, ecology, and countless other fields where knowledge discovery and predictive analytics are playing a significant role. Bayesian statistics and modeling have had a recent resurgence with the global rise of AI and data-driven machine learning systems We will apply the Bayes’ rule to a problem of drug screening (e.g. mandatory testing for federal or many other jobs which promise a drug-free work environment). Suppose that a test for using a particular drug is 97% sensitive and 95% specific. That is, the test will produce 97% true positive results for drug users and 95% true negative results for non-drug users. These are the pieces of data that any screening test will have from their history of tests. Bayes’ rule allows us to use this kind of data-driven knowledge to calculate the final probability. Suppose, we also know that 0.5% of the general population are users of the drug. What is the probability that a randomly selected individual with a positive test is a drug user? Note, this is the crucial piece of ‘Prior’ which is a piece of generalized knowledge about the common prevalence rate. This is our prior belief about the probability of a random test subject being a drug user. That means if we choose a random person from the general population, without any testing, we can only say that there is a 0.5% chance of that person being a drug-user. How to use Bayes’ rule then, in this situation? We will write a custom function that accepts the test capabilities and the prior knowledge of drug user percentage as input and produces the output probability of a test-taker being a user based on a positive result. Here is the formula for computing as per the Bayes’ rule... The actual code is here. If we run the function with the given data, we get the following result, Even with a test that is 97% correct for catching positive cases, and 95% correct for rejecting negative cases, the true probability of being a drug-user with a positive result is only 8.9%! If you look at the computations, this is because of the extremely low prevalence rate. The number of false positives outweighs the number of true positives. For example, if 1000 individuals are tested, there are expected to be 995 non-users and 5 users. From the 995 non-users, 0.05 × 995 ≃ 50 false positives are expected. From the 5 users, 0.95 × 5 ≈ 5 true positives are expected. Out of 55 positive results, only 5 are genuine! Let’s see how the probability changes with the prevalence rate. The code is here. Note, your decision depends on the probability threshold. Currently, it is set to 0.5. You can lower it if necessary. But, at the threshold of 0.5, you need to have an almost 4.8% prevalence rate to catch a user with a single positive test result. We saw that the test sensitivity and specificity impact this computation strongly. So, we may like to see what kind of capabilities are needed to improve the likelihood of catching drug users. The Python code is here. The plots above clearly show that even with close to 100% sensitivity, we don’t gain much at all. However, the probability response is highly non-linear with respect to the specificity of the test and as it reaches perfection, we get a large increase in the probability. Therefore, all R&D efforts should be focused on how to improve the specificity of the test. This conclusion can be intuitively derived from the fact that the main issue with having low probability is the low prevalence rate. Therefore, catching non-users correctly (i.e. improving specificity) is the area where we should focus on because they are much larger in numbers than the user. Negative examples are much higher in number than the Positive examples in this problem. Therefore, the True Negative performance of the test should be excellent. The best thing about Bayesian inference is the ability to use prior knowledge in the form of a Prior probability term in the numerator of the Bayes’ theorem. In this setting of drug screening, the prior knowledge is nothing but the computed probability of a test which is then fed back to the next test. That means, for these cases, where the prevalence rate in the general population is extremely low, one way to increase confidence is to prescribe subsequent test if the first test result is positive. The posterior probability from the first test becomes the Prior for the second test i.e. the P(user) is not the general prevalence rate anymore for this second test, but the probability from the first test. Here is the simple code for demonstrating the chaining. When we run this code, we get the following, The test-taker may not be an userProbability of the test-taker being a drug user, in the first round of test, is: 0.089The test-taker could be an userProbability of the test-taker being a drug user, in the second round of test, is: 0.654The test-taker could be an userProbability of the test-taker being a drug user, in the third round of test, is: 0.973 When we run the test the first time, the output (posterior) probability is low, only 8.9%, but that goes up significantly up to 65.4% with the second test, and the third positive test puts the posterior at 97.3%. Therefore, a test, which is unable to screen a user first time, can be used multiple times to update our belief with the successive application of Bayes’ rule. The best thing about Bayesian inference is the ability to use prior knowledge in the form of a Prior probability term in the numerator of the Bayes’ theorem. In this article, we show the basics and application of one of the most powerful laws of statistics — Bayes’ theorem. Advanced probabilistic modeling and inference process that utilizes this law, has taken over the world of data science and analytics in recent years. We demonstrated the application of Bayes’ rule using a very simple yet practical example of drug-screen testing and associated Python code. We showed how the test limitations impact the predicted probability and which aspect of the test needs to be improved for a high-confidence screen. We further showed how multiple Bayesian calculations can be chained together to compute the overall posterior and the true power of Bayesian reasoning. For further reading and resources, you can refer to these excellent articles, https://www.mathsisfun.com/data/bayes-theorem.htmlhttps://betterexplained.com/articles/an-intuitive-and-short-explanation-of-bayes-theorem/ https://www.mathsisfun.com/data/bayes-theorem.html https://betterexplained.com/articles/an-intuitive-and-short-explanation-of-bayes-theorem/ If you have any questions or ideas to share, please contact the author at tirthajyoti[AT]gmail.com. Also, you can check the author’s GitHub repositories for code, ideas, and resources in machine learning and data science. If you are, like me, passionate about AI/machine learning/data science, please feel free to add me on LinkedIn or follow me on Twitter.
[ { "code": null, "e": 415, "s": 171, "text": "Bayes’ theorem (alternatively Bayes’ law or Bayes’ rule) has been called the most powerful rule of probability and statistics. It describes the probability of an event, based on prior knowledge of conditions that might be related to the event." }, { "code": null, "e": 686, "s": 415, "text": "For example, if a disease is related to age, then, using Bayes’ theorem, a person’s age can be used to more accurately assess the probability that they have the disease, compared to the assessment of the probability of disease made without knowledge of the person’s age." }, { "code": null, "e": 984, "s": 686, "text": "It is a powerful law of probability that brings in the concept of ‘subjectivity’ or ‘the degree of belief’ into the cold, hard statistical modeling. Bayes’ rule is the only mechanism that can be used to gradually update the probability of an event as the evidence or data is gathered sequentially." }, { "code": null, "e": 1354, "s": 984, "text": "Bayes’ theorem is named after Reverend Thomas Bayes, who first used conditional probability to provide an algorithm (his Proposition 9) that uses evidence to calculate limits on an unknown parameter, published as An Essay towards solving a Problem in the Doctrine of Chances (1763). In what he called a scholium, Bayes extended his algorithm to any unknown prior cause." }, { "code": null, "e": 1603, "s": 1354, "text": "Independently of Bayes, Pierre-Simon Laplace in 1774, and later in his 1812 “Théorie analytique des probabilités” used conditional probability to formulate the relation of an updated posterior probability from a prior probability, given evidence." }, { "code": null, "e": 1752, "s": 1603, "text": "It is a powerful law of probability that brings in the concept of ‘subjectivity’ or ‘the degree of belief’ into the cold, hard statistical modeling." }, { "code": null, "e": 1795, "s": 1752, "text": "It is a logical way of doing data science." }, { "code": null, "e": 1976, "s": 1795, "text": "We start with a hypothesis and a degree of belief in that hypothesis. That means, based on domain expertise or prior knowledge, we assign a non-zero probability to that hypothesis." }, { "code": null, "e": 2144, "s": 1976, "text": "Then, we gather data and update our initial beliefs. If the data support the hypothesis then the probability goes up, if it does not match, then probability goes down." }, { "code": null, "e": 2184, "s": 2144, "text": "Sound’s simple and logical, doesn’t it?" }, { "code": null, "e": 2431, "s": 2184, "text": "But traditionally, in the majority of statistical learning, the notion of prior is not used or not looked favorably. Also, the computational intricacies of Bayesian learning have prevented it from being mainstream for more than two hundred years." }, { "code": null, "e": 2500, "s": 2431, "text": "But things are changing now with the advent of Bayesian inference..." }, { "code": null, "e": 2615, "s": 2500, "text": "If the data support the hypothesis then the probability goes up, if it does not match, then probability goes down." }, { "code": null, "e": 2798, "s": 2615, "text": "Bayesian statistics and modeling have had a recent resurgence with the global rise of AI and data-driven machine learning systems in all aspects of business, science, and technology." }, { "code": null, "e": 3141, "s": 2798, "text": "Bayesian inference is being applied to genetics, linguistics, image processing, brain imaging, cosmology, machine learning, epidemiology, psychology, forensic science, human object recognition, evolution, visual perception, ecology, and countless other fields where knowledge discovery and predictive analytics are playing a significant role." }, { "code": null, "e": 3271, "s": 3141, "text": "Bayesian statistics and modeling have had a recent resurgence with the global rise of AI and data-driven machine learning systems" }, { "code": null, "e": 3432, "s": 3271, "text": "We will apply the Bayes’ rule to a problem of drug screening (e.g. mandatory testing for federal or many other jobs which promise a drug-free work environment)." }, { "code": null, "e": 3829, "s": 3432, "text": "Suppose that a test for using a particular drug is 97% sensitive and 95% specific. That is, the test will produce 97% true positive results for drug users and 95% true negative results for non-drug users. These are the pieces of data that any screening test will have from their history of tests. Bayes’ rule allows us to use this kind of data-driven knowledge to calculate the final probability." }, { "code": null, "e": 4007, "s": 3829, "text": "Suppose, we also know that 0.5% of the general population are users of the drug. What is the probability that a randomly selected individual with a positive test is a drug user?" }, { "code": null, "e": 4385, "s": 4007, "text": "Note, this is the crucial piece of ‘Prior’ which is a piece of generalized knowledge about the common prevalence rate. This is our prior belief about the probability of a random test subject being a drug user. That means if we choose a random person from the general population, without any testing, we can only say that there is a 0.5% chance of that person being a drug-user." }, { "code": null, "e": 4433, "s": 4385, "text": "How to use Bayes’ rule then, in this situation?" }, { "code": null, "e": 4650, "s": 4433, "text": "We will write a custom function that accepts the test capabilities and the prior knowledge of drug user percentage as input and produces the output probability of a test-taker being a user based on a positive result." }, { "code": null, "e": 4710, "s": 4650, "text": "Here is the formula for computing as per the Bayes’ rule..." }, { "code": null, "e": 4735, "s": 4710, "text": "The actual code is here." }, { "code": null, "e": 4808, "s": 4735, "text": "If we run the function with the given data, we get the following result," }, { "code": null, "e": 4999, "s": 4808, "text": "Even with a test that is 97% correct for catching positive cases, and 95% correct for rejecting negative cases, the true probability of being a drug-user with a positive result is only 8.9%!" }, { "code": null, "e": 5156, "s": 4999, "text": "If you look at the computations, this is because of the extremely low prevalence rate. The number of false positives outweighs the number of true positives." }, { "code": null, "e": 5431, "s": 5156, "text": "For example, if 1000 individuals are tested, there are expected to be 995 non-users and 5 users. From the 995 non-users, 0.05 × 995 ≃ 50 false positives are expected. From the 5 users, 0.95 × 5 ≈ 5 true positives are expected. Out of 55 positive results, only 5 are genuine!" }, { "code": null, "e": 5513, "s": 5431, "text": "Let’s see how the probability changes with the prevalence rate. The code is here." }, { "code": null, "e": 5761, "s": 5513, "text": "Note, your decision depends on the probability threshold. Currently, it is set to 0.5. You can lower it if necessary. But, at the threshold of 0.5, you need to have an almost 4.8% prevalence rate to catch a user with a single positive test result." }, { "code": null, "e": 5954, "s": 5761, "text": "We saw that the test sensitivity and specificity impact this computation strongly. So, we may like to see what kind of capabilities are needed to improve the likelihood of catching drug users." }, { "code": null, "e": 5979, "s": 5954, "text": "The Python code is here." }, { "code": null, "e": 6342, "s": 5979, "text": "The plots above clearly show that even with close to 100% sensitivity, we don’t gain much at all. However, the probability response is highly non-linear with respect to the specificity of the test and as it reaches perfection, we get a large increase in the probability. Therefore, all R&D efforts should be focused on how to improve the specificity of the test." }, { "code": null, "e": 6636, "s": 6342, "text": "This conclusion can be intuitively derived from the fact that the main issue with having low probability is the low prevalence rate. Therefore, catching non-users correctly (i.e. improving specificity) is the area where we should focus on because they are much larger in numbers than the user." }, { "code": null, "e": 6798, "s": 6636, "text": "Negative examples are much higher in number than the Positive examples in this problem. Therefore, the True Negative performance of the test should be excellent." }, { "code": null, "e": 6956, "s": 6798, "text": "The best thing about Bayesian inference is the ability to use prior knowledge in the form of a Prior probability term in the numerator of the Bayes’ theorem." }, { "code": null, "e": 7102, "s": 6956, "text": "In this setting of drug screening, the prior knowledge is nothing but the computed probability of a test which is then fed back to the next test." }, { "code": null, "e": 7302, "s": 7102, "text": "That means, for these cases, where the prevalence rate in the general population is extremely low, one way to increase confidence is to prescribe subsequent test if the first test result is positive." }, { "code": null, "e": 7509, "s": 7302, "text": "The posterior probability from the first test becomes the Prior for the second test i.e. the P(user) is not the general prevalence rate anymore for this second test, but the probability from the first test." }, { "code": null, "e": 7565, "s": 7509, "text": "Here is the simple code for demonstrating the chaining." }, { "code": null, "e": 7610, "s": 7565, "text": "When we run this code, we get the following," }, { "code": null, "e": 7965, "s": 7610, "text": "The test-taker may not be an userProbability of the test-taker being a drug user, in the first round of test, is: 0.089The test-taker could be an userProbability of the test-taker being a drug user, in the second round of test, is: 0.654The test-taker could be an userProbability of the test-taker being a drug user, in the third round of test, is: 0.973" }, { "code": null, "e": 8178, "s": 7965, "text": "When we run the test the first time, the output (posterior) probability is low, only 8.9%, but that goes up significantly up to 65.4% with the second test, and the third positive test puts the posterior at 97.3%." }, { "code": null, "e": 8338, "s": 8178, "text": "Therefore, a test, which is unable to screen a user first time, can be used multiple times to update our belief with the successive application of Bayes’ rule." }, { "code": null, "e": 8496, "s": 8338, "text": "The best thing about Bayesian inference is the ability to use prior knowledge in the form of a Prior probability term in the numerator of the Bayes’ theorem." }, { "code": null, "e": 8763, "s": 8496, "text": "In this article, we show the basics and application of one of the most powerful laws of statistics — Bayes’ theorem. Advanced probabilistic modeling and inference process that utilizes this law, has taken over the world of data science and analytics in recent years." }, { "code": null, "e": 9051, "s": 8763, "text": "We demonstrated the application of Bayes’ rule using a very simple yet practical example of drug-screen testing and associated Python code. We showed how the test limitations impact the predicted probability and which aspect of the test needs to be improved for a high-confidence screen." }, { "code": null, "e": 9203, "s": 9051, "text": "We further showed how multiple Bayesian calculations can be chained together to compute the overall posterior and the true power of Bayesian reasoning." }, { "code": null, "e": 9281, "s": 9203, "text": "For further reading and resources, you can refer to these excellent articles," }, { "code": null, "e": 9421, "s": 9281, "text": "https://www.mathsisfun.com/data/bayes-theorem.htmlhttps://betterexplained.com/articles/an-intuitive-and-short-explanation-of-bayes-theorem/" }, { "code": null, "e": 9472, "s": 9421, "text": "https://www.mathsisfun.com/data/bayes-theorem.html" }, { "code": null, "e": 9562, "s": 9472, "text": "https://betterexplained.com/articles/an-intuitive-and-short-explanation-of-bayes-theorem/" } ]
Bootstrap 4 .flex-grow-0|1 class
Use the .flex-grow-0|1 class in Bootstrap to allow a singly lex item to take up rest of the space in the flex. For example, the following takes rest of the space in the right − The above is set by adding flex-grow class for the last flex-item − <div class="d-flex mb-3"> <div class="p-2 bg-danger">P</div> <div class="p-2 bg-info">Q</div> <div class="p-2 flex-grow-1 bg-secondary">R</div> </div> Let us see the following example to implement flex-grow-0|1 class − Live Demo <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> </head> <body> <div class="container mt-3"> <div class="d-flex mb-3"> <div class="p-2 bg-danger">P</div> <div class="p-2 bg-info">Q</div> <div class="p-2 flex-grow-1 bg-secondary">R</div> </div> <div class="d-flex mb-3"> <div class="p-2 bg-success">P</div> <div class="p-2 flex-grow-1 bg-primary">Q</div> <div class="p-2 bg-info">R</div> </div> </div> </body> </html>
[ { "code": null, "e": 1173, "s": 1062, "text": "Use the .flex-grow-0|1 class in Bootstrap to allow a singly lex item to take up rest of the space in the flex." }, { "code": null, "e": 1239, "s": 1173, "text": "For example, the following takes rest of the space in the right −" }, { "code": null, "e": 1307, "s": 1239, "text": "The above is set by adding flex-grow class for the last flex-item −" }, { "code": null, "e": 1464, "s": 1307, "text": "<div class=\"d-flex mb-3\">\n <div class=\"p-2 bg-danger\">P</div>\n <div class=\"p-2 bg-info\">Q</div>\n <div class=\"p-2 flex-grow-1 bg-secondary\">R</div>\n</div>" }, { "code": null, "e": 1532, "s": 1464, "text": "Let us see the following example to implement flex-grow-0|1 class −" }, { "code": null, "e": 1542, "s": 1532, "text": "Live Demo" }, { "code": null, "e": 2443, "s": 1542, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n\n<body>\n <div class=\"container mt-3\">\n <div class=\"d-flex mb-3\">\n <div class=\"p-2 bg-danger\">P</div>\n <div class=\"p-2 bg-info\">Q</div>\n <div class=\"p-2 flex-grow-1 bg-secondary\">R</div>\n </div>\n <div class=\"d-flex mb-3\">\n <div class=\"p-2 bg-success\">P</div>\n <div class=\"p-2 flex-grow-1 bg-primary\">Q</div>\n <div class=\"p-2 bg-info\">R</div>\n </div>\n </div>\n\n</body>\n</html>" } ]
Mahout - Recommendation
This chapter covers the popular machine learning technique called recommendation, its mechanisms, and how to write an application implementing Mahout recommendation. Ever wondered how Amazon comes up with a list of recommended items to draw your attention to a particular product that you might be interested in! Suppose you want to purchase the book “Mahout in Action” from Amazon: Along with the selected product, Amazon also displays a list of related recommended items, as shown below. Such recommendation lists are produced with the help of recommender engines. Mahout provides recommender engines of several types such as: user-based recommenders, item-based recommenders, and several other algorithms. Mahout has a non-distributed, non-Hadoop-based recommender engine. You should pass a text document having user preferences for items. And the output of this engine would be the estimated preferences of a particular user for other items. Consider a website that sells consumer goods such as mobiles, gadgets, and their accessories. If we want to implement the features of Mahout in such a site, then we can build a recommender engine. This engine analyzes past purchase data of the users and recommends new products based on that. The components provided by Mahout to build a recommender engine are as follows: DataModel UserSimilarity ItemSimilarity UserNeighborhood Recommender From the data store, the data model is prepared and is passed as an input to the recommender engine. The Recommender engine generates the recommendations for a particular user. Given below is the architecture of recommender engine. Here are the steps to develop a simple recommender: The constructor of PearsonCorrelationSimilarity class requires a data model object, which holds a file that contains the Users, Items, and Preferences details of a product. Here is the sample data model file: 1,00,1.0 1,01,2.0 1,02,5.0 1,03,5.0 1,04,5.0 2,00,1.0 2,01,2.0 2,05,5.0 2,06,4.5 2,02,5.0 3,01,2.5 3,02,5.0 3,03,4.0 3,04,3.0 4,00,5.0 4,01,5.0 4,02,5.0 4,03,0.0 The DataModel object requires the file object, which contains the path of the input file. Create the DataModel object as shown below. DataModel datamodel = new FileDataModel(new File("input file")); Create UserSimilarity object using PearsonCorrelationSimilarity class as shown below: UserSimilarity similarity = new PearsonCorrelationSimilarity(datamodel); This object computes a "neighborhood" of users like a given user. There are two types of neighborhoods: NearestNUserNeighborhood - This class computes a neighborhood consisting of the nearest n users to a given user. "Nearest" is defined by the given UserSimilarity. NearestNUserNeighborhood - This class computes a neighborhood consisting of the nearest n users to a given user. "Nearest" is defined by the given UserSimilarity. ThresholdUserNeighborhood - This class computes a neighborhood consisting of all the users whose similarity to the given user meets or exceeds a certain threshold. Similarity is defined by the given UserSimilarity. ThresholdUserNeighborhood - This class computes a neighborhood consisting of all the users whose similarity to the given user meets or exceeds a certain threshold. Similarity is defined by the given UserSimilarity. Here we are using ThresholdUserNeighborhood and set the limit of preference to 3.0. UserNeighborhood neighborhood = new ThresholdUserNeighborhood(3.0, similarity, model); Create UserbasedRecomender object. Pass all the above created objects to its constructor as shown below. UserBasedRecommender recommender = new GenericUserBasedRecommender(model, neighborhood, similarity); Recommend products to a user using the recommend() method of Recommender interface. This method requires two parameters. The first represents the user id of the user to whom we need to send the recommendations, and the second represents the number of recommendations to be sent. Here is the usage of recommender() method: List<RecommendedItem> recommendations = recommender.recommend(2, 3); for (RecommendedItem recommendation : recommendations) { System.out.println(recommendation); } Example Program Given below is an example program to set recommendation. Prepare the recommendations for the user with user id 2. import java.io.File; import java.util.List; import org.apache.mahout.cf.taste.impl.model.file.FileDataModel; import org.apache.mahout.cf.taste.impl.neighborhood.ThresholdUserNeighborhood; import org.apache.mahout.cf.taste.impl.recommender.GenericUserBasedRecommender; import org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity; import org.apache.mahout.cf.taste.model.DataModel; import org.apache.mahout.cf.taste.neighborhood.UserNeighborhood; import org.apache.mahout.cf.taste.recommender.RecommendedItem; import org.apache.mahout.cf.taste.recommender.UserBasedRecommender; import org.apache.mahout.cf.taste.similarity.UserSimilarity; public class Recommender { public static void main(String args[]){ try{ //Creating data model DataModel datamodel = new FileDataModel(new File("data")); //data //Creating UserSimilarity object. UserSimilarity usersimilarity = new PearsonCorrelationSimilarity(datamodel); //Creating UserNeighbourHHood object. UserNeighborhood userneighborhood = new ThresholdUserNeighborhood(3.0, usersimilarity, datamodel); //Create UserRecomender UserBasedRecommender recommender = new GenericUserBasedRecommender(datamodel, userneighborhood, usersimilarity); List<RecommendedItem> recommendations = recommender.recommend(2, 3); for (RecommendedItem recommendation : recommendations) { System.out.println(recommendation); } }catch(Exception e){} } } Compile the program using the following commands: javac Recommender.java java Recommender It should produce the following output: RecommendedItem [item:3, value:4.5] RecommendedItem [item:4, value:4.0] Print Add Notes Bookmark this page
[ { "code": null, "e": 1871, "s": 1705, "text": "This chapter covers the popular machine learning technique called recommendation, its mechanisms, and how to write an application implementing Mahout recommendation." }, { "code": null, "e": 2018, "s": 1871, "text": "Ever wondered how Amazon comes up with a list of recommended items to draw your attention to a particular product that you might be interested in!" }, { "code": null, "e": 2088, "s": 2018, "text": "Suppose you want to purchase the book “Mahout in Action” from Amazon:" }, { "code": null, "e": 2195, "s": 2088, "text": "Along with the selected product, Amazon also displays a list of related recommended\nitems, as shown below." }, { "code": null, "e": 2334, "s": 2195, "text": "Such recommendation lists are produced with the help of recommender engines.\nMahout provides recommender engines of several types such as:" }, { "code": null, "e": 2359, "s": 2334, "text": "user-based recommenders," }, { "code": null, "e": 2389, "s": 2359, "text": "item-based recommenders, and " }, { "code": null, "e": 2415, "s": 2389, "text": "several other algorithms." }, { "code": null, "e": 2652, "s": 2415, "text": "Mahout has a non-distributed, non-Hadoop-based recommender engine. You should pass a text document having user preferences for items. And the output of this engine would be the estimated preferences of a particular user for other items." }, { "code": null, "e": 2945, "s": 2652, "text": "Consider a website that sells consumer goods such as mobiles, gadgets, and their accessories. If we want to implement the features of Mahout in such a site, then we\ncan build a recommender engine. This engine analyzes past purchase data of the users\nand recommends new products based on that." }, { "code": null, "e": 3025, "s": 2945, "text": "The components provided by Mahout to build a recommender engine are as follows:" }, { "code": null, "e": 3035, "s": 3025, "text": "DataModel" }, { "code": null, "e": 3050, "s": 3035, "text": "UserSimilarity" }, { "code": null, "e": 3065, "s": 3050, "text": "ItemSimilarity" }, { "code": null, "e": 3082, "s": 3065, "text": "UserNeighborhood" }, { "code": null, "e": 3095, "s": 3082, "text": " Recommender" }, { "code": null, "e": 3327, "s": 3095, "text": "From the data store, the data model is prepared and is passed as an input to the recommender engine. The Recommender engine generates the recommendations for a particular user. Given below is the architecture of recommender engine." }, { "code": null, "e": 3379, "s": 3327, "text": "Here are the steps to develop a simple recommender:" }, { "code": null, "e": 3588, "s": 3379, "text": "The constructor of PearsonCorrelationSimilarity class requires a data model\nobject, which holds a file that contains the Users, Items, and Preferences details of a\nproduct. Here is the sample data model file:" }, { "code": null, "e": 3754, "s": 3588, "text": "1,00,1.0\n1,01,2.0\n1,02,5.0\n1,03,5.0\n1,04,5.0\n\n2,00,1.0\n2,01,2.0\n2,05,5.0\n2,06,4.5\n2,02,5.0\n\n3,01,2.5\n3,02,5.0\n3,03,4.0\n3,04,3.0\n\n4,00,5.0\n4,01,5.0\n4,02,5.0\n4,03,0.0\n" }, { "code": null, "e": 3888, "s": 3754, "text": "The DataModel object requires the file object, which contains the path of the input file. Create the DataModel object as shown below." }, { "code": null, "e": 3954, "s": 3888, "text": "DataModel datamodel = new FileDataModel(new File(\"input file\"));\n" }, { "code": null, "e": 4040, "s": 3954, "text": "Create UserSimilarity object using PearsonCorrelationSimilarity class as shown below:" }, { "code": null, "e": 4114, "s": 4040, "text": "UserSimilarity similarity = new PearsonCorrelationSimilarity(datamodel);\n" }, { "code": null, "e": 4218, "s": 4114, "text": "This object computes a \"neighborhood\" of users like a given user. There are two types\nof neighborhoods:" }, { "code": null, "e": 4381, "s": 4218, "text": "NearestNUserNeighborhood - This class computes a neighborhood\nconsisting of the nearest n users to a given user. \"Nearest\" is defined by the\ngiven UserSimilarity." }, { "code": null, "e": 4544, "s": 4381, "text": "NearestNUserNeighborhood - This class computes a neighborhood\nconsisting of the nearest n users to a given user. \"Nearest\" is defined by the\ngiven UserSimilarity." }, { "code": null, "e": 4759, "s": 4544, "text": "ThresholdUserNeighborhood - This class computes a neighborhood\nconsisting of all the users whose similarity to the given user meets or exceeds\na certain threshold. Similarity is defined by the given UserSimilarity." }, { "code": null, "e": 4974, "s": 4759, "text": "ThresholdUserNeighborhood - This class computes a neighborhood\nconsisting of all the users whose similarity to the given user meets or exceeds\na certain threshold. Similarity is defined by the given UserSimilarity." }, { "code": null, "e": 5058, "s": 4974, "text": "Here we are using ThresholdUserNeighborhood and set the limit of preference to\n3.0." }, { "code": null, "e": 5146, "s": 5058, "text": "UserNeighborhood neighborhood = new ThresholdUserNeighborhood(3.0, similarity, model);\n" }, { "code": null, "e": 5251, "s": 5146, "text": "Create UserbasedRecomender object. Pass all the above created objects to its constructor as shown below." }, { "code": null, "e": 5353, "s": 5251, "text": "UserBasedRecommender recommender = new GenericUserBasedRecommender(model, neighborhood, similarity);\n" }, { "code": null, "e": 5675, "s": 5353, "text": "Recommend products to a user using the recommend() method of Recommender interface. This method requires two parameters. The first represents the user id of the user to whom we need to send the recommendations, and the second represents the number of recommendations to be sent. Here is the usage of recommender() method:" }, { "code": null, "e": 5845, "s": 5675, "text": "List<RecommendedItem> recommendations = recommender.recommend(2, 3);\n\nfor (RecommendedItem recommendation : recommendations) {\n System.out.println(recommendation);\n }\n" }, { "code": null, "e": 5861, "s": 5845, "text": "Example Program" }, { "code": null, "e": 5975, "s": 5861, "text": "Given below is an example program to set recommendation. Prepare the recommendations for the user with user id 2." }, { "code": null, "e": 7550, "s": 5975, "text": "import java.io.File;\nimport java.util.List;\n\nimport org.apache.mahout.cf.taste.impl.model.file.FileDataModel;\nimport org.apache.mahout.cf.taste.impl.neighborhood.ThresholdUserNeighborhood;\nimport org.apache.mahout.cf.taste.impl.recommender.GenericUserBasedRecommender;\nimport org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity;\n\nimport org.apache.mahout.cf.taste.model.DataModel;\nimport org.apache.mahout.cf.taste.neighborhood.UserNeighborhood;\n\nimport org.apache.mahout.cf.taste.recommender.RecommendedItem;\nimport org.apache.mahout.cf.taste.recommender.UserBasedRecommender;\n\nimport org.apache.mahout.cf.taste.similarity.UserSimilarity;\n\npublic class Recommender {\n public static void main(String args[]){\n try{\n //Creating data model\n DataModel datamodel = new FileDataModel(new File(\"data\")); //data\n \n //Creating UserSimilarity object.\n UserSimilarity usersimilarity = new PearsonCorrelationSimilarity(datamodel);\n \n //Creating UserNeighbourHHood object.\n UserNeighborhood userneighborhood = new ThresholdUserNeighborhood(3.0, usersimilarity, datamodel);\n \n //Create UserRecomender\n UserBasedRecommender recommender = new GenericUserBasedRecommender(datamodel, userneighborhood, usersimilarity);\n \n List<RecommendedItem> recommendations = recommender.recommend(2, 3);\n\t\t\t\n for (RecommendedItem recommendation : recommendations) {\n System.out.println(recommendation);\n }\n \n }catch(Exception e){}\n \n }\n }" }, { "code": null, "e": 7600, "s": 7550, "text": "Compile the program using the following commands:" }, { "code": null, "e": 7641, "s": 7600, "text": "javac Recommender.java\njava Recommender\n" }, { "code": null, "e": 7681, "s": 7641, "text": "It should produce the following output:" }, { "code": null, "e": 7754, "s": 7681, "text": "RecommendedItem [item:3, value:4.5]\nRecommendedItem [item:4, value:4.0]\n" }, { "code": null, "e": 7761, "s": 7754, "text": " Print" }, { "code": null, "e": 7772, "s": 7761, "text": " Add Notes" } ]
How to get and set form element values with jQuery?
To get a form value with jQuery, you need to use the val() function. To set a form value with jQuery, you need to use the val() function, but to pass it a new value. You can try to run the following code to learn how to get and set form element values with jQuery − Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#buttonSet").click(function () { $("#txtBox").val("Amit"); $("input:radio").val(["male"]); $("#buttonGet").removeAttr('disabled'); }); $("#buttonGet").click(function () { $("#result").html( $("#txtBox").val() + "<br/>" + $("input:radio[name=rd]:checked").val() ); }); }); </script> </head> <body> Name <br /> <input id="txtBox" type="text" /> <br /><br /> Gender <br /> <input type="radio" name="rd" value="male"/> Male <input type="radio" name="rd" value="female"/> Female <br /><br /> <input id="buttonSet" type="button" value="Set Values" /> <input id="buttonGet" type="button" value="Get Values" disabled="disabled" /> <p id="result"></p> </body> </html>
[ { "code": null, "e": 1228, "s": 1062, "text": "To get a form value with jQuery, you need to use the val() function. To set a form value with jQuery, you need to use the val() function, but to pass it a new value." }, { "code": null, "e": 1328, "s": 1228, "text": "You can try to run the following code to learn how to get and set form element values with jQuery −" }, { "code": null, "e": 1338, "s": 1328, "text": "Live Demo" }, { "code": null, "e": 2451, "s": 1338, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script>\n $(document).ready(function(){\n \n $(\"#buttonSet\").click(function () {\n $(\"#txtBox\").val(\"Amit\");\n $(\"input:radio\").val([\"male\"]);\n $(\"#buttonGet\").removeAttr('disabled');\n });\n $(\"#buttonGet\").click(function () {\n $(\"#result\").html(\n $(\"#txtBox\").val() + \"<br/>\" +\n $(\"input:radio[name=rd]:checked\").val()\n );\n });\n });\n </script>\n </head>\n <body>\n Name <br />\n <input id=\"txtBox\" type=\"text\" />\n <br /><br />\n Gender <br />\n <input type=\"radio\" name=\"rd\" value=\"male\"/> Male\n <input type=\"radio\" name=\"rd\" value=\"female\"/> Female\n <br /><br />\n <input id=\"buttonSet\" type=\"button\" value=\"Set Values\" />\n <input id=\"buttonGet\" type=\"button\" value=\"Get Values\" disabled=\"disabled\" />\n <p id=\"result\"></p>\n </body>\n</html>" } ]
Creation of virtual environments using Python
A Python package of a specific version may be needed while developing Python based applications. However if this version of same package is installed for system wide use, it might be conflicting with other application’s requirements. Hence it is desired to have side-by-side environments for each purpose to resolve compatibility issues. Virtual Environments allow Python packages to be installed in an isolated location for a particular application, rather than being installed globally. The venv module in standard library of Python is used to create virtual environment. A virtual environment is a directory in file system having its own copy of Python interpreter and other scripts. Following command creates a virtual environment in the named directory. C:\python37>python -m venv e:\testenv You will find a new directory created as specified. The above can optionally use following switches The 'scripts' folder under the ENV_DIR (in this case testenv) contains local copy of Python interpreter, pip installer and scripts to activate and deactivate the environment. activate activate.bat activate.ps1 deactivate.bat easy_install-3.7.exe easy_install.exe pip.exe pip3.7.exe pip3.exe python.exe pythonw.exe In order to start Python in the isolated environment, it must be activated first. For this purpose, 'activate.bat' must be invoked from command line. E:\testenv>scripts\activate (testenv) E:\testenv>python Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> Name of the virtual environment appears in parentheses to the left of DOS prompt. Now you can Python in virtual environment. If any package is installed using pip3 utility in virtual environment's scripts folder, it will be locally installed and will not be available for system wide use. Deactivate virtual environment To return to normal environment, the virtual environment should be disable using 'deactivate.bat' in scripts folder. >>> quit() (testenv) E:\testenv>scripts\deactivate E:\testenv> For Python versions before 3.3, use virtualenv which must be installed separately. The venv module defined EnvironmentBuilder class for programmatically creating virtual environment.
[ { "code": null, "e": 1400, "s": 1062, "text": "A Python package of a specific version may be needed while developing Python based applications. However if this version of same package is installed for system wide use, it might be conflicting with other application’s requirements. Hence it is desired to have side-by-side environments for each purpose to resolve compatibility issues." }, { "code": null, "e": 1551, "s": 1400, "text": "Virtual Environments allow Python packages to be installed in an isolated location for a particular application, rather than being installed globally." }, { "code": null, "e": 1821, "s": 1551, "text": "The venv module in standard library of Python is used to create virtual environment. A virtual environment is a directory in file system having its own copy of Python interpreter and other scripts. Following command creates a virtual environment in the named directory." }, { "code": null, "e": 1859, "s": 1821, "text": "C:\\python37>python -m venv e:\\testenv" }, { "code": null, "e": 1959, "s": 1859, "text": "You will find a new directory created as specified. The above can optionally use following switches" }, { "code": null, "e": 2134, "s": 1959, "text": "The 'scripts' folder under the ENV_DIR (in this case testenv) contains local copy of Python interpreter, pip installer and scripts to activate and deactivate the environment." }, { "code": null, "e": 2273, "s": 2134, "text": "activate\nactivate.bat\nactivate.ps1\ndeactivate.bat\neasy_install-3.7.exe\neasy_install.exe\npip.exe\npip3.7.exe\npip3.exe\npython.exe\npythonw.exe" }, { "code": null, "e": 2423, "s": 2273, "text": "In order to start Python in the isolated environment, it must be activated first. For this purpose, 'activate.bat' must be invoked from command line." }, { "code": null, "e": 2653, "s": 2423, "text": "E:\\testenv>scripts\\activate\n\n(testenv) E:\\testenv>python\nPython 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>>" }, { "code": null, "e": 2778, "s": 2653, "text": "Name of the virtual environment appears in parentheses to the left of DOS prompt. Now you can Python in virtual environment." }, { "code": null, "e": 2942, "s": 2778, "text": "If any package is installed using pip3 utility in virtual environment's scripts folder, it will be locally installed and will not be available for system wide use." }, { "code": null, "e": 2973, "s": 2942, "text": "Deactivate virtual environment" }, { "code": null, "e": 3090, "s": 2973, "text": "To return to normal environment, the virtual environment should be disable using 'deactivate.bat' in scripts folder." }, { "code": null, "e": 3154, "s": 3090, "text": ">>> quit()\n\n(testenv) E:\\testenv>scripts\\deactivate\nE:\\testenv>" }, { "code": null, "e": 3237, "s": 3154, "text": "For Python versions before 3.3, use virtualenv which must be installed separately." }, { "code": null, "e": 3337, "s": 3237, "text": "The venv module defined EnvironmentBuilder class for programmatically creating virtual environment." } ]
Setting Y-axis in Matplotlib using Pandas
To set Y-Axis in matplotlib using Pandas, we can take the following steps − Create a dictionary with the keys, x and y. Create a dictionary with the keys, x and y. Create a data frame using Pandas. Create a data frame using Pandas. Plot data points using Pandas plot, with ylim(0, 25) and xlim(0, 15). Plot data points using Pandas plot, with ylim(0, 25) and xlim(0, 15). To display the figure, use show() method. To display the figure, use show() method. import numpy as np import pandas as pd from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True d = dict( x=np.linspace(0, 10, 10), y=np.linspace(0, 10, 10)*2 ) df = pd.DataFrame(d) df.plot(kind="bar", ylim=(0, 25), xlim=(0, 15)) plt.show()
[ { "code": null, "e": 1138, "s": 1062, "text": "To set Y-Axis in matplotlib using Pandas, we can take the following steps −" }, { "code": null, "e": 1182, "s": 1138, "text": "Create a dictionary with the keys, x and y." }, { "code": null, "e": 1226, "s": 1182, "text": "Create a dictionary with the keys, x and y." }, { "code": null, "e": 1260, "s": 1226, "text": "Create a data frame using Pandas." }, { "code": null, "e": 1294, "s": 1260, "text": "Create a data frame using Pandas." }, { "code": null, "e": 1364, "s": 1294, "text": "Plot data points using Pandas plot, with ylim(0, 25) and xlim(0, 15)." }, { "code": null, "e": 1434, "s": 1364, "text": "Plot data points using Pandas plot, with ylim(0, 25) and xlim(0, 15)." }, { "code": null, "e": 1476, "s": 1434, "text": "To display the figure, use show() method." }, { "code": null, "e": 1518, "s": 1476, "text": "To display the figure, use show() method." }, { "code": null, "e": 1832, "s": 1518, "text": "import numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nd = dict(\n x=np.linspace(0, 10, 10),\n y=np.linspace(0, 10, 10)*2\n)\ndf = pd.DataFrame(d)\ndf.plot(kind=\"bar\", ylim=(0, 25), xlim=(0, 15))\nplt.show()" } ]
Binary Tree to Binary Search Tree Conversion - GeeksforGeeks
12 Jan, 2022 Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of Binary Tree. Examples Example 1 Input: 10 / \ 2 7 / \ 8 4 Output: 8 / \ 4 10 / \ 2 7 Example 2 Input: 10 / \ 30 15 / \ 20 5 Output: 15 / \ 10 20 / \ 5 30 Solution Following is a 3 step solution for converting Binary tree to Binary Search Tree. 1) Create a temp array arr[] that stores inorder traversal of the tree. This step takes O(n) time. 2) Sort the temp array arr[]. Time complexity of this step depends upon the sorting algorithm. In the following implementation, Quick Sort is used which takes (n^2) time. This can be done in O(nLogn) time using Heap Sort or Merge Sort. 3) Again do inorder traversal of tree and copy array elements to tree nodes one by one. This step takes O(n) time. Following is C implementation of the above approach. The main function to convert is highlighted in the following code. C++ C Java Python3 C# Javascript /* A program to convert Binary Tree to Binary Search Tree */#include <iostream>using namespace std; /* A binary tree node structure */struct node { int data; struct node* left; struct node* right;}; /* A helper function that stores inorder traversal of a tree rootedwith node */void storeInorder(struct node* node, int inorder[], int* index_ptr){ // Base Case if (node == NULL) return; /* first store the left subtree */ storeInorder(node->left, inorder, index_ptr); /* Copy the root's data */ inorder[*index_ptr] = node->data; (*index_ptr)++; // increase index for next entry /* finally store the right subtree */ storeInorder(node->right, inorder, index_ptr);} /* A helper function to count nodes in a Binary Tree */int countNodes(struct node* root){ if (root == NULL) return 0; return countNodes(root->left) + countNodes(root->right) + 1;} // Following function is needed for library function qsort()int compare(const void* a, const void* b){ return (*(int*)a - *(int*)b);} /* A helper function that copies contents of arr[] to Binary Tree.This function basically does Inorder traversal of Binary Tree andone by one copy arr[] elements to Binary Tree nodes */void arrayToBST(int* arr, struct node* root, int* index_ptr){ // Base Case if (root == NULL) return; /* first update the left subtree */ arrayToBST(arr, root->left, index_ptr); /* Now update root's data and increment index */ root->data = arr[*index_ptr]; (*index_ptr)++; /* finally update the right subtree */ arrayToBST(arr, root->right, index_ptr);} // This function converts a given Binary Tree to BSTvoid binaryTreeToBST(struct node* root){ // base case: tree is empty if (root == NULL) return; /* Count the number of nodes in Binary Tree so that we know the size of temporary array to be created */ int n = countNodes(root); // Create a temp array arr[] and store inorder traversal of tree in arr[] int* arr = new int[n]; int i = 0; storeInorder(root, arr, &i); // Sort the array using library function for quick sort qsort(arr, n, sizeof(arr[0]), compare); // Copy array elements back to Binary Tree i = 0; arrayToBST(arr, root, &i); // delete dynamically allocated memory to avoid memory leak delete[] arr;} /* Utility function to create a new Binary Tree node */struct node* newNode(int data){ struct node* temp = new struct node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} /* Utility function to print inorder traversal of Binary Tree */void printInorder(struct node* node){ if (node == NULL) return; /* first recur on left child */ printInorder(node->left); /* then print the data of node */ cout <<" "<< node->data; /* now recur on right child */ printInorder(node->right);} /* Driver function to test above functions */int main(){ struct node* root = NULL; /* Constructing tree given in the above figure 10 / \ 30 15 / \ 20 5 */ root = newNode(10); root->left = newNode(30); root->right = newNode(15); root->left->left = newNode(20); root->right->right = newNode(5); // convert Binary Tree to BST binaryTreeToBST(root); cout <<"Following is Inorder Traversal of the converted BST:" << endl ; printInorder(root); return 0;} // This code is contributed by shivanisinghss2110 /* A program to convert Binary Tree to Binary Search Tree */#include <stdio.h>#include <stdlib.h> /* A binary tree node structure */struct node { int data; struct node* left; struct node* right;}; /* A helper function that stores inorder traversal of a tree rootedwith node */void storeInorder(struct node* node, int inorder[], int* index_ptr){ // Base Case if (node == NULL) return; /* first store the left subtree */ storeInorder(node->left, inorder, index_ptr); /* Copy the root's data */ inorder[*index_ptr] = node->data; (*index_ptr)++; // increase index for next entry /* finally store the right subtree */ storeInorder(node->right, inorder, index_ptr);} /* A helper function to count nodes in a Binary Tree */int countNodes(struct node* root){ if (root == NULL) return 0; return countNodes(root->left) + countNodes(root->right) + 1;} // Following function is needed for library function qsort()int compare(const void* a, const void* b){ return (*(int*)a - *(int*)b);} /* A helper function that copies contents of arr[] to Binary Tree.This function basically does Inorder traversal of Binary Tree andone by one copy arr[] elements to Binary Tree nodes */void arrayToBST(int* arr, struct node* root, int* index_ptr){ // Base Case if (root == NULL) return; /* first update the left subtree */ arrayToBST(arr, root->left, index_ptr); /* Now update root's data and increment index */ root->data = arr[*index_ptr]; (*index_ptr)++; /* finally update the right subtree */ arrayToBST(arr, root->right, index_ptr);} // This function converts a given Binary Tree to BSTvoid binaryTreeToBST(struct node* root){ // base case: tree is empty if (root == NULL) return; /* Count the number of nodes in Binary Tree so that we know the size of temporary array to be created */ int n = countNodes(root); // Create a temp array arr[] and store inorder traversal of tree in arr[] int* arr = new int[n]; int i = 0; storeInorder(root, arr, &i); // Sort the array using library function for quick sort qsort(arr, n, sizeof(arr[0]), compare); // Copy array elements back to Binary Tree i = 0; arrayToBST(arr, root, &i); // delete dynamically allocated memory to avoid memory leak delete[] arr;} /* Utility function to create a new Binary Tree node */struct node* newNode(int data){ struct node* temp = new struct node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} /* Utility function to print inorder traversal of Binary Tree */void printInorder(struct node* node){ if (node == NULL) return; /* first recur on left child */ printInorder(node->left); /* then print the data of node */ printf("%d ", node->data); /* now recur on right child */ printInorder(node->right);} /* Driver function to test above functions */int main(){ struct node* root = NULL; /* Constructing tree given in the above figure 10 / \ 30 15 / \ 20 5 */ root = newNode(10); root->left = newNode(30); root->right = newNode(15); root->left->left = newNode(20); root->right->right = newNode(5); // convert Binary Tree to BST binaryTreeToBST(root); printf("Following is Inorder Traversal of the converted BST: \n"); printInorder(root); return 0;} /* A program to convert Binary Tree to Binary Search Tree */import java.util.*; public class GFG{ /* A binary tree node structure */ static class Node { int data; Node left; Node right; }; // index pointer to pointer to the array index static int index; /* A helper function that stores inorder traversal of a tree rooted with node */ static void storeInorder(Node node, int inorder[]) { // Base Case if (node == null) return; /* first store the left subtree */ storeInorder(node.left, inorder); /* Copy the root's data */ inorder[index] = node.data; index++; // increase index for next entry /* finally store the right subtree */ storeInorder(node.right, inorder); } /* A helper function to count nodes in a Binary Tree */ static int countNodes(Node root) { if (root == null) return 0; return countNodes(root.left) + countNodes(root.right) + 1; } /* A helper function that copies contents of arr[] to Binary Tree. This function basically does Inorder traversal of Binary Tree and one by one copy arr[] elements to Binary Tree nodes */ static void arrayToBST(int[] arr, Node root) { // Base Case if (root == null) return; /* first update the left subtree */ arrayToBST(arr, root.left); /* Now update root's data and increment index */ root.data = arr[index]; index++; /* finally update the right subtree */ arrayToBST(arr, root.right); } // This function converts a given Binary Tree to BST static void binaryTreeToBST(Node root) { // base case: tree is empty if (root == null) return; /* Count the number of nodes in Binary Tree so that we know the size of temporary array to be created */ int n = countNodes(root); // Create a temp array arr[] and store inorder traversal of tree in arr[] int arr[] = new int[n]; storeInorder(root, arr); // Sort the array using library function for quick sort Arrays.sort(arr); // Copy array elements back to Binary Tree index = 0; arrayToBST(arr, root); } /* Utility function to create a new Binary Tree node */ static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } /* Utility function to print inorder traversal of Binary Tree */ static void printInorder(Node node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ System.out.print(node.data + " "); /* now recur on right child */ printInorder(node.right); } /* Driver function to test above functions */ public static void main(String args[]) { Node root = null; /* Constructing tree given in the above figure 10 / \ 30 15 / \ 20 5 */ root = newNode(10); root.left = newNode(30); root.right = newNode(15); root.left.left = newNode(20); root.right.right = newNode(5); // convert Binary Tree to BST binaryTreeToBST(root); System.out.println("Following is Inorder Traversal of the converted BST: "); printInorder(root); }} // This code is contributed by adityapande88. # Program to convert binary tree to BST # A binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Helper function to store the inorder traversal of a treedef storeInorder(root, inorder): # Base Case if root is None: return # First store the left subtree storeInorder(root.left, inorder) # Copy the root's data inorder.append(root.data) # Finally store the right subtree storeInorder(root.right, inorder) # A helper function to count nodes in a binary treedef countNodes(root): if root is None: return 0 return countNodes(root.left) + countNodes(root.right) + 1 # Helper function that copies contents of sorted array# to Binary treedef arrayToBST(arr, root): # Base Case if root is None: return # First update the left subtree arrayToBST(arr, root.left) # now update root's data delete the value from array root.data = arr[0] arr.pop(0) # Finally update the right subtree arrayToBST(arr, root.right) # This function converts a given binary tree to BSTdef binaryTreeToBST(root): # Base Case: Tree is empty if root is None: return # Count the number of nodes in Binary Tree so that # we know the size of temporary array to be created n = countNodes(root) # Create the temp array and store the inorder traversal # of tree arr = [] storeInorder(root, arr) # Sort the array arr.sort() # copy array elements back to binary tree arrayToBST(arr, root) # Print the inorder traversal of the treedef printInorder(root): if root is None: return printInorder(root.left) print (root.data,end=" ") printInorder(root.right) # Driver program to test above functionroot = Node(10)root.left = Node(30)root.right = Node(15)root.left.left = Node(20)root.right.right = Node(5) # Convert binary tree to BSTbinaryTreeToBST(root) print ("Following is the inorder traversal of the converted BST")printInorder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) using System; public class Node{ public int data; public Node left; public Node right;} public class GFG{ // index pointer to pointer to the array index static int index; /* A helper function that stores inorder traversal of a tree rooted with node */ static void storeInorder(Node node, int[] inorder) { // Base Case if (node == null) return; /* first store the left subtree */ storeInorder(node.left, inorder); /* Copy the root's data */ inorder[index] = node.data; index++; // increase index for next entry /* finally store the right subtree */ storeInorder(node.right, inorder); } /* A helper function to count nodes in a Binary Tree */ static int countNodes(Node root) { if (root == null) return 0; return countNodes(root.left) + countNodes(root.right) + 1; } /* A helper function that copies contents of arr[] to Binary Tree. This function basically does Inorder traversal of Binary Tree and one by one copy arr[] elements to Binary Tree nodes */ static void arrayToBST(int[] arr, Node root) { // Base Case if (root == null) return; /* first update the left subtree */ arrayToBST(arr, root.left); /* Now update root's data and increment index */ root.data = arr[index]; index++; /* finally update the right subtree */ arrayToBST(arr, root.right); } // This function converts a given Binary Tree to BST static void binaryTreeToBST(Node root) { // base case: tree is empty if (root == null) return; /* Count the number of nodes in Binary Tree so that we know the size of temporary array to be created */ int n = countNodes(root); // Create a temp array arr[] and store inorder traversal of tree in arr[] int[] arr = new int[n]; storeInorder(root, arr); // Sort the array using library function for quick sort Array.Sort(arr); // Copy array elements back to Binary Tree index = 0; arrayToBST(arr, root); } /* Utility function to create a new Binary Tree node */ static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } /* Utility function to print inorder traversal of Binary Tree */ static void printInorder(Node node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ Console.Write(node.data + " "); /* now recur on right child */ printInorder(node.right); } /* Driver function to test above functions */ static public void Main (){ Node root = null; /* Constructing tree given in the above figure 10 / \ 30 15 / \ 20 5 */ root = newNode(10); root.left = newNode(30); root.right = newNode(15); root.left.left = newNode(20); root.right.right = newNode(5); // convert Binary Tree to BST binaryTreeToBST(root); Console.WriteLine("Following is Inorder Traversal of the converted BST: "); printInorder(root); }} // This code is contributed by avanitrachhadiya2155 <script> /* A program to convert Binary Tree to Binary Search Tree */ class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // index pointer to pointer to the array index let index = 0; /* Utility function to create a new Binary Tree node */ function newNode(data) { let temp = new Node(data); return temp; } /* Utility function to print inorder traversal of Binary Tree */ function printInorder(node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ document.write(node.data + " "); /* now recur on right child */ printInorder(node.right); } /* A helper function that copies contents of arr[] to Binary Tree. This function basically does Inorder traversal of Binary Tree and one by one copy arr[] elements to Binary Tree nodes */ function arrayToBST(arr, root) { // Base Case if (root == null) return; /* first update the left subtree */ arrayToBST(arr, root.left); /* Now update root's data and increment index */ root.data = arr[index]; index++; /* finally update the right subtree */ arrayToBST(arr, root.right); } /* A helper function that stores inorder traversal of a tree rooted with node */ function storeInorder(node, inorder) { // Base Case if (node == null) return inorder; /* first store the left subtree */ storeInorder(node.left, inorder); /* Copy the root's data */ inorder[index] = node.data; index++; // increase index for next entry /* finally store the right subtree */ storeInorder(node.right, inorder); } /* A helper function to count nodes in a Binary Tree */ function countNodes(root) { if (root == null) return 0; return countNodes(root.left) + countNodes(root.right) + 1; } // This function converts a given Binary Tree to BST function binaryTreeToBST(root) { // base case: tree is empty if (root == null) return; /* Count the number of nodes in Binary Tree so that we know the size of temporary array to be created */ let n = countNodes(root); // Create a temp array arr[] and store // inorder traversal of tree in arr[] let arr = new Array(n); arr.fill(0); storeInorder(root, arr); // Sort the array using library function for quick sort arr.sort(function(a, b){return a - b}); // Copy array elements back to Binary Tree index = 0; arrayToBST(arr, root); } let root = null; /* Constructing tree given in the above figure 10 / \ 30 15 / \ 20 5 */ root = newNode(10); root.left = newNode(30); root.right = newNode(15); root.left.left = newNode(20); root.right.right = newNode(5); // convert Binary Tree to BST binaryTreeToBST(root); document.write( "Following is Inorder Traversal of the converted BST: "+ "</br>"); printInorder(root); </script> Following is the inorder traversal of the converted BST 5 10 15 20 30 Complexity Analysis: Time Complexity: O(nlogn). This is the complexity of the sorting algorithm which we are using after first in-order traversal, rest of the operations take place in linear time. Auxiliary Space: O(n). Use of data structure ‘array’ to store in-order traversal. We will be covering another method for this problem which converts the tree using O(height of the tree) extra space. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above bidibaaz123 Akanksha_Rai simmytarika5 adityapande88 decode2207 avanitrachhadiya2155 anikakapoor shivanisinghss2110 amartyaghoshgfg Amazon Binary Search Tree Tree Amazon Binary Search Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. AVL Tree | Set 1 (Insertion) A program to check if a binary tree is BST or not Inorder Successor in Binary Search Tree Red-Black Tree | Set 2 (Insert) Optimal Binary Search Tree | DP-24 Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Write a Program to Find the Maximum Depth or Height of a Tree Decision Tree A program to check if a binary tree is BST or not
[ { "code": null, "e": 37760, "s": 37732, "text": "\n12 Jan, 2022" }, { "code": null, "e": 37910, "s": 37760, "text": "Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of Binary Tree. " }, { "code": null, "e": 37919, "s": 37910, "text": "Examples" }, { "code": null, "e": 38254, "s": 37919, "text": "Example 1\nInput:\n 10\n / \\\n 2 7\n / \\\n 8 4\nOutput:\n 8\n / \\\n 4 10\n / \\\n 2 7\n\n\nExample 2\nInput:\n 10\n / \\\n 30 15\n / \\\n 20 5\nOutput:\n 15\n / \\\n 10 20\n / \\\n 5 30" }, { "code": null, "e": 38263, "s": 38254, "text": "Solution" }, { "code": null, "e": 38344, "s": 38263, "text": "Following is a 3 step solution for converting Binary tree to Binary Search Tree." }, { "code": null, "e": 38443, "s": 38344, "text": "1) Create a temp array arr[] that stores inorder traversal of the tree. This step takes O(n) time." }, { "code": null, "e": 38679, "s": 38443, "text": "2) Sort the temp array arr[]. Time complexity of this step depends upon the sorting algorithm. In the following implementation, Quick Sort is used which takes (n^2) time. This can be done in O(nLogn) time using Heap Sort or Merge Sort." }, { "code": null, "e": 38794, "s": 38679, "text": "3) Again do inorder traversal of tree and copy array elements to tree nodes one by one. This step takes O(n) time." }, { "code": null, "e": 38914, "s": 38794, "text": "Following is C implementation of the above approach. The main function to convert is highlighted in the following code." }, { "code": null, "e": 38918, "s": 38914, "text": "C++" }, { "code": null, "e": 38920, "s": 38918, "text": "C" }, { "code": null, "e": 38925, "s": 38920, "text": "Java" }, { "code": null, "e": 38933, "s": 38925, "text": "Python3" }, { "code": null, "e": 38936, "s": 38933, "text": "C#" }, { "code": null, "e": 38947, "s": 38936, "text": "Javascript" }, { "code": "/* A program to convert Binary Tree to Binary Search Tree */#include <iostream>using namespace std; /* A binary tree node structure */struct node { int data; struct node* left; struct node* right;}; /* A helper function that stores inorder traversal of a tree rootedwith node */void storeInorder(struct node* node, int inorder[], int* index_ptr){ // Base Case if (node == NULL) return; /* first store the left subtree */ storeInorder(node->left, inorder, index_ptr); /* Copy the root's data */ inorder[*index_ptr] = node->data; (*index_ptr)++; // increase index for next entry /* finally store the right subtree */ storeInorder(node->right, inorder, index_ptr);} /* A helper function to count nodes in a Binary Tree */int countNodes(struct node* root){ if (root == NULL) return 0; return countNodes(root->left) + countNodes(root->right) + 1;} // Following function is needed for library function qsort()int compare(const void* a, const void* b){ return (*(int*)a - *(int*)b);} /* A helper function that copies contents of arr[] to Binary Tree.This function basically does Inorder traversal of Binary Tree andone by one copy arr[] elements to Binary Tree nodes */void arrayToBST(int* arr, struct node* root, int* index_ptr){ // Base Case if (root == NULL) return; /* first update the left subtree */ arrayToBST(arr, root->left, index_ptr); /* Now update root's data and increment index */ root->data = arr[*index_ptr]; (*index_ptr)++; /* finally update the right subtree */ arrayToBST(arr, root->right, index_ptr);} // This function converts a given Binary Tree to BSTvoid binaryTreeToBST(struct node* root){ // base case: tree is empty if (root == NULL) return; /* Count the number of nodes in Binary Tree so that we know the size of temporary array to be created */ int n = countNodes(root); // Create a temp array arr[] and store inorder traversal of tree in arr[] int* arr = new int[n]; int i = 0; storeInorder(root, arr, &i); // Sort the array using library function for quick sort qsort(arr, n, sizeof(arr[0]), compare); // Copy array elements back to Binary Tree i = 0; arrayToBST(arr, root, &i); // delete dynamically allocated memory to avoid memory leak delete[] arr;} /* Utility function to create a new Binary Tree node */struct node* newNode(int data){ struct node* temp = new struct node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} /* Utility function to print inorder traversal of Binary Tree */void printInorder(struct node* node){ if (node == NULL) return; /* first recur on left child */ printInorder(node->left); /* then print the data of node */ cout <<\" \"<< node->data; /* now recur on right child */ printInorder(node->right);} /* Driver function to test above functions */int main(){ struct node* root = NULL; /* Constructing tree given in the above figure 10 / \\ 30 15 / \\ 20 5 */ root = newNode(10); root->left = newNode(30); root->right = newNode(15); root->left->left = newNode(20); root->right->right = newNode(5); // convert Binary Tree to BST binaryTreeToBST(root); cout <<\"Following is Inorder Traversal of the converted BST:\" << endl ; printInorder(root); return 0;} // This code is contributed by shivanisinghss2110", "e": 42405, "s": 38947, "text": null }, { "code": "/* A program to convert Binary Tree to Binary Search Tree */#include <stdio.h>#include <stdlib.h> /* A binary tree node structure */struct node { int data; struct node* left; struct node* right;}; /* A helper function that stores inorder traversal of a tree rootedwith node */void storeInorder(struct node* node, int inorder[], int* index_ptr){ // Base Case if (node == NULL) return; /* first store the left subtree */ storeInorder(node->left, inorder, index_ptr); /* Copy the root's data */ inorder[*index_ptr] = node->data; (*index_ptr)++; // increase index for next entry /* finally store the right subtree */ storeInorder(node->right, inorder, index_ptr);} /* A helper function to count nodes in a Binary Tree */int countNodes(struct node* root){ if (root == NULL) return 0; return countNodes(root->left) + countNodes(root->right) + 1;} // Following function is needed for library function qsort()int compare(const void* a, const void* b){ return (*(int*)a - *(int*)b);} /* A helper function that copies contents of arr[] to Binary Tree.This function basically does Inorder traversal of Binary Tree andone by one copy arr[] elements to Binary Tree nodes */void arrayToBST(int* arr, struct node* root, int* index_ptr){ // Base Case if (root == NULL) return; /* first update the left subtree */ arrayToBST(arr, root->left, index_ptr); /* Now update root's data and increment index */ root->data = arr[*index_ptr]; (*index_ptr)++; /* finally update the right subtree */ arrayToBST(arr, root->right, index_ptr);} // This function converts a given Binary Tree to BSTvoid binaryTreeToBST(struct node* root){ // base case: tree is empty if (root == NULL) return; /* Count the number of nodes in Binary Tree so that we know the size of temporary array to be created */ int n = countNodes(root); // Create a temp array arr[] and store inorder traversal of tree in arr[] int* arr = new int[n]; int i = 0; storeInorder(root, arr, &i); // Sort the array using library function for quick sort qsort(arr, n, sizeof(arr[0]), compare); // Copy array elements back to Binary Tree i = 0; arrayToBST(arr, root, &i); // delete dynamically allocated memory to avoid memory leak delete[] arr;} /* Utility function to create a new Binary Tree node */struct node* newNode(int data){ struct node* temp = new struct node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} /* Utility function to print inorder traversal of Binary Tree */void printInorder(struct node* node){ if (node == NULL) return; /* first recur on left child */ printInorder(node->left); /* then print the data of node */ printf(\"%d \", node->data); /* now recur on right child */ printInorder(node->right);} /* Driver function to test above functions */int main(){ struct node* root = NULL; /* Constructing tree given in the above figure 10 / \\ 30 15 / \\ 20 5 */ root = newNode(10); root->left = newNode(30); root->right = newNode(15); root->left->left = newNode(20); root->right->right = newNode(5); // convert Binary Tree to BST binaryTreeToBST(root); printf(\"Following is Inorder Traversal of the converted BST: \\n\"); printInorder(root); return 0;}", "e": 45807, "s": 42405, "text": null }, { "code": "/* A program to convert Binary Tree to Binary Search Tree */import java.util.*; public class GFG{ /* A binary tree node structure */ static class Node { int data; Node left; Node right; }; // index pointer to pointer to the array index static int index; /* A helper function that stores inorder traversal of a tree rooted with node */ static void storeInorder(Node node, int inorder[]) { // Base Case if (node == null) return; /* first store the left subtree */ storeInorder(node.left, inorder); /* Copy the root's data */ inorder[index] = node.data; index++; // increase index for next entry /* finally store the right subtree */ storeInorder(node.right, inorder); } /* A helper function to count nodes in a Binary Tree */ static int countNodes(Node root) { if (root == null) return 0; return countNodes(root.left) + countNodes(root.right) + 1; } /* A helper function that copies contents of arr[] to Binary Tree. This function basically does Inorder traversal of Binary Tree and one by one copy arr[] elements to Binary Tree nodes */ static void arrayToBST(int[] arr, Node root) { // Base Case if (root == null) return; /* first update the left subtree */ arrayToBST(arr, root.left); /* Now update root's data and increment index */ root.data = arr[index]; index++; /* finally update the right subtree */ arrayToBST(arr, root.right); } // This function converts a given Binary Tree to BST static void binaryTreeToBST(Node root) { // base case: tree is empty if (root == null) return; /* Count the number of nodes in Binary Tree so that we know the size of temporary array to be created */ int n = countNodes(root); // Create a temp array arr[] and store inorder traversal of tree in arr[] int arr[] = new int[n]; storeInorder(root, arr); // Sort the array using library function for quick sort Arrays.sort(arr); // Copy array elements back to Binary Tree index = 0; arrayToBST(arr, root); } /* Utility function to create a new Binary Tree node */ static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } /* Utility function to print inorder traversal of Binary Tree */ static void printInorder(Node node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ System.out.print(node.data + \" \"); /* now recur on right child */ printInorder(node.right); } /* Driver function to test above functions */ public static void main(String args[]) { Node root = null; /* Constructing tree given in the above figure 10 / \\ 30 15 / \\ 20 5 */ root = newNode(10); root.left = newNode(30); root.right = newNode(15); root.left.left = newNode(20); root.right.right = newNode(5); // convert Binary Tree to BST binaryTreeToBST(root); System.out.println(\"Following is Inorder Traversal of the converted BST: \"); printInorder(root); }} // This code is contributed by adityapande88.", "e": 49384, "s": 45807, "text": null }, { "code": "# Program to convert binary tree to BST # A binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Helper function to store the inorder traversal of a treedef storeInorder(root, inorder): # Base Case if root is None: return # First store the left subtree storeInorder(root.left, inorder) # Copy the root's data inorder.append(root.data) # Finally store the right subtree storeInorder(root.right, inorder) # A helper function to count nodes in a binary treedef countNodes(root): if root is None: return 0 return countNodes(root.left) + countNodes(root.right) + 1 # Helper function that copies contents of sorted array# to Binary treedef arrayToBST(arr, root): # Base Case if root is None: return # First update the left subtree arrayToBST(arr, root.left) # now update root's data delete the value from array root.data = arr[0] arr.pop(0) # Finally update the right subtree arrayToBST(arr, root.right) # This function converts a given binary tree to BSTdef binaryTreeToBST(root): # Base Case: Tree is empty if root is None: return # Count the number of nodes in Binary Tree so that # we know the size of temporary array to be created n = countNodes(root) # Create the temp array and store the inorder traversal # of tree arr = [] storeInorder(root, arr) # Sort the array arr.sort() # copy array elements back to binary tree arrayToBST(arr, root) # Print the inorder traversal of the treedef printInorder(root): if root is None: return printInorder(root.left) print (root.data,end=\" \") printInorder(root.right) # Driver program to test above functionroot = Node(10)root.left = Node(30)root.right = Node(15)root.left.left = Node(20)root.right.right = Node(5) # Convert binary tree to BSTbinaryTreeToBST(root) print (\"Following is the inorder traversal of the converted BST\")printInorder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 51541, "s": 49384, "text": null }, { "code": "using System; public class Node{ public int data; public Node left; public Node right;} public class GFG{ // index pointer to pointer to the array index static int index; /* A helper function that stores inorder traversal of a tree rooted with node */ static void storeInorder(Node node, int[] inorder) { // Base Case if (node == null) return; /* first store the left subtree */ storeInorder(node.left, inorder); /* Copy the root's data */ inorder[index] = node.data; index++; // increase index for next entry /* finally store the right subtree */ storeInorder(node.right, inorder); } /* A helper function to count nodes in a Binary Tree */ static int countNodes(Node root) { if (root == null) return 0; return countNodes(root.left) + countNodes(root.right) + 1; } /* A helper function that copies contents of arr[] to Binary Tree. This function basically does Inorder traversal of Binary Tree and one by one copy arr[] elements to Binary Tree nodes */ static void arrayToBST(int[] arr, Node root) { // Base Case if (root == null) return; /* first update the left subtree */ arrayToBST(arr, root.left); /* Now update root's data and increment index */ root.data = arr[index]; index++; /* finally update the right subtree */ arrayToBST(arr, root.right); } // This function converts a given Binary Tree to BST static void binaryTreeToBST(Node root) { // base case: tree is empty if (root == null) return; /* Count the number of nodes in Binary Tree so that we know the size of temporary array to be created */ int n = countNodes(root); // Create a temp array arr[] and store inorder traversal of tree in arr[] int[] arr = new int[n]; storeInorder(root, arr); // Sort the array using library function for quick sort Array.Sort(arr); // Copy array elements back to Binary Tree index = 0; arrayToBST(arr, root); } /* Utility function to create a new Binary Tree node */ static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } /* Utility function to print inorder traversal of Binary Tree */ static void printInorder(Node node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ Console.Write(node.data + \" \"); /* now recur on right child */ printInorder(node.right); } /* Driver function to test above functions */ static public void Main (){ Node root = null; /* Constructing tree given in the above figure 10 / \\ 30 15 / \\ 20 5 */ root = newNode(10); root.left = newNode(30); root.right = newNode(15); root.left.left = newNode(20); root.right.right = newNode(5); // convert Binary Tree to BST binaryTreeToBST(root); Console.WriteLine(\"Following is Inorder Traversal of the converted BST: \"); printInorder(root); }} // This code is contributed by avanitrachhadiya2155", "e": 55046, "s": 51541, "text": null }, { "code": "<script> /* A program to convert Binary Tree to Binary Search Tree */ class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // index pointer to pointer to the array index let index = 0; /* Utility function to create a new Binary Tree node */ function newNode(data) { let temp = new Node(data); return temp; } /* Utility function to print inorder traversal of Binary Tree */ function printInorder(node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ document.write(node.data + \" \"); /* now recur on right child */ printInorder(node.right); } /* A helper function that copies contents of arr[] to Binary Tree. This function basically does Inorder traversal of Binary Tree and one by one copy arr[] elements to Binary Tree nodes */ function arrayToBST(arr, root) { // Base Case if (root == null) return; /* first update the left subtree */ arrayToBST(arr, root.left); /* Now update root's data and increment index */ root.data = arr[index]; index++; /* finally update the right subtree */ arrayToBST(arr, root.right); } /* A helper function that stores inorder traversal of a tree rooted with node */ function storeInorder(node, inorder) { // Base Case if (node == null) return inorder; /* first store the left subtree */ storeInorder(node.left, inorder); /* Copy the root's data */ inorder[index] = node.data; index++; // increase index for next entry /* finally store the right subtree */ storeInorder(node.right, inorder); } /* A helper function to count nodes in a Binary Tree */ function countNodes(root) { if (root == null) return 0; return countNodes(root.left) + countNodes(root.right) + 1; } // This function converts a given Binary Tree to BST function binaryTreeToBST(root) { // base case: tree is empty if (root == null) return; /* Count the number of nodes in Binary Tree so that we know the size of temporary array to be created */ let n = countNodes(root); // Create a temp array arr[] and store // inorder traversal of tree in arr[] let arr = new Array(n); arr.fill(0); storeInorder(root, arr); // Sort the array using library function for quick sort arr.sort(function(a, b){return a - b}); // Copy array elements back to Binary Tree index = 0; arrayToBST(arr, root); } let root = null; /* Constructing tree given in the above figure 10 / \\ 30 15 / \\ 20 5 */ root = newNode(10); root.left = newNode(30); root.right = newNode(15); root.left.left = newNode(20); root.right.right = newNode(5); // convert Binary Tree to BST binaryTreeToBST(root); document.write( \"Following is Inorder Traversal of the converted BST: \"+ \"</br>\"); printInorder(root); </script>", "e": 58462, "s": 55046, "text": null }, { "code": null, "e": 58532, "s": 58462, "text": "Following is the inorder traversal of the converted BST\n5 10 15 20 30" }, { "code": null, "e": 58553, "s": 58532, "text": "Complexity Analysis:" }, { "code": null, "e": 58729, "s": 58553, "text": "Time Complexity: O(nlogn). This is the complexity of the sorting algorithm which we are using after first in-order traversal, rest of the operations take place in linear time." }, { "code": null, "e": 58811, "s": 58729, "text": "Auxiliary Space: O(n). Use of data structure ‘array’ to store in-order traversal." }, { "code": null, "e": 58928, "s": 58811, "text": "We will be covering another method for this problem which converts the tree using O(height of the tree) extra space." }, { "code": null, "e": 59052, "s": 58928, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 59064, "s": 59052, "text": "bidibaaz123" }, { "code": null, "e": 59077, "s": 59064, "text": "Akanksha_Rai" }, { "code": null, "e": 59090, "s": 59077, "text": "simmytarika5" }, { "code": null, "e": 59104, "s": 59090, "text": "adityapande88" }, { "code": null, "e": 59115, "s": 59104, "text": "decode2207" }, { "code": null, "e": 59136, "s": 59115, "text": "avanitrachhadiya2155" }, { "code": null, "e": 59148, "s": 59136, "text": "anikakapoor" }, { "code": null, "e": 59167, "s": 59148, "text": "shivanisinghss2110" }, { "code": null, "e": 59183, "s": 59167, "text": "amartyaghoshgfg" }, { "code": null, "e": 59190, "s": 59183, "text": "Amazon" }, { "code": null, "e": 59209, "s": 59190, "text": "Binary Search Tree" }, { "code": null, "e": 59214, "s": 59209, "text": "Tree" }, { "code": null, "e": 59221, "s": 59214, "text": "Amazon" }, { "code": null, "e": 59240, "s": 59221, "text": "Binary Search Tree" }, { "code": null, "e": 59245, "s": 59240, "text": "Tree" }, { "code": null, "e": 59343, "s": 59245, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 59372, "s": 59343, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 59422, "s": 59372, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 59462, "s": 59422, "text": "Inorder Successor in Binary Search Tree" }, { "code": null, "e": 59494, "s": 59462, "text": "Red-Black Tree | Set 2 (Insert)" }, { "code": null, "e": 59529, "s": 59494, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 59563, "s": 59529, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 59592, "s": 59563, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 59654, "s": 59592, "text": "Write a Program to Find the Maximum Depth or Height of a Tree" }, { "code": null, "e": 59668, "s": 59654, "text": "Decision Tree" } ]
Check if a key is present in a C++ map or unordered_map - GeeksforGeeks
11 Oct, 2021 A C++ map and unordered_map are initialized to some keys and their respective mapped values. Examples: Input : Map : 1 -> 4, 2 -> 6, 4 -> 6 Check1 : 5, Check2 : 4 Output : 5 : Not present, 4 : Present C++ implementation : map unordered_map // CPP code to check if a// key is present in a map#include <bits/stdc++.h>using namespace std; // Function to check if the key is present or notstring check_key(map<int, int> m, int key){ // Key is not present if (m.find(key) == m.end()) return "Not Present"; return "Present";} // Driverint main(){ map<int, int> m; // Initializing keys and mapped values m[1] = 4; m[2] = 6; m[4] = 6; // Keys to be checked int check1 = 5, check2 = 4; // Function call cout << check1 << ": " << check_key(m, check1) << '\n'; cout << check2 << ": " << check_key(m, check2);} // CPP code to check if a key is present// in an unordered_map#include <bits/stdc++.h>using namespace std; // Function to check if the key is present or notstring check_key(unordered_map<int, int> m, int key){ // Key is not present if (m.find(key) == m.end()) return "Not Present"; return "Present";} // Driverint main(){ unordered_map<int, int> m; // Initialising keys and mapped values m[1] = 4; m[2] = 6; m[4] = 6; // Keys to be checked int check1 = 5, check2 = 4; // Function call cout << check1 << ": " << check_key(m, check1) << '\n'; cout << check2 << ": " << check_key(m, check2);} Output: 5: Not Present 4: Present Approach 2nd: we can also use the count function of the map in c++. Implementation: 1. Map C++ // CPP code to check if a// key is present in a map#include <bits/stdc++.h>using namespace std; // Function to check if the key is present or not using count()string check_key(map<int, int> m, int key){ // Key is not present if (m.count(key) == 0) return "Not Present"; return "Present";} // Driverint main(){ map<int, int> m; // Initializing keys and mapped values m[1] = 4; m[2] = 6; m[4] = 6; // Keys to be checked int check1 = 5, check2 = 4; // Function call cout << check1 << ": " << check_key(m, check1) << '\n'; cout << check2 << ": " << check_key(m, check2);} Output: 5: Not Present 4: Present 2. Unordered Map C++ // CPP code to check if a key is present// in an unordered_map#include <bits/stdc++.h>using namespace std; // Function to check if the key is present or not using count()string check_key(unordered_map<int, int> m, int key){ // Key is not present if (m.count(key) == 0) return "Not Present"; return "Present";} // Driverint main(){ unordered_map<int, int> m; // Initialising keys and mapped values m[1] = 4; m[2] = 6; m[4] = 6; // Keys to be checked int check1 = 5, check2 = 4; // Function call cout << check1 << ": " << check_key(m, check1) << '\n'; cout << check2 << ": " << check_key(m, check2);} Output: 5: Not Present 4: Present This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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. preethibr1 CoderSaty cpp-map cpp-unordered_map cpp-unordered_map-functions STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ C++ Classes and Objects Bitwise Operators in C/C++ Operator Overloading in C++ Socket Programming in C/C++ Constructors in C++ Virtual Function in C++ Multidimensional Arrays in C / C++ Templates in C++ with Examples Copy Constructor in C++
[ { "code": null, "e": 24587, "s": 24559, "text": "\n11 Oct, 2021" }, { "code": null, "e": 24692, "s": 24587, "text": "A C++ map and unordered_map are initialized to some keys and their respective mapped values. Examples: " }, { "code": null, "e": 24791, "s": 24692, "text": "Input : \nMap : 1 -> 4, 2 -> 6, 4 -> 6\nCheck1 : 5, Check2 : 4\nOutput : 5 : Not present, 4 : Present" }, { "code": null, "e": 24814, "s": 24791, "text": "C++ implementation : " }, { "code": null, "e": 24818, "s": 24814, "text": "map" }, { "code": null, "e": 24832, "s": 24818, "text": "unordered_map" }, { "code": "// CPP code to check if a// key is present in a map#include <bits/stdc++.h>using namespace std; // Function to check if the key is present or notstring check_key(map<int, int> m, int key){ // Key is not present if (m.find(key) == m.end()) return \"Not Present\"; return \"Present\";} // Driverint main(){ map<int, int> m; // Initializing keys and mapped values m[1] = 4; m[2] = 6; m[4] = 6; // Keys to be checked int check1 = 5, check2 = 4; // Function call cout << check1 << \": \" << check_key(m, check1) << '\\n'; cout << check2 << \": \" << check_key(m, check2);}", "e": 25441, "s": 24832, "text": null }, { "code": "// CPP code to check if a key is present// in an unordered_map#include <bits/stdc++.h>using namespace std; // Function to check if the key is present or notstring check_key(unordered_map<int, int> m, int key){ // Key is not present if (m.find(key) == m.end()) return \"Not Present\"; return \"Present\";} // Driverint main(){ unordered_map<int, int> m; // Initialising keys and mapped values m[1] = 4; m[2] = 6; m[4] = 6; // Keys to be checked int check1 = 5, check2 = 4; // Function call cout << check1 << \": \" << check_key(m, check1) << '\\n'; cout << check2 << \": \" << check_key(m, check2);}", "e": 26081, "s": 25441, "text": null }, { "code": null, "e": 26091, "s": 26081, "text": "Output: " }, { "code": null, "e": 26117, "s": 26091, "text": "5: Not Present\n4: Present" }, { "code": null, "e": 26132, "s": 26117, "text": "Approach 2nd: " }, { "code": null, "e": 26186, "s": 26132, "text": "we can also use the count function of the map in c++." }, { "code": null, "e": 26202, "s": 26186, "text": "Implementation:" }, { "code": null, "e": 26209, "s": 26202, "text": "1. Map" }, { "code": null, "e": 26213, "s": 26209, "text": "C++" }, { "code": "// CPP code to check if a// key is present in a map#include <bits/stdc++.h>using namespace std; // Function to check if the key is present or not using count()string check_key(map<int, int> m, int key){ // Key is not present if (m.count(key) == 0) return \"Not Present\"; return \"Present\";} // Driverint main(){ map<int, int> m; // Initializing keys and mapped values m[1] = 4; m[2] = 6; m[4] = 6; // Keys to be checked int check1 = 5, check2 = 4; // Function call cout << check1 << \": \" << check_key(m, check1) << '\\n'; cout << check2 << \": \" << check_key(m, check2);}", "e": 26831, "s": 26213, "text": null }, { "code": null, "e": 26839, "s": 26831, "text": "Output:" }, { "code": null, "e": 26854, "s": 26839, "text": "5: Not Present" }, { "code": null, "e": 26865, "s": 26854, "text": "4: Present" }, { "code": null, "e": 26882, "s": 26865, "text": "2. Unordered Map" }, { "code": null, "e": 26886, "s": 26882, "text": "C++" }, { "code": "// CPP code to check if a key is present// in an unordered_map#include <bits/stdc++.h>using namespace std; // Function to check if the key is present or not using count()string check_key(unordered_map<int, int> m, int key){ // Key is not present if (m.count(key) == 0) return \"Not Present\"; return \"Present\";} // Driverint main(){ unordered_map<int, int> m; // Initialising keys and mapped values m[1] = 4; m[2] = 6; m[4] = 6; // Keys to be checked int check1 = 5, check2 = 4; // Function call cout << check1 << \": \" << check_key(m, check1) << '\\n'; cout << check2 << \": \" << check_key(m, check2);}", "e": 27535, "s": 26886, "text": null }, { "code": null, "e": 27543, "s": 27535, "text": "Output:" }, { "code": null, "e": 27558, "s": 27543, "text": "5: Not Present" }, { "code": null, "e": 27569, "s": 27558, "text": "4: Present" }, { "code": null, "e": 27993, "s": 27569, "text": "This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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": 28004, "s": 27993, "text": "preethibr1" }, { "code": null, "e": 28014, "s": 28004, "text": "CoderSaty" }, { "code": null, "e": 28022, "s": 28014, "text": "cpp-map" }, { "code": null, "e": 28040, "s": 28022, "text": "cpp-unordered_map" }, { "code": null, "e": 28068, "s": 28040, "text": "cpp-unordered_map-functions" }, { "code": null, "e": 28072, "s": 28068, "text": "STL" }, { "code": null, "e": 28076, "s": 28072, "text": "C++" }, { "code": null, "e": 28080, "s": 28076, "text": "STL" }, { "code": null, "e": 28084, "s": 28080, "text": "CPP" }, { "code": null, "e": 28182, "s": 28084, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28201, "s": 28182, "text": "Inheritance in C++" }, { "code": null, "e": 28225, "s": 28201, "text": "C++ Classes and Objects" }, { "code": null, "e": 28252, "s": 28225, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 28280, "s": 28252, "text": "Operator Overloading in C++" }, { "code": null, "e": 28308, "s": 28280, "text": "Socket Programming in C/C++" }, { "code": null, "e": 28328, "s": 28308, "text": "Constructors in C++" }, { "code": null, "e": 28352, "s": 28328, "text": "Virtual Function in C++" }, { "code": null, "e": 28387, "s": 28352, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 28418, "s": 28387, "text": "Templates in C++ with Examples" } ]
How can competitive programming help you get a job? - GeeksforGeeks
03 Oct, 2018 Let us first know about competitive programming! Competitive Programming Competitive programming is a brain game which take place on the Internet or a local network in which programmers have to code according to the given constraints. Here programmers are referred as competitive coders. Many top notch companies like Google, Facebook host contests like Codejam and Hackercup respectively. Those who perform well in these contests are recognised by these companies and get offers to work with these tech giants. Why competitive programming? Why competitive programming? Publicly demonstrate your skillsCompetitive programmers are known for their problem solving skills. Like developers show their skills by making different projects, competitive programmers show their talent by taking part in different challenges which sites like Codeforces, Codechef, Topcoder, Hackerrank, Hackerearth and many more host frequently. Competitive programmers build their name and earn fame on these sites and as they perform good, people start to recognize them. Prepare you for a Technical InterviewAs you get used to solving harder and harder problem in contests, you will easily be able to answer questions asked in technical interview. Competitive programming also increases your problem solving speed which provides a edge to you over other applicants. Makes you desirable Candidate for major CompaniesBig companies like Apple, Google and Facebook want talented and smart people to work with them. So these companies keep an eye on those programmers who outperform worldwide in the contests which take place at world level. One such contest is ACM ICPC, it is like olympics for a competitive programmer. You will definitely get an opportunity to work with these companies if you perform well in world level contests. Makes you more faster and focussedYou will become faster in every aspect of your life. You start finish your tasks quickly in your real life as well. This is an excellent skill which you develop. It helps you become more focussed as your code gets accepted only when your all test cases passes. So you start developing a habit of analyzing each and every factor which can affect your code. Hence in life also you don’t miss any factor which remains unconsidered easily. Helps you solve Complicated ProblemsWhile solving a question in competitive programming, most of the time you get wrong answer and you face a failure. By solving lots of questions, you will overcome the fear of failure. Competitive Programmers perform under pressure and take out a solution which builds their real life problem facing skills.For example : You are opening a business, then you won’t have fear of failure. You will handle any situation which comes in your way and will overcome it easily. Guaranteed Brain ExerciseMany a times, we come across a condition when we think that I have not done anything productive today. By solving 2 or 3 problems and getting correct answer for that helps you feel motivated. You will feel that yes I have applied my brain in solving these problems, which boosts your motivation. Teaches you how to work in TeamsMany contests take place at individual level and many contests involve team participation. You give contest in a group of 2 or 3. So you start to learn how to approach a situation in a group. Some person has good dynamic programming, some code faster, some think of a solution faster. In this way you learn to divide the work in team.It helps when you are working a company and doing work in a project. It’s FUN!One of the biggest factor is that competitive programming gives you a real time fun. Many people play football, cricket. They get recognition from various people that this person is very good in that particular sport. In the same way when you do Competitive Programming, you compete at the world level, among your peers. You start getting fame and recognition from people that this person’s algorithmic approach is fantastic. It feels nice when you hear these kind of words. So it is thrilling to do Competitive Programming. Various platform where you can showcase your skills 1. Codeforces2. Codechef3. Topcoder4. Hackerearth5. Hackerrank Various yearly top competitions 1. ACM ICPC2. Codejam3. Hackercup So guys, start competitive programming today if you have not geared up. It definitely helps you get a good job. Related Article :Practice for cracking any coding interview Career-Advices Picked Competitive Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bits manipulation (Important tactics) Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming Top 15 Websites for Coding Challenges and Competitions Formatted output in Java Breadth First Traversal ( BFS ) on a 2D array Algorithm Library | C++ Magicians STL Algorithm What is Competitive Programming and How to Prepare for It? Understanding The Coin Change Problem With Dynamic Programming 7 Best Coding Challenge Websites in 2020
[ { "code": null, "e": 25009, "s": 24981, "text": "\n03 Oct, 2018" }, { "code": null, "e": 25058, "s": 25009, "text": "Let us first know about competitive programming!" }, { "code": null, "e": 25082, "s": 25058, "text": "Competitive Programming" }, { "code": null, "e": 25521, "s": 25082, "text": "Competitive programming is a brain game which take place on the Internet or a local network in which programmers have to code according to the given constraints. Here programmers are referred as competitive coders. Many top notch companies like Google, Facebook host contests like Codejam and Hackercup respectively. Those who perform well in these contests are recognised by these companies and get offers to work with these tech giants." }, { "code": null, "e": 25550, "s": 25521, "text": "Why competitive programming?" }, { "code": null, "e": 25579, "s": 25550, "text": "Why competitive programming?" }, { "code": null, "e": 26056, "s": 25579, "text": "Publicly demonstrate your skillsCompetitive programmers are known for their problem solving skills. Like developers show their skills by making different projects, competitive programmers show their talent by taking part in different challenges which sites like Codeforces, Codechef, Topcoder, Hackerrank, Hackerearth and many more host frequently. Competitive programmers build their name and earn fame on these sites and as they perform good, people start to recognize them." }, { "code": null, "e": 26351, "s": 26056, "text": "Prepare you for a Technical InterviewAs you get used to solving harder and harder problem in contests, you will easily be able to answer questions asked in technical interview. Competitive programming also increases your problem solving speed which provides a edge to you over other applicants." }, { "code": null, "e": 26815, "s": 26351, "text": "Makes you desirable Candidate for major CompaniesBig companies like Apple, Google and Facebook want talented and smart people to work with them. So these companies keep an eye on those programmers who outperform worldwide in the contests which take place at world level. One such contest is ACM ICPC, it is like olympics for a competitive programmer. You will definitely get an opportunity to work with these companies if you perform well in world level contests." }, { "code": null, "e": 27285, "s": 26815, "text": "Makes you more faster and focussedYou will become faster in every aspect of your life. You start finish your tasks quickly in your real life as well. This is an excellent skill which you develop. It helps you become more focussed as your code gets accepted only when your all test cases passes. So you start developing a habit of analyzing each and every factor which can affect your code. Hence in life also you don’t miss any factor which remains unconsidered easily." }, { "code": null, "e": 27789, "s": 27285, "text": "Helps you solve Complicated ProblemsWhile solving a question in competitive programming, most of the time you get wrong answer and you face a failure. By solving lots of questions, you will overcome the fear of failure. Competitive Programmers perform under pressure and take out a solution which builds their real life problem facing skills.For example : You are opening a business, then you won’t have fear of failure. You will handle any situation which comes in your way and will overcome it easily." }, { "code": null, "e": 28110, "s": 27789, "text": "Guaranteed Brain ExerciseMany a times, we come across a condition when we think that I have not done anything productive today. By solving 2 or 3 problems and getting correct answer for that helps you feel motivated. You will feel that yes I have applied my brain in solving these problems, which boosts your motivation." }, { "code": null, "e": 28545, "s": 28110, "text": "Teaches you how to work in TeamsMany contests take place at individual level and many contests involve team participation. You give contest in a group of 2 or 3. So you start to learn how to approach a situation in a group. Some person has good dynamic programming, some code faster, some think of a solution faster. In this way you learn to divide the work in team.It helps when you are working a company and doing work in a project." }, { "code": null, "e": 29079, "s": 28545, "text": "It’s FUN!One of the biggest factor is that competitive programming gives you a real time fun. Many people play football, cricket. They get recognition from various people that this person is very good in that particular sport. In the same way when you do Competitive Programming, you compete at the world level, among your peers. You start getting fame and recognition from people that this person’s algorithmic approach is fantastic. It feels nice when you hear these kind of words. So it is thrilling to do Competitive Programming." }, { "code": null, "e": 29131, "s": 29079, "text": "Various platform where you can showcase your skills" }, { "code": null, "e": 29194, "s": 29131, "text": "1. Codeforces2. Codechef3. Topcoder4. Hackerearth5. Hackerrank" }, { "code": null, "e": 29226, "s": 29194, "text": "Various yearly top competitions" }, { "code": null, "e": 29260, "s": 29226, "text": "1. ACM ICPC2. Codejam3. Hackercup" }, { "code": null, "e": 29372, "s": 29260, "text": "So guys, start competitive programming today if you have not geared up. It definitely helps you get a good job." }, { "code": null, "e": 29432, "s": 29372, "text": "Related Article :Practice for cracking any coding interview" }, { "code": null, "e": 29447, "s": 29432, "text": "Career-Advices" }, { "code": null, "e": 29454, "s": 29447, "text": "Picked" }, { "code": null, "e": 29478, "s": 29454, "text": "Competitive Programming" }, { "code": null, "e": 29576, "s": 29478, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29614, "s": 29576, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 29641, "s": 29614, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 29719, "s": 29641, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 29774, "s": 29719, "text": "Top 15 Websites for Coding Challenges and Competitions" }, { "code": null, "e": 29799, "s": 29774, "text": "Formatted output in Java" }, { "code": null, "e": 29845, "s": 29799, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 29893, "s": 29845, "text": "Algorithm Library | C++ Magicians STL Algorithm" }, { "code": null, "e": 29952, "s": 29893, "text": "What is Competitive Programming and How to Prepare for It?" }, { "code": null, "e": 30015, "s": 29952, "text": "Understanding The Coin Change Problem With Dynamic Programming" } ]
Generate a QR code in Node.js
07 Jun, 2022 In this article, we will discuss how to generate a QR code using Node.js. A QR code is a monochromatic matrix with embedded data that is used in manufacturing industries in order to label the products. Nowadays QR codes are being used for payments in UPI-based apps, some chatting apps like WhatsApp, and in the play store. These are some most common examples, but we can use QR code in our apps for a far better purpose. If we are creating a website using MEAN/MERN Stack or any JavaScript related technology, We can generate QR codes in order to build advanced apps. Let’s set up our workspace by executing these commands: Creating directory: npm init -y mkdir src cd src nano app.js Installing package: We need to install an npm package in order to work ahead. npm install qrcode There are two ways we can use this library to generate QR codes. The first one is used for development and testing. Another one is used for deployment. Let’s create the data that we want to hide in a QR code: let data = { name:"Employee Name", age:27, department:"Police", id:"aisuoiqu3234738jdhf100223" } We need to convert data into a String format using JSON.stringify() method so that further operations can be performed easily. // Converting into String data let stringdata = JSON.stringify(data) Two methods of qrcode package are used for encoding the data. The first method will print the code in the terminal itself. But this method will be useless for deployment. But it is good for testing purposes. 1. toString(text, [options], [cb(error, string)]) // Print the QR code to terminal QRCode.toString(stringdata,{type:'terminal'}, function (err, url) { if(err) return console.log("error occurred") console.log(url) }) 2. toDataURL(text, [options], [cb(error, url)]) // Get the base64 url QRCode.toDataURL(stringdata, function (err, url) { if(err) return console.log("error occurred") console.log(url) }) There is one additional toCanvas() method but its functionalities can be used within toDataURL() method. Index.js Javascript // Require the packageconst QRCode = require('qrcode') // Creating the datalet data = { name:"Employee Name", age:27, department:"Police", id:"aisuoiqu3234738jdhf100223"} // Converting the data into String formatlet stringdata = JSON.stringify(data) // Print the QR code to terminalQRCode.toString(stringdata,{type:'terminal'}, function (err, QRcode) { if(err) return console.log("error occurred") // Printing the generated code console.log(QRcode)}) // Converting the data into base64QRCode.toDataURL(stringdata, function (err, code) { if(err) return console.log("error occurred") // Printing the code console.log(code)}) Run index.js file using the following command: node index.js Output: mridulmanochagfg nikhatkhan11 Node.js-Misc JavaScript Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jun, 2022" }, { "code": null, "e": 597, "s": 28, "text": "In this article, we will discuss how to generate a QR code using Node.js. A QR code is a monochromatic matrix with embedded data that is used in manufacturing industries in order to label the products. Nowadays QR codes are being used for payments in UPI-based apps, some chatting apps like WhatsApp, and in the play store. These are some most common examples, but we can use QR code in our apps for a far better purpose. If we are creating a website using MEAN/MERN Stack or any JavaScript related technology, We can generate QR codes in order to build advanced apps." }, { "code": null, "e": 653, "s": 597, "text": "Let’s set up our workspace by executing these commands:" }, { "code": null, "e": 673, "s": 653, "text": "Creating directory:" }, { "code": null, "e": 714, "s": 673, "text": "npm init -y\nmkdir src\ncd src\nnano app.js" }, { "code": null, "e": 792, "s": 714, "text": "Installing package: We need to install an npm package in order to work ahead." }, { "code": null, "e": 811, "s": 792, "text": "npm install qrcode" }, { "code": null, "e": 963, "s": 811, "text": "There are two ways we can use this library to generate QR codes. The first one is used for development and testing. Another one is used for deployment." }, { "code": null, "e": 1020, "s": 963, "text": "Let’s create the data that we want to hide in a QR code:" }, { "code": null, "e": 1133, "s": 1020, "text": "let data = {\n name:\"Employee Name\",\n age:27,\n department:\"Police\",\n id:\"aisuoiqu3234738jdhf100223\"\n}" }, { "code": null, "e": 1260, "s": 1133, "text": "We need to convert data into a String format using JSON.stringify() method so that further operations can be performed easily." }, { "code": null, "e": 1329, "s": 1260, "text": "// Converting into String data\nlet stringdata = JSON.stringify(data)" }, { "code": null, "e": 1537, "s": 1329, "text": "Two methods of qrcode package are used for encoding the data. The first method will print the code in the terminal itself. But this method will be useless for deployment. But it is good for testing purposes." }, { "code": null, "e": 1587, "s": 1537, "text": "1. toString(text, [options], [cb(error, string)])" }, { "code": null, "e": 1760, "s": 1587, "text": "// Print the QR code to terminal\nQRCode.toString(stringdata,{type:'terminal'}, function (err, url) {\n if(err) return console.log(\"error occurred\")\n console.log(url)\n })" }, { "code": null, "e": 1808, "s": 1760, "text": "2. toDataURL(text, [options], [cb(error, url)])" }, { "code": null, "e": 1954, "s": 1808, "text": "// Get the base64 url\nQRCode.toDataURL(stringdata, function (err, url) {\n if(err) return console.log(\"error occurred\")\n console.log(url)\n})" }, { "code": null, "e": 2059, "s": 1954, "text": "There is one additional toCanvas() method but its functionalities can be used within toDataURL() method." }, { "code": null, "e": 2068, "s": 2059, "text": "Index.js" }, { "code": null, "e": 2079, "s": 2068, "text": "Javascript" }, { "code": "// Require the packageconst QRCode = require('qrcode') // Creating the datalet data = { name:\"Employee Name\", age:27, department:\"Police\", id:\"aisuoiqu3234738jdhf100223\"} // Converting the data into String formatlet stringdata = JSON.stringify(data) // Print the QR code to terminalQRCode.toString(stringdata,{type:'terminal'}, function (err, QRcode) { if(err) return console.log(\"error occurred\") // Printing the generated code console.log(QRcode)}) // Converting the data into base64QRCode.toDataURL(stringdata, function (err, code) { if(err) return console.log(\"error occurred\") // Printing the code console.log(code)})", "e": 2756, "s": 2079, "text": null }, { "code": null, "e": 2803, "s": 2756, "text": "Run index.js file using the following command:" }, { "code": null, "e": 2817, "s": 2803, "text": "node index.js" }, { "code": null, "e": 2825, "s": 2817, "text": "Output:" }, { "code": null, "e": 2842, "s": 2825, "text": "mridulmanochagfg" }, { "code": null, "e": 2855, "s": 2842, "text": "nikhatkhan11" }, { "code": null, "e": 2868, "s": 2855, "text": "Node.js-Misc" }, { "code": null, "e": 2879, "s": 2868, "text": "JavaScript" }, { "code": null, "e": 2887, "s": 2879, "text": "Node.js" }, { "code": null, "e": 2904, "s": 2887, "text": "Web Technologies" } ]
PATCH method – Python requests
24 Oct, 2021 Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make PATCH request to a specified URL using requests.patch() method. Before checking out the PATCH method, let’s figure out what a Http PATCH request is – PATCH is a request method supported by HTTP used by the World Wide Web. It is used for modify capabilities. The PATCH request only needs to contain the changes to the resource, not the complete resource. This resembles PUT, but the body contains a set of instructions describing how a resource currently residing on the server should be modified to produce a new version. This means that the PATCH body should not just be a modified part of the resource, but in some kind of patch language like JSON Patch or XML Patch. PATCH is neither safe nor idempotent. Python’s requests module provides in-built method called patch() for making a PATCH request to a specified URI.Syntax – requests.patch(url, params={key: value}, args) Example – Let’s try making a request to httpbin’s APIs for example purposes. Python3 import requests # Making a PATCH requestr = requests.patch('https://httpbin.org / patch', data ={'key':'value'}) # check status code for response received# success code - 200print(r) # print content of requestprint(r.content) save this file as request.py and through terminal run, python request.py Output – The PATCH method is a request method supported by the HTTP protocol for making partial changes to an existing resource. The PATCH method provides an entity containing a list of changes to be applied to the resource requested using the HTTP URI. The list of changes are supplied in the form of a PATCH document. If the requested resource does not exist then the server may create the resource depending on the PATCH document media type and permissions. The changes described in the PATCH document must be semantically well defined but can have a different media type than the resource being patched. Frameworks such as XML, JSON can be used in describing the changes in the PATCH document. The main difference between the PUT and PATCH method is that the PUT method uses the request URI to supply a modified version of the requested resource which replaces the original version of the resource whereas the PATCH method supplies a set of instructions to modify the resource. If the PATCH document is larger than the size of the new version of the resource sent by the PUT method then the PUT method is preferred. sweetyty Python-requests Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Oct, 2021" }, { "code": null, "e": 356, "s": 54, "text": "Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make PATCH request to a specified URL using requests.patch() method. Before checking out the PATCH method, let’s figure out what a Http PATCH request is – " }, { "code": null, "e": 915, "s": 356, "text": "PATCH is a request method supported by HTTP used by the World Wide Web. It is used for modify capabilities. The PATCH request only needs to contain the changes to the resource, not the complete resource. This resembles PUT, but the body contains a set of instructions describing how a resource currently residing on the server should be modified to produce a new version. This means that the PATCH body should not just be a modified part of the resource, but in some kind of patch language like JSON Patch or XML Patch. PATCH is neither safe nor idempotent. " }, { "code": null, "e": 1037, "s": 915, "text": "Python’s requests module provides in-built method called patch() for making a PATCH request to a specified URI.Syntax – " }, { "code": null, "e": 1084, "s": 1037, "text": "requests.patch(url, params={key: value}, args)" }, { "code": null, "e": 1163, "s": 1084, "text": "Example – Let’s try making a request to httpbin’s APIs for example purposes. " }, { "code": null, "e": 1171, "s": 1163, "text": "Python3" }, { "code": "import requests # Making a PATCH requestr = requests.patch('https://httpbin.org / patch', data ={'key':'value'}) # check status code for response received# success code - 200print(r) # print content of requestprint(r.content)", "e": 1397, "s": 1171, "text": null }, { "code": null, "e": 1454, "s": 1397, "text": "save this file as request.py and through terminal run, " }, { "code": null, "e": 1472, "s": 1454, "text": "python request.py" }, { "code": null, "e": 1483, "s": 1472, "text": "Output – " }, { "code": null, "e": 2175, "s": 1485, "text": "The PATCH method is a request method supported by the HTTP protocol for making partial changes to an existing resource. The PATCH method provides an entity containing a list of changes to be applied to the resource requested using the HTTP URI. The list of changes are supplied in the form of a PATCH document. If the requested resource does not exist then the server may create the resource depending on the PATCH document media type and permissions. The changes described in the PATCH document must be semantically well defined but can have a different media type than the resource being patched. Frameworks such as XML, JSON can be used in describing the changes in the PATCH document. " }, { "code": null, "e": 2598, "s": 2175, "text": "The main difference between the PUT and PATCH method is that the PUT method uses the request URI to supply a modified version of the requested resource which replaces the original version of the resource whereas the PATCH method supplies a set of instructions to modify the resource. If the PATCH document is larger than the size of the new version of the resource sent by the PUT method then the PUT method is preferred. " }, { "code": null, "e": 2607, "s": 2598, "text": "sweetyty" }, { "code": null, "e": 2623, "s": 2607, "text": "Python-requests" }, { "code": null, "e": 2630, "s": 2623, "text": "Python" } ]
Queue offer() method in Java
26 Sep, 2018 The offer(E e) method of Queue Interface inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. This method is preferable to add() method since this method does not throws an exception when the capacity of the container is full since it returns false. Syntax: boolean offer(E e) Parameters: This method accepts a mandatory parameter e which is the element to be inserted in the Queue. Returns: This method returns true on successful insertion else it returns false. Exceptions: The function throws four exceptions which are described as below: ClassCastException: when the class of the element to be entered prevents it from being added to this container. IllegalArgumentException: when some property of the element prevents it to be added to the queue. NullPointerException: when the element to be inserted is passed as null and the Queue’s interface does not allow null elements. Below programs illustrate offer() method of Queue: Program 1: With the help of LinkedBlockingDeque. // Java Program Demonstrate offer()// method of Queue import java.util.*;import java.util.concurrent.LinkedBlockingQueue; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedBlockingQueue<Integer>(3); if (Q.offer(10)) System.out.println("The Queue is not full" + " and 10 is inserted"); else System.out.println("The Queue is full"); if (Q.offer(15)) System.out.println("The Queue is not full" + " and 15 is inserted"); else System.out.println("The Queue is full"); if (Q.offer(25)) System.out.println("The Queue is not full" + " and 25 is inserted"); else System.out.println("The Queue is full"); if (Q.offer(20)) System.out.println("The Queue is not full" + " and 20 is inserted"); else System.out.println("The Queue is full"); // before removing print Queue System.out.println("Queue: " + Q); }} The Queue is not full and 10 is inserted The Queue is not full and 15 is inserted The Queue is not full and 25 is inserted The Queue is full Queue: [10, 15, 25] Program 2: With the help of ConcurrentLinkedDeque. // Java Program Demonstrate offer()// method of Queue import java.util.*;import java.util.concurrent.ConcurrentLinkedDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new ConcurrentLinkedDeque<Integer>(); if (Q.offer(10)) System.out.println("The Queue is not full" + " and 10 is inserted"); else System.out.println("The Queue is full"); if (Q.offer(15)) System.out.println("The Queue is not full" + " and 15 is inserted"); else System.out.println("The Queue is full"); if (Q.offer(25)) System.out.println("The Queue is not full" + " and 25 is inserted"); else System.out.println("The Queue is full"); if (Q.offer(20)) System.out.println("The Queue is not full" + " and 20 is inserted"); else System.out.println("The Queue is full"); // before removing print Queue System.out.println("Queue: " + Q); }} The Queue is not full and 10 is inserted The Queue is not full and 15 is inserted The Queue is not full and 25 is inserted The Queue is not full and 20 is inserted Queue: [10, 15, 25, 20] Program 3: With the help of ArrayDeque. // Java Program Demonstrate offer()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new ArrayDeque<Integer>(6); if (Q.offer(10)) System.out.println("The Queue is not full" + " and 10 is inserted"); else System.out.println("The Queue is full"); if (Q.offer(15)) System.out.println("The Queue is not full" + " and 15 is inserted"); else System.out.println("The Queue is full"); if (Q.offer(25)) System.out.println("The Queue is not full" + " and 25 is inserted"); else System.out.println("The Queue is full"); if (Q.offer(20)) System.out.println("The Queue is not full" + " and 20 is inserted"); else System.out.println("The Queue is full"); // before removing print Queue System.out.println("Queue: " + Q); }} The Queue is not full and 10 is inserted The Queue is not full and 15 is inserted The Queue is not full and 25 is inserted The Queue is not full and 20 is inserted Queue: [10, 15, 25, 20] Program 4: With the help of LinkedList. // Java Program Demonstrate offer()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedList<Integer>(); if (Q.offer(10)) System.out.println("The Queue is not full" + " and 10 is inserted"); else System.out.println("The Queue is full"); if (Q.offer(15)) System.out.println("The Queue is not full" + " and 15 is inserted"); else System.out.println("The Queue is full"); if (Q.offer(25)) System.out.println("The Queue is not full" + " and 25 is inserted"); else System.out.println("The Queue is full"); if (Q.offer(20)) System.out.println("The Queue is not full" + " and 20 is inserted"); else System.out.println("The Queue is full"); // before removing print Queue System.out.println("Queue: " + Q); }} The Queue is not full and 10 is inserted The Queue is not full and 15 is inserted The Queue is not full and 25 is inserted The Queue is not full and 20 is inserted Queue: [10, 15, 25, 20] Below programs illustrate exceptions thrown by this method: Program 5: To show NullPointerException. // Java Program Demonstrate offer()// method of Queue when Null is passed import java.util.*;import java.util.concurrent.LinkedBlockingQueue; public class GFG { public static void main(String[] args) throws NullPointerException { // create object of Queue Queue<Integer> Q = new LinkedBlockingQueue<Integer>(); // Add numbers to end of Deque Q.offer(7855642); Q.offer(35658786); Q.offer(5278367); try { // when null is inserted Q.offer(null); } catch (Exception e) { System.out.println("Exception: " + e); } }} Exception: java.lang.NullPointerException Note: The other two exceptions are internal and are caused depending on the compiler hence cannot be shown in the code. Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html#offer-E- Java - util package java-basics Java-Collections Java-Functions java-queue Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Sep, 2018" }, { "code": null, "e": 351, "s": 28, "text": "The offer(E e) method of Queue Interface inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. This method is preferable to add() method since this method does not throws an exception when the capacity of the container is full since it returns false." }, { "code": null, "e": 359, "s": 351, "text": "Syntax:" }, { "code": null, "e": 378, "s": 359, "text": "boolean offer(E e)" }, { "code": null, "e": 484, "s": 378, "text": "Parameters: This method accepts a mandatory parameter e which is the element to be inserted in the Queue." }, { "code": null, "e": 565, "s": 484, "text": "Returns: This method returns true on successful insertion else it returns false." }, { "code": null, "e": 643, "s": 565, "text": "Exceptions: The function throws four exceptions which are described as below:" }, { "code": null, "e": 755, "s": 643, "text": "ClassCastException: when the class of the element to be entered prevents it from being added to this container." }, { "code": null, "e": 853, "s": 755, "text": "IllegalArgumentException: when some property of the element prevents it to be added to the queue." }, { "code": null, "e": 981, "s": 853, "text": "NullPointerException: when the element to be inserted is passed as null and the Queue’s interface does not allow null elements." }, { "code": null, "e": 1032, "s": 981, "text": "Below programs illustrate offer() method of Queue:" }, { "code": null, "e": 1081, "s": 1032, "text": "Program 1: With the help of LinkedBlockingDeque." }, { "code": "// Java Program Demonstrate offer()// method of Queue import java.util.*;import java.util.concurrent.LinkedBlockingQueue; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedBlockingQueue<Integer>(3); if (Q.offer(10)) System.out.println(\"The Queue is not full\" + \" and 10 is inserted\"); else System.out.println(\"The Queue is full\"); if (Q.offer(15)) System.out.println(\"The Queue is not full\" + \" and 15 is inserted\"); else System.out.println(\"The Queue is full\"); if (Q.offer(25)) System.out.println(\"The Queue is not full\" + \" and 25 is inserted\"); else System.out.println(\"The Queue is full\"); if (Q.offer(20)) System.out.println(\"The Queue is not full\" + \" and 20 is inserted\"); else System.out.println(\"The Queue is full\"); // before removing print Queue System.out.println(\"Queue: \" + Q); }}", "e": 2304, "s": 1081, "text": null }, { "code": null, "e": 2466, "s": 2304, "text": "The Queue is not full and 10 is inserted\nThe Queue is not full and 15 is inserted\nThe Queue is not full and 25 is inserted\nThe Queue is full\nQueue: [10, 15, 25]\n" }, { "code": null, "e": 2517, "s": 2466, "text": "Program 2: With the help of ConcurrentLinkedDeque." }, { "code": "// Java Program Demonstrate offer()// method of Queue import java.util.*;import java.util.concurrent.ConcurrentLinkedDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new ConcurrentLinkedDeque<Integer>(); if (Q.offer(10)) System.out.println(\"The Queue is not full\" + \" and 10 is inserted\"); else System.out.println(\"The Queue is full\"); if (Q.offer(15)) System.out.println(\"The Queue is not full\" + \" and 15 is inserted\"); else System.out.println(\"The Queue is full\"); if (Q.offer(25)) System.out.println(\"The Queue is not full\" + \" and 25 is inserted\"); else System.out.println(\"The Queue is full\"); if (Q.offer(20)) System.out.println(\"The Queue is not full\" + \" and 20 is inserted\"); else System.out.println(\"The Queue is full\"); // before removing print Queue System.out.println(\"Queue: \" + Q); }}", "e": 3743, "s": 2517, "text": null }, { "code": null, "e": 3932, "s": 3743, "text": "The Queue is not full and 10 is inserted\nThe Queue is not full and 15 is inserted\nThe Queue is not full and 25 is inserted\nThe Queue is not full and 20 is inserted\nQueue: [10, 15, 25, 20]\n" }, { "code": null, "e": 3972, "s": 3932, "text": "Program 3: With the help of ArrayDeque." }, { "code": "// Java Program Demonstrate offer()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new ArrayDeque<Integer>(6); if (Q.offer(10)) System.out.println(\"The Queue is not full\" + \" and 10 is inserted\"); else System.out.println(\"The Queue is full\"); if (Q.offer(15)) System.out.println(\"The Queue is not full\" + \" and 15 is inserted\"); else System.out.println(\"The Queue is full\"); if (Q.offer(25)) System.out.println(\"The Queue is not full\" + \" and 25 is inserted\"); else System.out.println(\"The Queue is full\"); if (Q.offer(20)) System.out.println(\"The Queue is not full\" + \" and 20 is inserted\"); else System.out.println(\"The Queue is full\"); // before removing print Queue System.out.println(\"Queue: \" + Q); }}", "e": 5138, "s": 3972, "text": null }, { "code": null, "e": 5327, "s": 5138, "text": "The Queue is not full and 10 is inserted\nThe Queue is not full and 15 is inserted\nThe Queue is not full and 25 is inserted\nThe Queue is not full and 20 is inserted\nQueue: [10, 15, 25, 20]\n" }, { "code": null, "e": 5367, "s": 5327, "text": "Program 4: With the help of LinkedList." }, { "code": "// Java Program Demonstrate offer()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedList<Integer>(); if (Q.offer(10)) System.out.println(\"The Queue is not full\" + \" and 10 is inserted\"); else System.out.println(\"The Queue is full\"); if (Q.offer(15)) System.out.println(\"The Queue is not full\" + \" and 15 is inserted\"); else System.out.println(\"The Queue is full\"); if (Q.offer(25)) System.out.println(\"The Queue is not full\" + \" and 25 is inserted\"); else System.out.println(\"The Queue is full\"); if (Q.offer(20)) System.out.println(\"The Queue is not full\" + \" and 20 is inserted\"); else System.out.println(\"The Queue is full\"); // before removing print Queue System.out.println(\"Queue: \" + Q); }}", "e": 6532, "s": 5367, "text": null }, { "code": null, "e": 6721, "s": 6532, "text": "The Queue is not full and 10 is inserted\nThe Queue is not full and 15 is inserted\nThe Queue is not full and 25 is inserted\nThe Queue is not full and 20 is inserted\nQueue: [10, 15, 25, 20]\n" }, { "code": null, "e": 6781, "s": 6721, "text": "Below programs illustrate exceptions thrown by this method:" }, { "code": null, "e": 6822, "s": 6781, "text": "Program 5: To show NullPointerException." }, { "code": "// Java Program Demonstrate offer()// method of Queue when Null is passed import java.util.*;import java.util.concurrent.LinkedBlockingQueue; public class GFG { public static void main(String[] args) throws NullPointerException { // create object of Queue Queue<Integer> Q = new LinkedBlockingQueue<Integer>(); // Add numbers to end of Deque Q.offer(7855642); Q.offer(35658786); Q.offer(5278367); try { // when null is inserted Q.offer(null); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 7471, "s": 6822, "text": null }, { "code": null, "e": 7514, "s": 7471, "text": "Exception: java.lang.NullPointerException\n" }, { "code": null, "e": 7634, "s": 7514, "text": "Note: The other two exceptions are internal and are caused depending on the compiler hence cannot be shown in the code." }, { "code": null, "e": 7717, "s": 7634, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html#offer-E-" }, { "code": null, "e": 7737, "s": 7717, "text": "Java - util package" }, { "code": null, "e": 7749, "s": 7737, "text": "java-basics" }, { "code": null, "e": 7766, "s": 7749, "text": "Java-Collections" }, { "code": null, "e": 7781, "s": 7766, "text": "Java-Functions" }, { "code": null, "e": 7792, "s": 7781, "text": "java-queue" }, { "code": null, "e": 7797, "s": 7792, "text": "Java" }, { "code": null, "e": 7802, "s": 7797, "text": "Java" }, { "code": null, "e": 7819, "s": 7802, "text": "Java-Collections" } ]
Java Program for How to check if a given number is Fibonacci number?
06 Dec, 2018 Given a number ‘n’, how to check if n is a Fibonacci number. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, .. Examples : Input : 8 Output : Yes Input : 34 Output : Yes Input : 41 Output : No Following is an interesting property about Fibonacci numbers that can also be used to check if a given number is Fibonacci or not.A number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square (Source: Wiki). // Java program to check if x is a perfect square class GFG { // A utility method that returns true if x is perfect square static boolean isPerfectSquare(int x) { int s = (int)Math.sqrt(x); return (s * s == x); } // Returns true if n is a Fibonacci Number, else false static boolean isFibonacci(int n) { // n is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 or both // is a perfect square return isPerfectSquare(5 * n * n + 4) || isPerfectSquare(5 * n * n - 4); } // Driver method public static void main(String[] args) { for (int i = 1; i <= 10; i++) System.out.println(isFibonacci(i) ? i + " is a Fibonacci Number" : i + " is a not Fibonacci Number"); }}// This code is contributed by Nikita Tiwari 1 is a Fibonacci Number 2 is a Fibonacci Number 3 is a Fibonacci Number 4 is a not Fibonacci Number 5 is a Fibonacci Number 6 is a not Fibonacci Number 7 is a not Fibonacci Number 8 is a Fibonacci Number 9 is a not Fibonacci Number 10 is a not Fibonacci Number Please refer complete article on How to check if a given number is Fibonacci number? for more details! Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Dec, 2018" }, { "code": null, "e": 170, "s": 28, "text": "Given a number ‘n’, how to check if n is a Fibonacci number. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, .." }, { "code": null, "e": 181, "s": 170, "text": "Examples :" }, { "code": null, "e": 254, "s": 181, "text": "Input : 8\nOutput : Yes\n\nInput : 34\nOutput : Yes\n\nInput : 41\nOutput : No\n" }, { "code": null, "e": 497, "s": 254, "text": "Following is an interesting property about Fibonacci numbers that can also be used to check if a given number is Fibonacci or not.A number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square (Source: Wiki)." }, { "code": "// Java program to check if x is a perfect square class GFG { // A utility method that returns true if x is perfect square static boolean isPerfectSquare(int x) { int s = (int)Math.sqrt(x); return (s * s == x); } // Returns true if n is a Fibonacci Number, else false static boolean isFibonacci(int n) { // n is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 or both // is a perfect square return isPerfectSquare(5 * n * n + 4) || isPerfectSquare(5 * n * n - 4); } // Driver method public static void main(String[] args) { for (int i = 1; i <= 10; i++) System.out.println(isFibonacci(i) ? i + \" is a Fibonacci Number\" : i + \" is a not Fibonacci Number\"); }}// This code is contributed by Nikita Tiwari", "e": 1334, "s": 497, "text": null }, { "code": null, "e": 1596, "s": 1334, "text": "1 is a Fibonacci Number\n2 is a Fibonacci Number\n3 is a Fibonacci Number\n4 is a not Fibonacci Number\n5 is a Fibonacci Number\n6 is a not Fibonacci Number\n7 is a not Fibonacci Number\n8 is a Fibonacci Number\n9 is a not Fibonacci Number\n10 is a not Fibonacci Number\n" }, { "code": null, "e": 1699, "s": 1596, "text": "Please refer complete article on How to check if a given number is Fibonacci number? for more details!" }, { "code": null, "e": 1713, "s": 1699, "text": "Java Programs" } ]
Find the number of divisors of all numbers in the range [1, n]
08 Jun, 2022 Given an integer N. The task is to find the number of divisors of all the numbers in the range [1, N]. Examples: Input: N = 5 Output: 1 2 2 3 2 divisors(1) = 1 divisors(2) = 1 and 2 divisors(3) = 1 and 3 divisors(4) = 1, 2 and 4 divisors(5) = 1 and 5 Input: N = 10 Output: 1 2 2 3 2 4 2 4 3 4 Approach: Create an array arr[] of the size (N + 1) where arr[i] stores the number of divisors of i. Now for every j from the range [1, N], increment all the elements which are divisible by j. For example, if j = 3 then update arr[3], arr[6], arr[9], ... Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the number of divisors// of all numbers in the range [1, n]void findDivisors(int n){ // Array to store the count // of divisors int div[n + 1]; memset(div, 0, sizeof div); // For every number from 1 to n for (int i = 1; i <= n; i++) { // Increase divisors count for // every number divisible by i for (int j = 1; j * i <= n; j++) div[i * j]++; } // Print the divisors for (int i = 1; i <= n; i++) cout << div[i] << " ";} // Driver codeint main(){ int n = 10; findDivisors(n); return 0;} // Java implementation of the approach class GFG{ // Function to find the number of divisors // of all numbers in the range [1, n] static void findDivisors(int n) { // Array to store the count // of divisors int[] div = new int[n + 1]; // For every number from 1 to n for (int i = 1; i <= n; i++) { // Increase divisors count for // every number divisible by i for (int j = 1; j * i <= n; j++) div[i * j]++; } // Print the divisors for (int i = 1; i <= n; i++) System.out.print(div[i]+" "); } // Driver code public static void main(String args[]) { int n = 10; findDivisors(n); }} // This code is contributed by Ryuga # Python3 implementation of the approach# Function to find the number of divisors# of all numbers in the range [1,n]def findDivisors(n): # List to store the count # of divisors div = [0 for i in range(n + 1)] # For every number from 1 to n for i in range(1, n + 1): # Increase divisors count for # every number divisible by i for j in range(1, n + 1): if j * i <= n: div[i * j] += 1 # Print the divisors for i in range(1, n + 1): print(div[i], end = " ") # Driver Codeif __name__ == "__main__": n = 10 findDivisors(n) # This code is contributed by# Vivek Kumar Singh // C# implementation of the approachusing System; class GFG{ // Function to find the number of divisors// of all numbers in the range [1, n]static void findDivisors(int n){ // Array to store the count // of divisors int[] div = new int[n + 1]; // For every number from 1 to n for (int i = 1; i <= n; i++) { // Increase divisors count for // every number divisible by i for (int j = 1; j * i <= n; j++) div[i * j]++; } // Print the divisors for (int i = 1; i <= n; i++) Console.Write(div[i]+" ");} // Driver codestatic void Main(){ int n = 10; findDivisors(n);}} // This code is contributed by mits <?php// PHP implementation of the approach // Function to find the number of divisors// of all numbers in the range [1, n]function findDivisors($n){ // Array to store the count // of divisors $div = array_fill(0, $n + 2, 0); // For every number from 1 to n for ($i = 1; $i <= $n; $i++) { // Increase divisors count for // every number divisible by i for ($j = 1; $j * $i <= $n; $j++) $div[$i * $j]++; } // Print the divisors for ($i = 1; $i <= $n; $i++) echo $div[$i], " ";} // Driver code$n = 10;findDivisors($n); // This code is contributed// by Arnab Kundu?> <script> // Javascript implementation of the approach // Function to find the number of divisors// of all numbers in the range [1, n]function findDivisors(n){ // Array to store the count // of divisors let div = new Array(n + 1).fill(0); // For every number from 1 to n for(let i = 1; i <= n; i++) { // Increase divisors count for // every number divisible by i for(let j = 1; j * i <= n; j++) div[i * j]++; } // Print the divisors for(let i = 1; i <= n; i++) document.write(div[i] + " ");} // Driver codelet n = 10;findDivisors(n); // This code is contributed by souravmahato348 </script> 1 2 2 3 2 4 2 4 3 4 Time Complexity: O(n3/2)Auxiliary Space: O(n) Mithun Kumar ankthon andrew1234 Vivekkumar Singh souravmahato348 rishavnitro Competitive Programming Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jun, 2022" }, { "code": null, "e": 158, "s": 54, "text": "Given an integer N. The task is to find the number of divisors of all the numbers in the range [1, N]. " }, { "code": null, "e": 169, "s": 158, "text": "Examples: " }, { "code": null, "e": 307, "s": 169, "text": "Input: N = 5 Output: 1 2 2 3 2 divisors(1) = 1 divisors(2) = 1 and 2 divisors(3) = 1 and 3 divisors(4) = 1, 2 and 4 divisors(5) = 1 and 5" }, { "code": null, "e": 351, "s": 307, "text": "Input: N = 10 Output: 1 2 2 3 2 4 2 4 3 4 " }, { "code": null, "e": 606, "s": 351, "text": "Approach: Create an array arr[] of the size (N + 1) where arr[i] stores the number of divisors of i. Now for every j from the range [1, N], increment all the elements which are divisible by j. For example, if j = 3 then update arr[3], arr[6], arr[9], ..." }, { "code": null, "e": 659, "s": 606, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 663, "s": 659, "text": "C++" }, { "code": null, "e": 668, "s": 663, "text": "Java" }, { "code": null, "e": 676, "s": 668, "text": "Python3" }, { "code": null, "e": 679, "s": 676, "text": "C#" }, { "code": null, "e": 683, "s": 679, "text": "PHP" }, { "code": null, "e": 694, "s": 683, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the number of divisors// of all numbers in the range [1, n]void findDivisors(int n){ // Array to store the count // of divisors int div[n + 1]; memset(div, 0, sizeof div); // For every number from 1 to n for (int i = 1; i <= n; i++) { // Increase divisors count for // every number divisible by i for (int j = 1; j * i <= n; j++) div[i * j]++; } // Print the divisors for (int i = 1; i <= n; i++) cout << div[i] << \" \";} // Driver codeint main(){ int n = 10; findDivisors(n); return 0;}", "e": 1363, "s": 694, "text": null }, { "code": "// Java implementation of the approach class GFG{ // Function to find the number of divisors // of all numbers in the range [1, n] static void findDivisors(int n) { // Array to store the count // of divisors int[] div = new int[n + 1]; // For every number from 1 to n for (int i = 1; i <= n; i++) { // Increase divisors count for // every number divisible by i for (int j = 1; j * i <= n; j++) div[i * j]++; } // Print the divisors for (int i = 1; i <= n; i++) System.out.print(div[i]+\" \"); } // Driver code public static void main(String args[]) { int n = 10; findDivisors(n); }} // This code is contributed by Ryuga", "e": 2174, "s": 1363, "text": null }, { "code": "# Python3 implementation of the approach# Function to find the number of divisors# of all numbers in the range [1,n]def findDivisors(n): # List to store the count # of divisors div = [0 for i in range(n + 1)] # For every number from 1 to n for i in range(1, n + 1): # Increase divisors count for # every number divisible by i for j in range(1, n + 1): if j * i <= n: div[i * j] += 1 # Print the divisors for i in range(1, n + 1): print(div[i], end = \" \") # Driver Codeif __name__ == \"__main__\": n = 10 findDivisors(n) # This code is contributed by# Vivek Kumar Singh", "e": 2842, "s": 2174, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to find the number of divisors// of all numbers in the range [1, n]static void findDivisors(int n){ // Array to store the count // of divisors int[] div = new int[n + 1]; // For every number from 1 to n for (int i = 1; i <= n; i++) { // Increase divisors count for // every number divisible by i for (int j = 1; j * i <= n; j++) div[i * j]++; } // Print the divisors for (int i = 1; i <= n; i++) Console.Write(div[i]+\" \");} // Driver codestatic void Main(){ int n = 10; findDivisors(n);}} // This code is contributed by mits", "e": 3520, "s": 2842, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to find the number of divisors// of all numbers in the range [1, n]function findDivisors($n){ // Array to store the count // of divisors $div = array_fill(0, $n + 2, 0); // For every number from 1 to n for ($i = 1; $i <= $n; $i++) { // Increase divisors count for // every number divisible by i for ($j = 1; $j * $i <= $n; $j++) $div[$i * $j]++; } // Print the divisors for ($i = 1; $i <= $n; $i++) echo $div[$i], \" \";} // Driver code$n = 10;findDivisors($n); // This code is contributed// by Arnab Kundu?>", "e": 4156, "s": 3520, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to find the number of divisors// of all numbers in the range [1, n]function findDivisors(n){ // Array to store the count // of divisors let div = new Array(n + 1).fill(0); // For every number from 1 to n for(let i = 1; i <= n; i++) { // Increase divisors count for // every number divisible by i for(let j = 1; j * i <= n; j++) div[i * j]++; } // Print the divisors for(let i = 1; i <= n; i++) document.write(div[i] + \" \");} // Driver codelet n = 10;findDivisors(n); // This code is contributed by souravmahato348 </script>", "e": 4824, "s": 4156, "text": null }, { "code": null, "e": 4844, "s": 4824, "text": "1 2 2 3 2 4 2 4 3 4" }, { "code": null, "e": 4892, "s": 4846, "text": "Time Complexity: O(n3/2)Auxiliary Space: O(n)" }, { "code": null, "e": 4905, "s": 4892, "text": "Mithun Kumar" }, { "code": null, "e": 4913, "s": 4905, "text": "ankthon" }, { "code": null, "e": 4924, "s": 4913, "text": "andrew1234" }, { "code": null, "e": 4941, "s": 4924, "text": "Vivekkumar Singh" }, { "code": null, "e": 4957, "s": 4941, "text": "souravmahato348" }, { "code": null, "e": 4969, "s": 4957, "text": "rishavnitro" }, { "code": null, "e": 4993, "s": 4969, "text": "Competitive Programming" }, { "code": null, "e": 5006, "s": 4993, "text": "Mathematical" }, { "code": null, "e": 5019, "s": 5006, "text": "Mathematical" } ]
Convert a Data Frame into a Numeric Matrix in R Programming – data.matrix() Function
16 Jun, 2020 data.matrix() function in R Language is used to create a matrix by converting all the values of a Data Frame into numeric mode and then binding them as a matrix. Syntax: data.matrix(df) Parameters:df: Data frame to be converted. Example 1: # R program to convert a data frame# into a numeric matrix # Creating a dataframe df1 = data.frame( "Name" = c("Amar", "Akbar", "Ronald"), "Language" = c("R", "Python", "C#"), "Age" = c(26, 38, 22) ) # Printing data frameprint(df1) # Converting into numeric matrixdf2 <- data.matrix(df1)df2 Output: Name Language Age 1 Amar R 26 2 Akbar Python 38 3 Ronald C# 22 Name Language Age [1, ] 2 3 26 [2, ] 1 2 38 [3, ] 3 1 22 Example 2: # R program to convert a data frame# into a numeric matrix # Creating a dataframe df <- data.frame(sample(LETTERS[1:4], 8, replace = T), cbind(1:4, 1:8))colnames(df) <- c("x", "y", "z") # Printing data frameprint(df) # Converting into numeric matrixdf2 <- data.matrix(df)df2 Output: x y z 1 A 1 1 2 D 2 2 3 C 3 3 4 A 4 4 5 B 1 5 6 B 2 6 7 A 3 7 8 C 4 8 x y z [1, ] 1 1 1 [2, ] 4 2 2 [3, ] 3 3 3 [4, ] 1 4 4 [5, ] 2 1 5 [6, ] 2 2 6 [7, ] 1 3 7 [8, ] 3 4 8 R DataFrame-Function R Matrix-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n16 Jun, 2020" }, { "code": null, "e": 215, "s": 53, "text": "data.matrix() function in R Language is used to create a matrix by converting all the values of a Data Frame into numeric mode and then binding them as a matrix." }, { "code": null, "e": 239, "s": 215, "text": "Syntax: data.matrix(df)" }, { "code": null, "e": 282, "s": 239, "text": "Parameters:df: Data frame to be converted." }, { "code": null, "e": 293, "s": 282, "text": "Example 1:" }, { "code": "# R program to convert a data frame# into a numeric matrix # Creating a dataframe df1 = data.frame( \"Name\" = c(\"Amar\", \"Akbar\", \"Ronald\"), \"Language\" = c(\"R\", \"Python\", \"C#\"), \"Age\" = c(26, 38, 22) ) # Printing data frameprint(df1) # Converting into numeric matrixdf2 <- data.matrix(df1)df2", "e": 596, "s": 293, "text": null }, { "code": null, "e": 604, "s": 596, "text": "Output:" }, { "code": null, "e": 788, "s": 604, "text": " Name Language Age\n1 Amar R 26\n2 Akbar Python 38\n3 Ronald C# 22\n Name Language Age\n[1, ] 2 3 26\n[2, ] 1 2 38\n[3, ] 3 1 22\n" }, { "code": null, "e": 799, "s": 788, "text": "Example 2:" }, { "code": "# R program to convert a data frame# into a numeric matrix # Creating a dataframe df <- data.frame(sample(LETTERS[1:4], 8, replace = T), cbind(1:4, 1:8))colnames(df) <- c(\"x\", \"y\", \"z\") # Printing data frameprint(df) # Converting into numeric matrixdf2 <- data.matrix(df)df2", "e": 1096, "s": 799, "text": null }, { "code": null, "e": 1104, "s": 1096, "text": "Output:" }, { "code": null, "e": 1284, "s": 1104, "text": " x y z\n1 A 1 1\n2 D 2 2\n3 C 3 3\n4 A 4 4\n5 B 1 5\n6 B 2 6\n7 A 3 7\n8 C 4 8\n x y z\n[1, ] 1 1 1\n[2, ] 4 2 2\n[3, ] 3 3 3\n[4, ] 1 4 4\n[5, ] 2 1 5\n[6, ] 2 2 6\n[7, ] 1 3 7\n[8, ] 3 4 8\n" }, { "code": null, "e": 1305, "s": 1284, "text": "R DataFrame-Function" }, { "code": null, "e": 1323, "s": 1305, "text": "R Matrix-Function" }, { "code": null, "e": 1334, "s": 1323, "text": "R Language" } ]
pprint : Data pretty printer in Python
01 Sep, 2021 This article is about a pretty useful built-in module in Python, pprint. The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a well-formatted and more readable way! Let us consider an example: # A python code without pprintimport requests def geocode(address): url = "https://maps.googleapis.com/maps/api/geocode/json" resp = requests.get(url, params = {'address': address}) return resp.json() # calling geocode functiondata = geocode('India gate') # printing json responseprint(data) The above code is for getting the geocode information of a place using Google Maps API in JSON format. The output of above program looks like this: {'status': 'OK', 'results': [{'address_components': [{'long_name': 'Rajpath', 'types': ['route'], 'short_name': 'Rajpath'}, {'long_name': 'India Gate', 'types': ['political', 'sublocality', 'sublocality_level_1'], 'short_name': 'India Gate'}, {'long_name': 'New Delhi', 'types': ['locality', 'political'], 'short_name': 'New Delhi'}, {'long_name': 'New Delhi', 'types': ['administrative_area_level_2', 'political'], 'short_name': 'New Delhi'}, {'long_name': 'Delhi', 'types': ['administrative_area_level_1', 'political'], 'short_name': 'DL'}, {'long_name': 'India', 'types': ['country', 'political'], 'short_name': 'IN'}, {'long_name': '110001', 'types': ['postal_code'], 'short_name': '110001'}], 'geometry': {'location': {'lng': 77.2295097, 'lat': 28.612912}, 'viewport': {'northeast': {'lng': 77.2308586802915, 'lat': 28.6142609802915}, 'southwest': {'lng': 77.22816071970848, 'lat': 28.6115630197085}}, 'location_type': 'APPROXIMATE'}, 'types': ['establishment', 'point_of_interest'], 'formatted_address': 'Rajpath, India Gate, New Delhi, Delhi 110001, India', 'place_id': 'ChIJC03rqdriDDkRXT6SJRGXFwc'}]} As you can see, this output is not properly indented which affects readability for nested data structures. Now, consider the code below: # A python code with pprintimport requestsfrom pprint import pprint def geocode(address): url = "https://maps.googleapis.com/maps/api/geocode/json" resp = requests.get(url, params = {'address': address}) return resp.json() # calling geocode functiondata = geocode('India gate') # pretty-printing json responsepprint(data) The output of above code looks like this: {'results': [{'address_components': [{'long_name': 'Rajpath', 'short_name': 'Rajpath', 'types': ['route']}, {'long_name': 'India Gate', 'short_name': 'India Gate', 'types': ['political', 'sublocality', 'sublocality_level_1']}, {'long_name': 'New Delhi', 'short_name': 'New Delhi', 'types': ['locality', 'political']}, {'long_name': 'New Delhi', 'short_name': 'New Delhi', 'types': ['administrative_area_level_2', 'political']}, {'long_name': 'Delhi', 'short_name': 'DL', 'types': ['administrative_area_level_1', 'political']}, {'long_name': 'India', 'short_name': 'IN', 'types': ['country', 'political']}, {'long_name': '110001', 'short_name': '110001', 'types': ['postal_code']}], 'formatted_address': 'Rajpath, India Gate, New Delhi, Delhi ' '110001, India', 'geometry': {'location': {'lat': 28.612912, 'lng': 77.2295097}, 'location_type': 'APPROXIMATE', 'viewport': {'northeast': {'lat': 28.6142609802915, 'lng': 77.2308586802915}, 'southwest': {'lat': 28.6115630197085, 'lng': 77.22816071970848}}}, 'place_id': 'ChIJC03rqdriDDkRXT6SJRGXFwc', 'types': ['establishment', 'point_of_interest']}], 'status': 'OK'} As you can see, the output is now well formatted and much more readable. All we did was to import the pprint function of pprint module. And use pprint() function rather than the print function! This blog is contributed by Nikhil 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. surindertarika1234 Python-Library python-utility Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Convert integer to string in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Sep, 2021" }, { "code": null, "e": 125, "s": 52, "text": "This article is about a pretty useful built-in module in Python, pprint." }, { "code": null, "e": 259, "s": 125, "text": "The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a well-formatted and more readable way!" }, { "code": null, "e": 287, "s": 259, "text": "Let us consider an example:" }, { "code": "# A python code without pprintimport requests def geocode(address): url = \"https://maps.googleapis.com/maps/api/geocode/json\" resp = requests.get(url, params = {'address': address}) return resp.json() # calling geocode functiondata = geocode('India gate') # printing json responseprint(data)", "e": 588, "s": 287, "text": null }, { "code": null, "e": 691, "s": 588, "text": "The above code is for getting the geocode information of a place using Google Maps API in JSON format." }, { "code": null, "e": 736, "s": 691, "text": "The output of above program looks like this:" }, { "code": null, "e": 1857, "s": 736, "text": "{'status': 'OK', 'results': [{'address_components': [{'long_name': 'Rajpath', 'types': ['route'], \n'short_name': 'Rajpath'}, {'long_name': 'India Gate', 'types': ['political', 'sublocality', \n'sublocality_level_1'], 'short_name': 'India Gate'}, {'long_name': 'New Delhi', 'types': \n['locality', 'political'], 'short_name': 'New Delhi'}, {'long_name': 'New Delhi', \n'types': ['administrative_area_level_2', 'political'], 'short_name': 'New Delhi'}, {'long_name': \n'Delhi', 'types': ['administrative_area_level_1', 'political'], 'short_name': 'DL'}, {'long_name': \n'India', 'types': ['country', 'political'], 'short_name': 'IN'}, {'long_name': '110001', 'types': \n['postal_code'], 'short_name': '110001'}], 'geometry': {'location': {'lng': 77.2295097, 'lat': 28.612912}, \n'viewport': {'northeast': {'lng': 77.2308586802915, 'lat': 28.6142609802915}, 'southwest': {'lng': \n77.22816071970848, 'lat': 28.6115630197085}}, 'location_type': 'APPROXIMATE'}, 'types': \n['establishment', 'point_of_interest'], 'formatted_address': 'Rajpath, India Gate, New Delhi, Delhi 110001, \nIndia', 'place_id': 'ChIJC03rqdriDDkRXT6SJRGXFwc'}]}" }, { "code": null, "e": 1964, "s": 1857, "text": "As you can see, this output is not properly indented which affects readability for nested data structures." }, { "code": null, "e": 1994, "s": 1964, "text": "Now, consider the code below:" }, { "code": "# A python code with pprintimport requestsfrom pprint import pprint def geocode(address): url = \"https://maps.googleapis.com/maps/api/geocode/json\" resp = requests.get(url, params = {'address': address}) return resp.json() # calling geocode functiondata = geocode('India gate') # pretty-printing json responsepprint(data)", "e": 2325, "s": 1994, "text": null }, { "code": null, "e": 2367, "s": 2325, "text": "The output of above code looks like this:" }, { "code": null, "e": 4721, "s": 2367, "text": "{'results': [{'address_components': [{'long_name': 'Rajpath',\n 'short_name': 'Rajpath',\n 'types': ['route']},\n {'long_name': 'India Gate',\n 'short_name': 'India Gate',\n 'types': ['political',\n 'sublocality',\n 'sublocality_level_1']},\n {'long_name': 'New Delhi',\n 'short_name': 'New Delhi',\n 'types': ['locality', 'political']},\n {'long_name': 'New Delhi',\n 'short_name': 'New Delhi',\n 'types': ['administrative_area_level_2',\n 'political']},\n {'long_name': 'Delhi',\n 'short_name': 'DL',\n 'types': ['administrative_area_level_1',\n 'political']},\n {'long_name': 'India',\n 'short_name': 'IN',\n 'types': ['country', 'political']},\n {'long_name': '110001',\n 'short_name': '110001',\n 'types': ['postal_code']}],\n 'formatted_address': 'Rajpath, India Gate, New Delhi, Delhi '\n '110001, India',\n 'geometry': {'location': {'lat': 28.612912, 'lng': 77.2295097},\n 'location_type': 'APPROXIMATE',\n 'viewport': {'northeast': {'lat': 28.6142609802915,\n 'lng': 77.2308586802915},\n 'southwest': {'lat': 28.6115630197085,\n 'lng': 77.22816071970848}}},\n 'place_id': 'ChIJC03rqdriDDkRXT6SJRGXFwc',\n 'types': ['establishment', 'point_of_interest']}],\n 'status': 'OK'}\n" }, { "code": null, "e": 4794, "s": 4721, "text": "As you can see, the output is now well formatted and much more readable." }, { "code": null, "e": 4915, "s": 4794, "text": "All we did was to import the pprint function of pprint module. And use pprint() function rather than the print function!" }, { "code": null, "e": 5208, "s": 4915, "text": "This blog is contributed by Nikhil 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." }, { "code": null, "e": 5333, "s": 5208, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5352, "s": 5333, "text": "surindertarika1234" }, { "code": null, "e": 5367, "s": 5352, "text": "Python-Library" }, { "code": null, "e": 5382, "s": 5367, "text": "python-utility" }, { "code": null, "e": 5389, "s": 5382, "text": "Python" }, { "code": null, "e": 5408, "s": 5389, "text": "Technical Scripter" }, { "code": null, "e": 5506, "s": 5408, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5524, "s": 5506, "text": "Python Dictionary" }, { "code": null, "e": 5566, "s": 5524, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5588, "s": 5566, "text": "Enumerate() in Python" }, { "code": null, "e": 5614, "s": 5588, "text": "Python String | replace()" }, { "code": null, "e": 5646, "s": 5614, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5675, "s": 5646, "text": "*args and **kwargs in Python" }, { "code": null, "e": 5702, "s": 5675, "text": "Python Classes and Objects" }, { "code": null, "e": 5723, "s": 5702, "text": "Python OOPs Concepts" }, { "code": null, "e": 5746, "s": 5723, "text": "Introduction To PYTHON" } ]
Draw a smiley face using Graphics in C language
19 Apr, 2021 Prerequisite: graphics.h, How to include graphics.h in CodeBlocks? The task is to write a C program to draw a smiley face using graphics in C.To run the program we have the include the below header file: #include <graphic.h> Approach: We will create a Smiley Face with the help below functions: fillellipse(int x, int y, int x_radius, int y_radius): A function from graphics.h header file which draws and fills an ellipse with center at (x, y) and (x_radius, y_radius) as x and y radius of ellipse.ellipse(int x, int y, int stangle, int endangle, int xradius, int yradius): A function from graphics.h header file which is used to draw an ellipse (x, y) are coordinates of the center of the ellipse, stangle is the starting angle, end angle is the ending angle, and fifth and sixth parameters specifies the X and Y radius of the ellipse.setcolor(n): A function from graphics.h header file which set the color of pointer(cursor).setfillstyle(): A function from graphics.h header file which sets the current fill pattern and fill color.floodfill(): A function from graphics.h header file which is used to fill an enclosed area. fillellipse(int x, int y, int x_radius, int y_radius): A function from graphics.h header file which draws and fills an ellipse with center at (x, y) and (x_radius, y_radius) as x and y radius of ellipse. ellipse(int x, int y, int stangle, int endangle, int xradius, int yradius): A function from graphics.h header file which is used to draw an ellipse (x, y) are coordinates of the center of the ellipse, stangle is the starting angle, end angle is the ending angle, and fifth and sixth parameters specifies the X and Y radius of the ellipse. setcolor(n): A function from graphics.h header file which set the color of pointer(cursor). setfillstyle(): A function from graphics.h header file which sets the current fill pattern and fill color. floodfill(): A function from graphics.h header file which is used to fill an enclosed area. Below is the implementation of to draw Smiley Face using graphics in C: C // C program to create a smiley face#include <conio.h>#include <dos.h>#include <graphics.h>#include <stdio.h> // Driver Codeint main(){ // Initialize graphic driver int gr = DETECT, gm; // Initialize graphics mode by passing // three arguments to initgraph function // &gdriver is the address of gdriver // variable, &gmode is the address of // gmode and "C:\\Turboc3\\BGI" is the // directory path where BGI files // are stored initgraph(&gr, &gm, "C:\\Turboc3\\BGI"); // Set color of smiley to yellow setcolor(YELLOW); // creating circle and fill it with // yellow color using floodfill. circle(300, 100, 40); setfillstyle(SOLID_FILL, YELLOW); floodfill(300, 100, YELLOW); // Set color of background to black setcolor(BLACK); setfillstyle(SOLID_FILL, BLACK); // Use fill ellipse for creating eyes fillellipse(310, 85, 2, 6); fillellipse(290, 85, 2, 6); // Use ellipse for creating mouth ellipse(300, 100, 205, 335, 20, 9); ellipse(300, 100, 205, 335, 20, 10); ellipse(300, 100, 205, 335, 20, 11); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system closegraph(); return 0;} Output: Below is the output of the above program: arorakashish0911 c-graphics computer-graphics C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Apr, 2021" }, { "code": null, "e": 234, "s": 28, "text": "Prerequisite: graphics.h, How to include graphics.h in CodeBlocks? The task is to write a C program to draw a smiley face using graphics in C.To run the program we have the include the below header file: " }, { "code": null, "e": 255, "s": 234, "text": "#include <graphic.h>" }, { "code": null, "e": 327, "s": 255, "text": "Approach: We will create a Smiley Face with the help below functions: " }, { "code": null, "e": 1157, "s": 327, "text": "fillellipse(int x, int y, int x_radius, int y_radius): A function from graphics.h header file which draws and fills an ellipse with center at (x, y) and (x_radius, y_radius) as x and y radius of ellipse.ellipse(int x, int y, int stangle, int endangle, int xradius, int yradius): A function from graphics.h header file which is used to draw an ellipse (x, y) are coordinates of the center of the ellipse, stangle is the starting angle, end angle is the ending angle, and fifth and sixth parameters specifies the X and Y radius of the ellipse.setcolor(n): A function from graphics.h header file which set the color of pointer(cursor).setfillstyle(): A function from graphics.h header file which sets the current fill pattern and fill color.floodfill(): A function from graphics.h header file which is used to fill an enclosed area." }, { "code": null, "e": 1361, "s": 1157, "text": "fillellipse(int x, int y, int x_radius, int y_radius): A function from graphics.h header file which draws and fills an ellipse with center at (x, y) and (x_radius, y_radius) as x and y radius of ellipse." }, { "code": null, "e": 1700, "s": 1361, "text": "ellipse(int x, int y, int stangle, int endangle, int xradius, int yradius): A function from graphics.h header file which is used to draw an ellipse (x, y) are coordinates of the center of the ellipse, stangle is the starting angle, end angle is the ending angle, and fifth and sixth parameters specifies the X and Y radius of the ellipse." }, { "code": null, "e": 1792, "s": 1700, "text": "setcolor(n): A function from graphics.h header file which set the color of pointer(cursor)." }, { "code": null, "e": 1899, "s": 1792, "text": "setfillstyle(): A function from graphics.h header file which sets the current fill pattern and fill color." }, { "code": null, "e": 1991, "s": 1899, "text": "floodfill(): A function from graphics.h header file which is used to fill an enclosed area." }, { "code": null, "e": 2064, "s": 1991, "text": "Below is the implementation of to draw Smiley Face using graphics in C: " }, { "code": null, "e": 2066, "s": 2064, "text": "C" }, { "code": "// C program to create a smiley face#include <conio.h>#include <dos.h>#include <graphics.h>#include <stdio.h> // Driver Codeint main(){ // Initialize graphic driver int gr = DETECT, gm; // Initialize graphics mode by passing // three arguments to initgraph function // &gdriver is the address of gdriver // variable, &gmode is the address of // gmode and \"C:\\\\Turboc3\\\\BGI\" is the // directory path where BGI files // are stored initgraph(&gr, &gm, \"C:\\\\Turboc3\\\\BGI\"); // Set color of smiley to yellow setcolor(YELLOW); // creating circle and fill it with // yellow color using floodfill. circle(300, 100, 40); setfillstyle(SOLID_FILL, YELLOW); floodfill(300, 100, YELLOW); // Set color of background to black setcolor(BLACK); setfillstyle(SOLID_FILL, BLACK); // Use fill ellipse for creating eyes fillellipse(310, 85, 2, 6); fillellipse(290, 85, 2, 6); // Use ellipse for creating mouth ellipse(300, 100, 205, 335, 20, 9); ellipse(300, 100, 205, 335, 20, 10); ellipse(300, 100, 205, 335, 20, 11); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system closegraph(); return 0;}", "e": 3326, "s": 2066, "text": null }, { "code": null, "e": 3378, "s": 3326, "text": "Output: Below is the output of the above program: " }, { "code": null, "e": 3397, "s": 3380, "text": "arorakashish0911" }, { "code": null, "e": 3408, "s": 3397, "text": "c-graphics" }, { "code": null, "e": 3426, "s": 3408, "text": "computer-graphics" }, { "code": null, "e": 3437, "s": 3426, "text": "C Language" } ]
Why does PHP 5.2+ disallow abstract static class methods ? - GeeksforGeeks
31 May, 2020 Before we answer this question, you must have a clear definition of what exactly is an abstract class, an abstract method and a static method. Abstract Class: In the Object-Oriented programming paradigm, abstraction refers to the process of hiding the internal implementation details of any program and only showing the functionality of the program to the user. Abstract classes are a way of achieving this. An abstract class is any class that cannot be instantiated (i.e. objects cannot be created) and has to be extended (inherited) for objects to be created. The ‘abstract’ keyword is used to create abstract classes. Abstract Method: An abstract method is a method that can only be declared and not defined. It is defined in the class that inherits from this class. Static Method: A static method of any class is a method that is created only once. This means that even if you create hundreds of objects of a class with static methods, there will be the only copy of each static method. Consider the following example: abstract class Abstract_Parent { static function X() { self::Y(); } abstract static function Y();} class Child extends Abstract_Parent { static function Y() { echo "GeeksforGeeks"; }} Child::X(); Now if you run this PHP code, you will see the error, “PHP Fatal error: Cannot call abstract method Abstract_Parent::X().” When we call method X() in the child class, the static function X() in the parent gets called. In the method X(), we are again calling function Y(), which is an abstract static function. The Y() that function X() is trying to call is the parent class Y(), which is itself an abstract function. So, using abstract and static on the same method defeats each other purpose. This is the reason why PHP 5.2+ does not allow abstract static class methods. PHP-Misc Picked PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to fetch data from localserver database and display on HTML table using PHP ? How to pass form variables from one page to other page in PHP ? Create a drop-down list that options fetched from a MySQL database in PHP How to create admin login page using PHP? Different ways for passing data to view in Laravel How to call PHP function on the click of a Button ? How to fetch data from localserver database and display on HTML table using PHP ? How to pass form variables from one page to other page in PHP ? How to create admin login page using PHP? How to Install php-curl in Ubuntu ?
[ { "code": null, "e": 24581, "s": 24553, "text": "\n31 May, 2020" }, { "code": null, "e": 24724, "s": 24581, "text": "Before we answer this question, you must have a clear definition of what exactly is an abstract class, an abstract method and a static method." }, { "code": null, "e": 25202, "s": 24724, "text": "Abstract Class: In the Object-Oriented programming paradigm, abstraction refers to the process of hiding the internal implementation details of any program and only showing the functionality of the program to the user. Abstract classes are a way of achieving this. An abstract class is any class that cannot be instantiated (i.e. objects cannot be created) and has to be extended (inherited) for objects to be created. The ‘abstract’ keyword is used to create abstract classes." }, { "code": null, "e": 25351, "s": 25202, "text": "Abstract Method: An abstract method is a method that can only be declared and not defined. It is defined in the class that inherits from this class." }, { "code": null, "e": 25572, "s": 25351, "text": "Static Method: A static method of any class is a method that is created only once. This means that even if you create hundreds of objects of a class with static methods, there will be the only copy of each static method." }, { "code": null, "e": 25604, "s": 25572, "text": "Consider the following example:" }, { "code": "abstract class Abstract_Parent { static function X() { self::Y(); } abstract static function Y();} class Child extends Abstract_Parent { static function Y() { echo \"GeeksforGeeks\"; }} Child::X();", "e": 25849, "s": 25604, "text": null }, { "code": null, "e": 25972, "s": 25849, "text": "Now if you run this PHP code, you will see the error, “PHP Fatal error: Cannot call abstract method Abstract_Parent::X().”" }, { "code": null, "e": 26266, "s": 25972, "text": "When we call method X() in the child class, the static function X() in the parent gets called. In the method X(), we are again calling function Y(), which is an abstract static function. The Y() that function X() is trying to call is the parent class Y(), which is itself an abstract function." }, { "code": null, "e": 26421, "s": 26266, "text": "So, using abstract and static on the same method defeats each other purpose. This is the reason why PHP 5.2+ does not allow abstract static class methods." }, { "code": null, "e": 26430, "s": 26421, "text": "PHP-Misc" }, { "code": null, "e": 26437, "s": 26430, "text": "Picked" }, { "code": null, "e": 26441, "s": 26437, "text": "PHP" }, { "code": null, "e": 26454, "s": 26441, "text": "PHP Programs" }, { "code": null, "e": 26471, "s": 26454, "text": "Web Technologies" }, { "code": null, "e": 26498, "s": 26471, "text": "Web technologies Questions" }, { "code": null, "e": 26502, "s": 26498, "text": "PHP" }, { "code": null, "e": 26600, "s": 26502, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26609, "s": 26600, "text": "Comments" }, { "code": null, "e": 26622, "s": 26609, "text": "Old Comments" }, { "code": null, "e": 26704, "s": 26622, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 26768, "s": 26704, "text": "How to pass form variables from one page to other page in PHP ?" }, { "code": null, "e": 26842, "s": 26768, "text": "Create a drop-down list that options fetched from a MySQL database in PHP" }, { "code": null, "e": 26884, "s": 26842, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 26935, "s": 26884, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 26987, "s": 26935, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 27069, "s": 26987, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 27133, "s": 27069, "text": "How to pass form variables from one page to other page in PHP ?" }, { "code": null, "e": 27175, "s": 27133, "text": "How to create admin login page using PHP?" } ]
How to position and align a Matplotlib figure legend?
To position and align a matplotlib figure legend, we can take the following steps− Plot line1 and line2 using plot() method. Place a legend on the figure. Use bbox_to_anchor to set the position and make horizontal alignment of the legend elements. To display the figure, use show() method. from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True line1, = plt.plot([1, 5, 1, 7], linewidth=0.7) line2, = plt.plot([5, 1, 7, 1], linewidth=2.0) plt.legend([line1, line2], ["line1", "line2"], bbox_to_anchor=(0.45, 1.0), ncol=2) plt.show()
[ { "code": null, "e": 1145, "s": 1062, "text": "To position and align a matplotlib figure legend, we can take the following steps−" }, { "code": null, "e": 1187, "s": 1145, "text": "Plot line1 and line2 using plot() method." }, { "code": null, "e": 1310, "s": 1187, "text": "Place a legend on the figure. Use bbox_to_anchor to set the position and make horizontal alignment of the legend elements." }, { "code": null, "e": 1352, "s": 1310, "text": "To display the figure, use show() method." }, { "code": null, "e": 1664, "s": 1352, "text": "from matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nline1, = plt.plot([1, 5, 1, 7], linewidth=0.7)\nline2, = plt.plot([5, 1, 7, 1], linewidth=2.0)\nplt.legend([line1, line2], [\"line1\", \"line2\"], bbox_to_anchor=(0.45, 1.0), ncol=2)\nplt.show()" } ]
C++ Vector Library - assign() Function
The C++ function std::vector::assign() assign new values to the vector elements by replacing old ones. It modifies size of vector if necessary. If memory allocation happens allocation is allocated by internal allocator. Following is the declaration for std::vector::assign() function form std::vector header. template <class InputIterator> void assign(InputIterator first, InputIterator last); template <class InputIterator> wvoid assign (InputIterator first, InputIterator last); first − Input iterator to the initial position in range. first − Input iterator to the initial position in range. last − Input iterator to the final position in range. last − Input iterator to the final position in range. None This member function never throws exception. If value of (first, last) is not valid index then behavior is undefined. Linear i.e. O(n) The following example shows the usage of std::vector::assign() function. #include <iostream> #include <vector> using namespace std; int main(void) { vector<int> v(5, 100); cout << "Initial vector contents" << endl; for (int i = 0; i < v.size(); ++i) cout << v[i] << endl; cout << endl; cout << "Modified vector contents" << endl; v.assign(v.begin(), v.begin() + 2); for (int i = 0; i < v.size(); ++i) cout << v[i] << endl; return 0; } Let us compile and run the above program, this will produce the following result − Initial vector contents 100 100 100 100 100 Modified vector contents 100 100 Print Add Notes Bookmark this page
[ { "code": null, "e": 2747, "s": 2603, "text": "The C++ function std::vector::assign() assign new values to the vector elements by replacing old ones. It modifies size of vector if necessary." }, { "code": null, "e": 2823, "s": 2747, "text": "If memory allocation happens allocation is allocated by internal allocator." }, { "code": null, "e": 2912, "s": 2823, "text": "Following is the declaration for std::vector::assign() function form std::vector header." }, { "code": null, "e": 2998, "s": 2912, "text": "template <class InputIterator>\nvoid assign(InputIterator first, InputIterator last);\n" }, { "code": null, "e": 3086, "s": 2998, "text": "template <class InputIterator>\nwvoid assign (InputIterator first, InputIterator last);\n" }, { "code": null, "e": 3143, "s": 3086, "text": "first − Input iterator to the initial position in range." }, { "code": null, "e": 3200, "s": 3143, "text": "first − Input iterator to the initial position in range." }, { "code": null, "e": 3254, "s": 3200, "text": "last − Input iterator to the final position in range." }, { "code": null, "e": 3308, "s": 3254, "text": "last − Input iterator to the final position in range." }, { "code": null, "e": 3313, "s": 3308, "text": "None" }, { "code": null, "e": 3431, "s": 3313, "text": "This member function never throws exception. If value of (first, last) is not valid index then behavior is undefined." }, { "code": null, "e": 3448, "s": 3431, "text": "Linear i.e. O(n)" }, { "code": null, "e": 3521, "s": 3448, "text": "The following example shows the usage of std::vector::assign() function." }, { "code": null, "e": 3932, "s": 3521, "text": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main(void) {\n vector<int> v(5, 100);\n\n cout << \"Initial vector contents\" << endl;\n for (int i = 0; i < v.size(); ++i)\n cout << v[i] << endl;\n\n cout << endl;\n \n cout << \"Modified vector contents\" << endl;\n \n v.assign(v.begin(), v.begin() + 2);\n for (int i = 0; i < v.size(); ++i)\n cout << v[i] << endl;\n \n return 0;\n}" }, { "code": null, "e": 4015, "s": 3932, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 4093, "s": 4015, "text": "Initial vector contents\n100\n100\n100\n100\n100\nModified vector contents\n100\n100\n" }, { "code": null, "e": 4100, "s": 4093, "text": " Print" }, { "code": null, "e": 4111, "s": 4100, "text": " Add Notes" } ]
Smallest K digit number divisible by all numbers in given array - GeeksforGeeks
17 Dec, 2021 Given an array arr[]. The task is to create the smallest K digit number divisible by all numbers of arr[]. Examples: Input: arr[] = {2, 3, 5}, N = 3Output: 120Explanation: 120 is divisible by 2, 3 and 5 Input: arr[] = {2, 6, 7, 4, 5}, N = 5Output: 10080 Approach: This problem can be solved by using Lowest common multiple. Follow the steps below to solve the given problem. Find the LCM of all the array elements of arr[]. Find a multiple of LCM having K digits. The first number having K digits will be the final answer. Finally, return the answer. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ program for above approach#include <bits/stdc++.h>using namespace std; // Recursive implementationint findLCM(vector<int> arr, int idx){ // lcm(a,b) = (a*b/gcd(a,b)) if (idx == arr.size() - 1) { return arr[idx]; } int a = arr[idx]; int b = findLCM(arr, idx + 1); return (a * b / __gcd(a, b));} // Finding smallest number with given conditionsint findNum(vector<int>& arr, int N){ int lcm = findLCM(arr, 0); int ans = pow(10, N - 1) / lcm; ans = (ans + 1) * lcm; return ans;} // Driver Codeint main(){ // Array arr[] vector<int> arr = { 2, 3, 5 }; int N = 3; // Function call cout << findNum(arr, N); return 0;} // Java program for above approachclass GFG { static int __gcd(int a, int b) { // Everything divides 0 if (b == 0) { return a; } return __gcd(b, a % b); } // Recursive implementation static int findLCM(int[] arr, int idx) { // lcm(a,b) = (a*b/gcd(a,b)) if (idx == arr.length - 1) { return arr[idx]; } int a = arr[idx]; int b = findLCM(arr, idx + 1); return (a * b / __gcd(a, b)); } // Finding smallest number with given conditions static int findNum(int[] arr, int N) { int lcm = findLCM(arr, 0); int ans = (int) Math.pow(10, N - 1) / lcm; ans = (ans + 1) * lcm; return ans; } // Driver Code public static void main(String args[]) { // Array arr[] int[] arr = { 2, 3, 5 }; int N = 3; // Function call System.out.println(findNum(arr, N)); }} // This code is contributed b saurabh_jaiswal. # Python 3 program for above approachimport math# Recursive implementationdef findLCM(arr, idx): # lcm(a,b) = (a*b/gcd(a,b)) if (idx == len(arr) - 1): return arr[idx] a = arr[idx] b = findLCM(arr, idx + 1) return (a * b // math.gcd(a, b)) # Finding smallest number with given conditions def findNum(arr, N): lcm = findLCM(arr, 0) ans = pow(10, N - 1) // lcm ans = (ans + 1) * lcm return ans # Driver Codeif __name__ == "__main__": # Array arr[] arr = [2, 3, 5] N = 3 # Function call print(findNum(arr, N)) # This code is contributed by ukasp. // C# program for above approachusing System;class GFG { static int __gcd(int a, int b) { // Everything divides 0 if (b == 0) { return a; } return __gcd(b, a % b); } // Recursive implementation static int findLCM(int[] arr, int idx) { // lcm(a,b) = (a*b/gcd(a,b)) if (idx == arr.Length - 1) { return arr[idx]; } int a = arr[idx]; int b = findLCM(arr, idx + 1); return (a * b / __gcd(a, b)); } // Finding smallest number with given conditions static int findNum(int[] arr, int N) { int lcm = findLCM(arr, 0); int ans = (int) Math.Pow(10, N - 1) / lcm; ans = (ans + 1) * lcm; return ans; } // Driver Code public static void Main(string []args) { // Array arr[] int[] arr = { 2, 3, 5 }; int N = 3; // Function call Console.WriteLine(findNum(arr, N)); }} // This code is contributed by gaurav01. <script> // JavaScript code for the above approach function __gcd(a, b) { // Everything divides 0 if (b == 0) { return a; } return __gcd(b, a % b); } // Recursive implementation function findLCM(arr, idx) { // lcm(a,b) = (a*b/gcd(a,b)) if (idx == arr.length - 1) { return arr[idx]; } let a = arr[idx]; let b = findLCM(arr, idx + 1); return (a * b / __gcd(a, b)); } // Finding smallest number with given conditions function findNum(arr, N) { let lcm = findLCM(arr, 0); let ans = Math.floor(Math.pow(10, N - 1) / lcm); ans = (ans + 1) * lcm; return ans; } // Driver Code // Array arr[] let arr = [2, 3, 5]; let N = 3; // Function call document.write(findNum(arr, N)); // This code is contributed by Potta Lokesh </script> 120 Time Complexity: O(N) Auxiliary Space: O(1) lokeshpotta20 ukasp _saurabh_jaiswal gaurav01 divisibility GCD-LCM number-digits Greedy Mathematical Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Split the given array into K sub-arrays such that maximum sum of all sub arrays is minimum Program for First Fit algorithm in Memory Management Optimal Page Replacement Algorithm Program for Best Fit algorithm in Memory Management Bin Packing Problem (Minimize number of used Bins) Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Merge two sorted arrays Program to find GCD or HCF of two numbers
[ { "code": null, "e": 24903, "s": 24875, "text": "\n17 Dec, 2021" }, { "code": null, "e": 25010, "s": 24903, "text": "Given an array arr[]. The task is to create the smallest K digit number divisible by all numbers of arr[]." }, { "code": null, "e": 25020, "s": 25010, "text": "Examples:" }, { "code": null, "e": 25106, "s": 25020, "text": "Input: arr[] = {2, 3, 5}, N = 3Output: 120Explanation: 120 is divisible by 2, 3 and 5" }, { "code": null, "e": 25157, "s": 25106, "text": "Input: arr[] = {2, 6, 7, 4, 5}, N = 5Output: 10080" }, { "code": null, "e": 25279, "s": 25157, "text": "Approach: This problem can be solved by using Lowest common multiple. Follow the steps below to solve the given problem. " }, { "code": null, "e": 25328, "s": 25279, "text": "Find the LCM of all the array elements of arr[]." }, { "code": null, "e": 25368, "s": 25328, "text": "Find a multiple of LCM having K digits." }, { "code": null, "e": 25427, "s": 25368, "text": "The first number having K digits will be the final answer." }, { "code": null, "e": 25455, "s": 25427, "text": "Finally, return the answer." }, { "code": null, "e": 25507, "s": 25455, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 25511, "s": 25507, "text": "C++" }, { "code": null, "e": 25516, "s": 25511, "text": "Java" }, { "code": null, "e": 25524, "s": 25516, "text": "Python3" }, { "code": null, "e": 25527, "s": 25524, "text": "C#" }, { "code": null, "e": 25538, "s": 25527, "text": "Javascript" }, { "code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Recursive implementationint findLCM(vector<int> arr, int idx){ // lcm(a,b) = (a*b/gcd(a,b)) if (idx == arr.size() - 1) { return arr[idx]; } int a = arr[idx]; int b = findLCM(arr, idx + 1); return (a * b / __gcd(a, b));} // Finding smallest number with given conditionsint findNum(vector<int>& arr, int N){ int lcm = findLCM(arr, 0); int ans = pow(10, N - 1) / lcm; ans = (ans + 1) * lcm; return ans;} // Driver Codeint main(){ // Array arr[] vector<int> arr = { 2, 3, 5 }; int N = 3; // Function call cout << findNum(arr, N); return 0;}", "e": 26224, "s": 25538, "text": null }, { "code": "// Java program for above approachclass GFG { static int __gcd(int a, int b) { // Everything divides 0 if (b == 0) { return a; } return __gcd(b, a % b); } // Recursive implementation static int findLCM(int[] arr, int idx) { // lcm(a,b) = (a*b/gcd(a,b)) if (idx == arr.length - 1) { return arr[idx]; } int a = arr[idx]; int b = findLCM(arr, idx + 1); return (a * b / __gcd(a, b)); } // Finding smallest number with given conditions static int findNum(int[] arr, int N) { int lcm = findLCM(arr, 0); int ans = (int) Math.pow(10, N - 1) / lcm; ans = (ans + 1) * lcm; return ans; } // Driver Code public static void main(String args[]) { // Array arr[] int[] arr = { 2, 3, 5 }; int N = 3; // Function call System.out.println(findNum(arr, N)); }} // This code is contributed b saurabh_jaiswal.", "e": 27103, "s": 26224, "text": null }, { "code": "# Python 3 program for above approachimport math# Recursive implementationdef findLCM(arr, idx): # lcm(a,b) = (a*b/gcd(a,b)) if (idx == len(arr) - 1): return arr[idx] a = arr[idx] b = findLCM(arr, idx + 1) return (a * b // math.gcd(a, b)) # Finding smallest number with given conditions def findNum(arr, N): lcm = findLCM(arr, 0) ans = pow(10, N - 1) // lcm ans = (ans + 1) * lcm return ans # Driver Codeif __name__ == \"__main__\": # Array arr[] arr = [2, 3, 5] N = 3 # Function call print(findNum(arr, N)) # This code is contributed by ukasp.", "e": 27707, "s": 27103, "text": null }, { "code": "// C# program for above approachusing System;class GFG { static int __gcd(int a, int b) { // Everything divides 0 if (b == 0) { return a; } return __gcd(b, a % b); } // Recursive implementation static int findLCM(int[] arr, int idx) { // lcm(a,b) = (a*b/gcd(a,b)) if (idx == arr.Length - 1) { return arr[idx]; } int a = arr[idx]; int b = findLCM(arr, idx + 1); return (a * b / __gcd(a, b)); } // Finding smallest number with given conditions static int findNum(int[] arr, int N) { int lcm = findLCM(arr, 0); int ans = (int) Math.Pow(10, N - 1) / lcm; ans = (ans + 1) * lcm; return ans; } // Driver Code public static void Main(string []args) { // Array arr[] int[] arr = { 2, 3, 5 }; int N = 3; // Function call Console.WriteLine(findNum(arr, N)); }} // This code is contributed by gaurav01.", "e": 28590, "s": 27707, "text": null }, { "code": "<script> // JavaScript code for the above approach function __gcd(a, b) { // Everything divides 0 if (b == 0) { return a; } return __gcd(b, a % b); } // Recursive implementation function findLCM(arr, idx) { // lcm(a,b) = (a*b/gcd(a,b)) if (idx == arr.length - 1) { return arr[idx]; } let a = arr[idx]; let b = findLCM(arr, idx + 1); return (a * b / __gcd(a, b)); } // Finding smallest number with given conditions function findNum(arr, N) { let lcm = findLCM(arr, 0); let ans = Math.floor(Math.pow(10, N - 1) / lcm); ans = (ans + 1) * lcm; return ans; } // Driver Code // Array arr[] let arr = [2, 3, 5]; let N = 3; // Function call document.write(findNum(arr, N)); // This code is contributed by Potta Lokesh </script>", "e": 29636, "s": 28590, "text": null }, { "code": null, "e": 29643, "s": 29639, "text": "120" }, { "code": null, "e": 29689, "s": 29645, "text": "Time Complexity: O(N) Auxiliary Space: O(1)" }, { "code": null, "e": 29705, "s": 29691, "text": "lokeshpotta20" }, { "code": null, "e": 29711, "s": 29705, "text": "ukasp" }, { "code": null, "e": 29728, "s": 29711, "text": "_saurabh_jaiswal" }, { "code": null, "e": 29737, "s": 29728, "text": "gaurav01" }, { "code": null, "e": 29750, "s": 29737, "text": "divisibility" }, { "code": null, "e": 29758, "s": 29750, "text": "GCD-LCM" }, { "code": null, "e": 29772, "s": 29758, "text": "number-digits" }, { "code": null, "e": 29779, "s": 29772, "text": "Greedy" }, { "code": null, "e": 29792, "s": 29779, "text": "Mathematical" }, { "code": null, "e": 29799, "s": 29792, "text": "Greedy" }, { "code": null, "e": 29812, "s": 29799, "text": "Mathematical" }, { "code": null, "e": 29910, "s": 29812, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29919, "s": 29910, "text": "Comments" }, { "code": null, "e": 29932, "s": 29919, "text": "Old Comments" }, { "code": null, "e": 30023, "s": 29932, "text": "Split the given array into K sub-arrays such that maximum sum of all sub arrays is minimum" }, { "code": null, "e": 30076, "s": 30023, "text": "Program for First Fit algorithm in Memory Management" }, { "code": null, "e": 30111, "s": 30076, "text": "Optimal Page Replacement Algorithm" }, { "code": null, "e": 30163, "s": 30111, "text": "Program for Best Fit algorithm in Memory Management" }, { "code": null, "e": 30214, "s": 30163, "text": "Bin Packing Problem (Minimize number of used Bins)" }, { "code": null, "e": 30244, "s": 30214, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 30259, "s": 30244, "text": "C++ Data Types" }, { "code": null, "e": 30302, "s": 30259, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 30326, "s": 30302, "text": "Merge two sorted arrays" } ]
Chain of Responsibility - Python Design Patterns - GeeksforGeeks
04 Jan, 2022 Chain of Responsibility method is Behavioral design pattern and it is the object-oriented version of if ... elif ... elif ... else and make us capable to rearrange the condition-action blocks dynamically at the run-time. It allows us to pass the requests along the chain of handlers. The processing is simple, whenever any handler received the request it has two choices either to process it or pass it to the next handler in the chain. This pattern aims to decouple the senders of a request from its receivers by allowing the request to move through chained receivers until it is handled. chain-of-responsibility-method Imagine you are building a simple website that takes input strings and tells about the various properties of the strings such as is the string palindrome? is string upperCase? is string lowerCase? and many other properties too. After the complete planning, you decide that these checks for the input string should be performed sequentially. So, here the problem arises for the developer that he/she has to implement such an application that can decide on run-time which action should be performed next. Chain of Responsibility Method provides the solution for the above-described problem. It creates a separate Abstract handler which is used to handle the sequential operations which should be performed dynamically. For eg., we create four handlers named as FirstConcreteHandler, SecondConcreteHandler, ThirdConcreteHandler, and Defaulthandler and calls them sequentially from the user class. Python3 class AbstractHandler(object): """Parent class of all concrete handlers""" def __init__(self, nxt): """change or increase the local variable using nxt""" self._nxt = nxt def handle(self, request): """It calls the processRequest through given request""" handled = self.processRequest(request) """case when it is not handled""" if not handled: self._nxt.handle(request) def processRequest(self, request): """throws a NotImplementedError""" raise NotImplementedError('First implement it !') class FirstConcreteHandler(AbstractHandler): """Concrete Handler # 1: Child class of AbstractHandler""" def processRequest(self, request): '''return True if request is handled ''' if 'a' < request <= 'e': print("This is {} handling request '{}'".format(self.__class__.__name__, request)) return True class SecondConcreteHandler(AbstractHandler): """Concrete Handler # 2: Child class of AbstractHandler""" def processRequest(self, request): '''return True if the request is handled''' if 'e' < request <= 'l': print("This is {} handling request '{}'".format(self.__class__.__name__, request)) return True class ThirdConcreteHandler(AbstractHandler): """Concrete Handler # 3: Child class of AbstractHandler""" def processRequest(self, request): '''return True if the request is handled''' if 'l' < request <= 'z': print("This is {} handling request '{}'".format(self.__class__.__name__, request)) return True class DefaultHandler(AbstractHandler): """Default Handler: child class from AbstractHandler""" def processRequest(self, request): """Gives the message that th request is not handled and returns true""" print("This is {} telling you that request '{}' has no handler right now.".format(self.__class__.__name__, request)) return True class User: """User Class""" def __init__(self): """Provides the sequence of handles for the users""" initial = None self.handler = FirstConcreteHandler(SecondConcreteHandler(ThirdConcreteHandler(DefaultHandler(initial)))) def agent(self, user_request): """Iterates over each request and sends them to specific handles""" for request in user_request: self.handler.handle(request) """main method""" if __name__ == "__main__": """Create a client object""" user = User() """Create requests to be processed""" string = "GeeksforGeeks" requests = list(string) """Send the requests one by one, to handlers as per the sequence of handlers defined in the Client class""" user.agent(requests) This is DefaultHandler telling you that request 'G' has no handler right now. This is FirstConcreteHandler handling request 'e' This is FirstConcreteHandler handling request 'e' This is SecondConcreteHandler handling request 'k' This is ThirdConcreteHandler handling request 's' This is SecondConcreteHandler handling request 'f' This is ThirdConcreteHandler handling request 'o' This is ThirdConcreteHandler handling request 'r' This is DefaultHandler telling you that request 'G' has no handler right now. This is FirstConcreteHandler handling request 'e' This is FirstConcreteHandler handling request 'e' This is SecondConcreteHandler handling request 'k' This is ThirdConcreteHandler handling request 's' Class Diagram for Chain of Responsibility Method Chain-Of-Responsibility_class_diagram Single Responsibility Principle: It’s easy to decouple the classes here that invoke operations from classes that perform operations. Open/Closed principle: We can introduce the new code classes without breaking th existing client code. Increases Flexibility: While giving the responsibilities to the objects, it increases the flexibility of the code. Unassured about request: This method doesn’t provide any assurance whether the object will be received or not. Spotting characteristics: Due to debugging, it becomes difficult task to observe the characteristics of operations. Depreciated System Performance: It might affect the system’s performance due to continuous cycle calls Processing several handlers in order: Chain of responsibility method helps very much when it is required to process several handlers in a particular order because the linking is possible in any order Decoupling requests: This method is generally used when you want to decouple the request’s sender and receiver. Unspecified handlers: When you don’t want to specify handlers in the code, it is always preferred to use the Chain of Responsibility. Further Read – Chain of Responsibility in Java Akanksha_Rai sweetyty simmytarika5 varshagumber28 sumitgumber28 python-design-pattern Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n04 Jan, 2022" }, { "code": null, "e": 24493, "s": 23901, "text": "Chain of Responsibility method is Behavioral design pattern and it is the object-oriented version of if ... elif ... elif ... else and make us capable to rearrange the condition-action blocks dynamically at the run-time. It allows us to pass the requests along the chain of handlers. The processing is simple, whenever any handler received the request it has two choices either to process it or pass it to the next handler in the chain. This pattern aims to decouple the senders of a request from its receivers by allowing the request to move through chained receivers until it is handled. " }, { "code": null, "e": 24524, "s": 24493, "text": "chain-of-responsibility-method" }, { "code": null, "e": 25030, "s": 24526, "text": "Imagine you are building a simple website that takes input strings and tells about the various properties of the strings such as is the string palindrome? is string upperCase? is string lowerCase? and many other properties too. After the complete planning, you decide that these checks for the input string should be performed sequentially. So, here the problem arises for the developer that he/she has to implement such an application that can decide on run-time which action should be performed next. " }, { "code": null, "e": 25422, "s": 25030, "text": "Chain of Responsibility Method provides the solution for the above-described problem. It creates a separate Abstract handler which is used to handle the sequential operations which should be performed dynamically. For eg., we create four handlers named as FirstConcreteHandler, SecondConcreteHandler, ThirdConcreteHandler, and Defaulthandler and calls them sequentially from the user class. " }, { "code": null, "e": 25430, "s": 25422, "text": "Python3" }, { "code": "class AbstractHandler(object): \"\"\"Parent class of all concrete handlers\"\"\" def __init__(self, nxt): \"\"\"change or increase the local variable using nxt\"\"\" self._nxt = nxt def handle(self, request): \"\"\"It calls the processRequest through given request\"\"\" handled = self.processRequest(request) \"\"\"case when it is not handled\"\"\" if not handled: self._nxt.handle(request) def processRequest(self, request): \"\"\"throws a NotImplementedError\"\"\" raise NotImplementedError('First implement it !') class FirstConcreteHandler(AbstractHandler): \"\"\"Concrete Handler # 1: Child class of AbstractHandler\"\"\" def processRequest(self, request): '''return True if request is handled ''' if 'a' < request <= 'e': print(\"This is {} handling request '{}'\".format(self.__class__.__name__, request)) return True class SecondConcreteHandler(AbstractHandler): \"\"\"Concrete Handler # 2: Child class of AbstractHandler\"\"\" def processRequest(self, request): '''return True if the request is handled''' if 'e' < request <= 'l': print(\"This is {} handling request '{}'\".format(self.__class__.__name__, request)) return True class ThirdConcreteHandler(AbstractHandler): \"\"\"Concrete Handler # 3: Child class of AbstractHandler\"\"\" def processRequest(self, request): '''return True if the request is handled''' if 'l' < request <= 'z': print(\"This is {} handling request '{}'\".format(self.__class__.__name__, request)) return True class DefaultHandler(AbstractHandler): \"\"\"Default Handler: child class from AbstractHandler\"\"\" def processRequest(self, request): \"\"\"Gives the message that th request is not handled and returns true\"\"\" print(\"This is {} telling you that request '{}' has no handler right now.\".format(self.__class__.__name__, request)) return True class User: \"\"\"User Class\"\"\" def __init__(self): \"\"\"Provides the sequence of handles for the users\"\"\" initial = None self.handler = FirstConcreteHandler(SecondConcreteHandler(ThirdConcreteHandler(DefaultHandler(initial)))) def agent(self, user_request): \"\"\"Iterates over each request and sends them to specific handles\"\"\" for request in user_request: self.handler.handle(request) \"\"\"main method\"\"\" if __name__ == \"__main__\": \"\"\"Create a client object\"\"\" user = User() \"\"\"Create requests to be processed\"\"\" string = \"GeeksforGeeks\" requests = list(string) \"\"\"Send the requests one by one, to handlers as per the sequence of handlers defined in the Client class\"\"\" user.agent(requests)", "e": 28280, "s": 25430, "text": null }, { "code": null, "e": 28989, "s": 28280, "text": "This is DefaultHandler telling you that request 'G' has no handler right now.\nThis is FirstConcreteHandler handling request 'e'\nThis is FirstConcreteHandler handling request 'e'\nThis is SecondConcreteHandler handling request 'k'\nThis is ThirdConcreteHandler handling request 's'\nThis is SecondConcreteHandler handling request 'f'\nThis is ThirdConcreteHandler handling request 'o'\nThis is ThirdConcreteHandler handling request 'r'\nThis is DefaultHandler telling you that request 'G' has no handler right now.\nThis is FirstConcreteHandler handling request 'e'\nThis is FirstConcreteHandler handling request 'e'\nThis is SecondConcreteHandler handling request 'k'\nThis is ThirdConcreteHandler handling request 's'" }, { "code": null, "e": 29039, "s": 28989, "text": "Class Diagram for Chain of Responsibility Method " }, { "code": null, "e": 29077, "s": 29039, "text": "Chain-Of-Responsibility_class_diagram" }, { "code": null, "e": 29214, "s": 29081, "text": "Single Responsibility Principle: It’s easy to decouple the classes here that invoke operations from classes that perform operations." }, { "code": null, "e": 29317, "s": 29214, "text": "Open/Closed principle: We can introduce the new code classes without breaking th existing client code." }, { "code": null, "e": 29432, "s": 29317, "text": "Increases Flexibility: While giving the responsibilities to the objects, it increases the flexibility of the code." }, { "code": null, "e": 29547, "s": 29436, "text": "Unassured about request: This method doesn’t provide any assurance whether the object will be received or not." }, { "code": null, "e": 29663, "s": 29547, "text": "Spotting characteristics: Due to debugging, it becomes difficult task to observe the characteristics of operations." }, { "code": null, "e": 29766, "s": 29663, "text": "Depreciated System Performance: It might affect the system’s performance due to continuous cycle calls" }, { "code": null, "e": 29970, "s": 29770, "text": "Processing several handlers in order: Chain of responsibility method helps very much when it is required to process several handlers in a particular order because the linking is possible in any order" }, { "code": null, "e": 30082, "s": 29970, "text": "Decoupling requests: This method is generally used when you want to decouple the request’s sender and receiver." }, { "code": null, "e": 30216, "s": 30082, "text": "Unspecified handlers: When you don’t want to specify handlers in the code, it is always preferred to use the Chain of Responsibility." }, { "code": null, "e": 30264, "s": 30216, "text": "Further Read – Chain of Responsibility in Java " }, { "code": null, "e": 30277, "s": 30264, "text": "Akanksha_Rai" }, { "code": null, "e": 30286, "s": 30277, "text": "sweetyty" }, { "code": null, "e": 30299, "s": 30286, "text": "simmytarika5" }, { "code": null, "e": 30314, "s": 30299, "text": "varshagumber28" }, { "code": null, "e": 30328, "s": 30314, "text": "sumitgumber28" }, { "code": null, "e": 30350, "s": 30328, "text": "python-design-pattern" }, { "code": null, "e": 30357, "s": 30350, "text": "Python" }, { "code": null, "e": 30455, "s": 30357, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30464, "s": 30455, "text": "Comments" }, { "code": null, "e": 30477, "s": 30464, "text": "Old Comments" }, { "code": null, "e": 30509, "s": 30477, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30565, "s": 30509, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30607, "s": 30565, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30649, "s": 30607, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30685, "s": 30649, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 30707, "s": 30685, "text": "Defaultdict in Python" }, { "code": null, "e": 30746, "s": 30707, "text": "Python | Get unique values from a list" }, { "code": null, "e": 30773, "s": 30746, "text": "Python Classes and Objects" }, { "code": null, "e": 30804, "s": 30773, "text": "Python | os.path.join() method" } ]
Postfix to Infix in C++
In this problem, we are given expression in postfix form and our task is to print the infix form of the expression. Infix expression is an expression in which the operator is in the middle of operands, like operand operator operand. Postfix expression is an expression in which the operator is after operands, like operand operator. Postfix expressions are easily computed by the system but are not human readable. So this conversion is required. Generally reading and editing by the end-user is done on infix notations as they are parenthesis separated hence easily understandable for humans. Let’s take an example to understand the problem Input − xyz/* Output − (x * (y/z)) To solve this problem, we will use the stack data structure. And traverse the postfix expression one by one and then check for the following case − Case 1 − if the operand is found, push it in the stack. Case 2 − if an operator is found, pop to operands, create an infix expression of the three and push the expression as an operand. In the end when the stack has only one element left and the traversing is done, pop the top of stack, it is the infix conversion. Program to show the implementation of our solution. Live Demo #include <bits/stdc++.h> using namespace std; bool isOperand(char x) { return (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z'); } string infixConversion(string postfix) { stack<string> infix; for (int i=0; postfix[i]!='\0'; i++) { if (isOperand(postfix[i])) { string op(1, postfix[i]); infix.push(op); } else { string op1 = infix.top(); infix.pop(); string op2 = infix.top(); infix.pop(); infix.push("{"+op2+postfix[i]+op1 +"}"); } } return infix.top(); } int main() { string postfix = "xyae+/%"; cout<<"The infix conversion of the postfix expression '"<<postfix<<"' is : "; cout<<infixConversion(postfix); return 0; } The infix conversion of the postfix expression 'xyae+/%' is : {x%{y/{a+e}}}
[ { "code": null, "e": 1178, "s": 1062, "text": "In this problem, we are given expression in postfix form and our task is to print the infix form of the expression." }, { "code": null, "e": 1295, "s": 1178, "text": "Infix expression is an expression in which the operator is in the middle of operands, like operand operator operand." }, { "code": null, "e": 1395, "s": 1295, "text": "Postfix expression is an expression in which the operator is after operands, like operand operator." }, { "code": null, "e": 1656, "s": 1395, "text": "Postfix expressions are easily computed by the system but are not human readable. So this conversion is required. Generally reading and editing by the end-user is done on infix notations as they are parenthesis separated hence easily understandable for humans." }, { "code": null, "e": 1704, "s": 1656, "text": "Let’s take an example to understand the problem" }, { "code": null, "e": 1718, "s": 1704, "text": "Input − xyz/*" }, { "code": null, "e": 1739, "s": 1718, "text": "Output − (x * (y/z))" }, { "code": null, "e": 1887, "s": 1739, "text": "To solve this problem, we will use the stack data structure. And traverse the postfix expression one by one and then check for the following case −" }, { "code": null, "e": 1943, "s": 1887, "text": "Case 1 − if the operand is found, push it in the stack." }, { "code": null, "e": 2073, "s": 1943, "text": "Case 2 − if an operator is found, pop to operands, create an infix expression of the three and push the expression as an operand." }, { "code": null, "e": 2203, "s": 2073, "text": "In the end when the stack has only one element left and the traversing is done, pop the top of stack, it is the infix conversion." }, { "code": null, "e": 2255, "s": 2203, "text": "Program to show the implementation of our solution." }, { "code": null, "e": 2266, "s": 2255, "text": " Live Demo" }, { "code": null, "e": 2993, "s": 2266, "text": "#include <bits/stdc++.h>\nusing namespace std;\nbool isOperand(char x) {\n return (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z');\n}\nstring infixConversion(string postfix) {\n stack<string> infix;\n for (int i=0; postfix[i]!='\\0'; i++) {\n if (isOperand(postfix[i])) {\n string op(1, postfix[i]);\n infix.push(op);\n } else {\n string op1 = infix.top();\n infix.pop();\n string op2 = infix.top();\n infix.pop();\n infix.push(\"{\"+op2+postfix[i]+op1 +\"}\");\n }\n }\n return infix.top();\n}\nint main() {\n string postfix = \"xyae+/%\";\n cout<<\"The infix conversion of the postfix expression '\"<<postfix<<\"' is : \";\n cout<<infixConversion(postfix);\n return 0;\n}" }, { "code": null, "e": 3069, "s": 2993, "text": "The infix conversion of the postfix expression 'xyae+/%' is : {x%{y/{a+e}}}" } ]
Branch prediction macros in GCC - GeeksforGeeks
28 May, 2017 One of the most used optimization techniques in the Linux kernel is ” __builtin_expect”. When working with conditional code (if-else statements), we often know which branch is true and which is not. If compiler knows this information in advance, it can generate most optimized code. Let us see macro definition of “likely()” and “unlikely()” macros from linux kernel code “http://lxr.linux.no/linux+v3.6.5/include/linux/compiler.h” [line no 146 and 147]. #define likely(x) __builtin_expect(!!(x), 1)#define unlikely(x) __builtin_expect(!!(x), 0) In the following example, we are marking branch as likely true: const char *home_dir ; home_dir = getenv("HOME");if (likely(home_dir)) printf("home directory: %s\n", home_dir);else perror("getenv"); For above example, we have marked “if” condition as “likely()” true, so compiler will put true code immediately after branch, and false code within the branch instruction. In this way compiler can achieve optimization. But don’t use “likely()” and “unlikely()” macros blindly. If prediction is correct, it means there is zero cycle of jump instruction, but if prediction is wrong, then it will take several cycles, because processor needs to flush it’s pipeline which is worst than no prediction. Accessing memory is the slowest CPU operation as compared to other CPU operations. To avoid this limitation, CPU uses “CPU caches” e.g L1-cache, L2-cache etc. The idea behind cache is, copy some part of memory into CPU itself. We can access cache memory much faster than any other memory. But the problem is, limited size of “cache memory”, we can’t copy entire memory into cache. So, the CPU has to guess which memory is going to be used in the near future and load that memory into the CPU cache and above macros are hint to load memory into the CPU cache. This article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. AdvanceC C-Macro & Preprocessor c-puzzle GCC C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Function Pointer in C Substring in C++ fork() in C std::string class in C++ Enumeration (or enum) in C Command line arguments in C/C++ TCP Server-Client implementation in C Different methods to reverse a string in C/C++ Structures in C Exception Handling in C++
[ { "code": null, "e": 25665, "s": 25637, "text": "\n28 May, 2017" }, { "code": null, "e": 25948, "s": 25665, "text": "One of the most used optimization techniques in the Linux kernel is ” __builtin_expect”. When working with conditional code (if-else statements), we often know which branch is true and which is not. If compiler knows this information in advance, it can generate most optimized code." }, { "code": null, "e": 26120, "s": 25948, "text": "Let us see macro definition of “likely()” and “unlikely()” macros from linux kernel code “http://lxr.linux.no/linux+v3.6.5/include/linux/compiler.h” [line no 146 and 147]." }, { "code": "#define likely(x) __builtin_expect(!!(x), 1)#define unlikely(x) __builtin_expect(!!(x), 0)", "e": 26219, "s": 26120, "text": null }, { "code": null, "e": 26283, "s": 26219, "text": "In the following example, we are marking branch as likely true:" }, { "code": "const char *home_dir ; home_dir = getenv(\"HOME\");if (likely(home_dir)) printf(\"home directory: %s\\n\", home_dir);else perror(\"getenv\");", "e": 26426, "s": 26283, "text": null }, { "code": null, "e": 26923, "s": 26426, "text": "For above example, we have marked “if” condition as “likely()” true, so compiler will put true code immediately after branch, and false code within the branch instruction. In this way compiler can achieve optimization. But don’t use “likely()” and “unlikely()” macros blindly. If prediction is correct, it means there is zero cycle of jump instruction, but if prediction is wrong, then it will take several cycles, because processor needs to flush it’s pipeline which is worst than no prediction." }, { "code": null, "e": 27482, "s": 26923, "text": "Accessing memory is the slowest CPU operation as compared to other CPU operations. To avoid this limitation, CPU uses “CPU caches” e.g L1-cache, L2-cache etc. The idea behind cache is, copy some part of memory into CPU itself. We can access cache memory much faster than any other memory. But the problem is, limited size of “cache memory”, we can’t copy entire memory into cache. So, the CPU has to guess which memory is going to be used in the near future and load that memory into the CPU cache and above macros are hint to load memory into the CPU cache." }, { "code": null, "e": 27656, "s": 27482, "text": "This article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27665, "s": 27656, "text": "AdvanceC" }, { "code": null, "e": 27688, "s": 27665, "text": "C-Macro & Preprocessor" }, { "code": null, "e": 27697, "s": 27688, "text": "c-puzzle" }, { "code": null, "e": 27701, "s": 27697, "text": "GCC" }, { "code": null, "e": 27712, "s": 27701, "text": "C Language" }, { "code": null, "e": 27810, "s": 27712, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27832, "s": 27810, "text": "Function Pointer in C" }, { "code": null, "e": 27849, "s": 27832, "text": "Substring in C++" }, { "code": null, "e": 27861, "s": 27849, "text": "fork() in C" }, { "code": null, "e": 27886, "s": 27861, "text": "std::string class in C++" }, { "code": null, "e": 27913, "s": 27886, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 27945, "s": 27913, "text": "Command line arguments in C/C++" }, { "code": null, "e": 27983, "s": 27945, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 28030, "s": 27983, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 28046, "s": 28030, "text": "Structures in C" } ]
Python | Pandas Series.str.endswith() - GeeksforGeeks
17 Sep, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas endswith() is yet another method to search and filter text data in a Series or a Data Frame. This method is Similar to Python’s endswith() method, but has different parameters and it works on Pandas objects only. Hence .str has to be prefixed every time before calling this method, so that the compiler knows that it’s different from default function. Syntax: Series.str.endswith(pat, na=nan) Parameters:pat: String to be searched. Regex are not acceptedna: Used to set what should be displayed if the value in series is NULL. Return type: Boolean series which is True where the value has the passed string in the end. To download the CSV used in code, click here. In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below. Example #1: Returning Bool seriesIn this example, the college column is checked if elements have “e” in the end of string using the str.endswith() function. A Boolean series is returned which is true at the index position where string has “e” in the end. str.lower() method is called before endswith() since the data can be in any case. # importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # String to be searched in end of string search ="e" # boolean series returned with False at place of NaNbool_series = data["College"].str.lower().str.endswith(search) # displaying boolean seriesbool_series Output:As shown in the output image, The bool series is having True at the index position where the College column was having “e” in the end. It can also be compared by looking at the image of original data frame. Example #2: Handling NULL values The most important part in data analysis is handling Null values. As it can be seen in the above output image, the Boolean series is having NaN wherever the value in College column was empty or NaN. If this boolean series is passed into data frame, it will give an error. Hence, the NaN values need to be handled using na Parameter. It can be set to string too, but since bool series is used to pass and return respective value, it should be set to a Bool value only.In this example, na Parameter is set to False. So wherever the College column is having Null value, the Bool series will store False instead of NaN. After that, the series is passed again to data frame to display only True values. # importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # String to be searched in end of string search ="e" # boolean series returned with False at place of NaNbool_series = data["College"].str.lower().str.endswith(search, na = False) # displaying filtered dataframedata[bool_series] Output:As shown in the output image, the data frame is having rows which have “e” in the end of the string in College column. NaN values are not displayed since the na parameter was set to False. 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. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n17 Sep, 2018" }, { "code": null, "e": 25751, "s": 25537, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 26110, "s": 25751, "text": "Pandas endswith() is yet another method to search and filter text data in a Series or a Data Frame. This method is Similar to Python’s endswith() method, but has different parameters and it works on Pandas objects only. Hence .str has to be prefixed every time before calling this method, so that the compiler knows that it’s different from default function." }, { "code": null, "e": 26151, "s": 26110, "text": "Syntax: Series.str.endswith(pat, na=nan)" }, { "code": null, "e": 26285, "s": 26151, "text": "Parameters:pat: String to be searched. Regex are not acceptedna: Used to set what should be displayed if the value in series is NULL." }, { "code": null, "e": 26377, "s": 26285, "text": "Return type: Boolean series which is True where the value has the passed string in the end." }, { "code": null, "e": 26423, "s": 26377, "text": "To download the CSV used in code, click here." }, { "code": null, "e": 26570, "s": 26423, "text": "In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below." }, { "code": null, "e": 26907, "s": 26570, "text": "Example #1: Returning Bool seriesIn this example, the college column is checked if elements have “e” in the end of string using the str.endswith() function. A Boolean series is returned which is true at the index position where string has “e” in the end. str.lower() method is called before endswith() since the data can be in any case." }, { "code": "# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # String to be searched in end of string search =\"e\" # boolean series returned with False at place of NaNbool_series = data[\"College\"].str.lower().str.endswith(search) # displaying boolean seriesbool_series", "e": 27273, "s": 26907, "text": null }, { "code": null, "e": 27487, "s": 27273, "text": "Output:As shown in the output image, The bool series is having True at the index position where the College column was having “e” in the end. It can also be compared by looking at the image of original data frame." }, { "code": null, "e": 27521, "s": 27487, "text": " Example #2: Handling NULL values" }, { "code": null, "e": 28219, "s": 27521, "text": "The most important part in data analysis is handling Null values. As it can be seen in the above output image, the Boolean series is having NaN wherever the value in College column was empty or NaN. If this boolean series is passed into data frame, it will give an error. Hence, the NaN values need to be handled using na Parameter. It can be set to string too, but since bool series is used to pass and return respective value, it should be set to a Bool value only.In this example, na Parameter is set to False. So wherever the College column is having Null value, the Bool series will store False instead of NaN. After that, the series is passed again to data frame to display only True values." }, { "code": "# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # String to be searched in end of string search =\"e\" # boolean series returned with False at place of NaNbool_series = data[\"College\"].str.lower().str.endswith(search, na = False) # displaying filtered dataframedata[bool_series]", "e": 28607, "s": 28219, "text": null }, { "code": null, "e": 28803, "s": 28607, "text": "Output:As shown in the output image, the data frame is having rows which have “e” in the end of the string in College column. NaN values are not displayed since the na parameter was set to False." }, { "code": null, "e": 28824, "s": 28803, "text": "Python pandas-series" }, { "code": null, "e": 28853, "s": 28824, "text": "Python pandas-series-methods" }, { "code": null, "e": 28867, "s": 28853, "text": "Python-pandas" }, { "code": null, "e": 28874, "s": 28867, "text": "Python" }, { "code": null, "e": 28972, "s": 28874, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29004, "s": 28972, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29046, "s": 29004, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29088, "s": 29046, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29115, "s": 29088, "text": "Python Classes and Objects" }, { "code": null, "e": 29171, "s": 29115, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29193, "s": 29171, "text": "Defaultdict in Python" }, { "code": null, "e": 29232, "s": 29193, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29263, "s": 29232, "text": "Python | os.path.join() method" }, { "code": null, "e": 29292, "s": 29263, "text": "Create a directory in Python" } ]
GATE | GATE-CS-2015 (Set 2) | Question 21 - GeeksforGeeks
01 Nov, 2021 Consider the following C function. int fun (int n){ int x=1, k; if (n==1) return x; for (k=1; k < n; ++k) x = x + fun(k) * fun(n – k); return x;} The return value of fun(5) is __________. (A) 0(B) 26(C) 51(D) 71Answer: (C)Explanation: fun(5) = 1 + fun(1) * fun(4) + fun(2) * fun(3) + fun(3) * fun(2) + fun(4) * fun(1) = 1 + 2*[fun(1)*fun(4) + fun(2)*fun(3)] Substituting fun(1) = 1 = 1 + 2*[fun(4) + fun(2)*fun(3)] Calculating fun(2), fun(3) and fun(4) fun(2) = 1 + fun(1)*fun(1) = 1 + 1*1 = 2 fun(3) = 1 + 2*fun(1)*fun(2) = 1 + 2*1*2 = 5 fun(4) = 1 + 2*fun(1)*fun(3) + fun(2)*fun(2) = 1 + 2*1*5 + 2*2 = 15 Substituting values of fun(2), fun(3) and fun(4) fun(5) = 1 + 2*[15 + 2*5] = 51 Quiz of this Question GATE-CS-2015 (Set 2) GATE-GATE-CS-2015 (Set 2) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2006 | Question 47 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25717, "s": 25689, "text": "\n01 Nov, 2021" }, { "code": null, "e": 25752, "s": 25717, "text": "Consider the following C function." }, { "code": "int fun (int n){ int x=1, k; if (n==1) return x; for (k=1; k < n; ++k) x = x + fun(k) * fun(n – k); return x;}", "e": 25871, "s": 25752, "text": null }, { "code": null, "e": 25913, "s": 25871, "text": "The return value of fun(5) is __________." }, { "code": null, "e": 25960, "s": 25913, "text": "(A) 0(B) 26(C) 51(D) 71Answer: (C)Explanation:" }, { "code": null, "e": 26451, "s": 25960, "text": "fun(5) = 1 + fun(1) * fun(4) + fun(2) * fun(3) + \n fun(3) * fun(2) + fun(4) * fun(1)\n = 1 + 2*[fun(1)*fun(4) + fun(2)*fun(3)]\n\nSubstituting fun(1) = 1\n = 1 + 2*[fun(4) + fun(2)*fun(3)]\n\nCalculating fun(2), fun(3) and fun(4)\nfun(2) = 1 + fun(1)*fun(1) = 1 + 1*1 = 2\nfun(3) = 1 + 2*fun(1)*fun(2) = 1 + 2*1*2 = 5\nfun(4) = 1 + 2*fun(1)*fun(3) + fun(2)*fun(2)\n = 1 + 2*1*5 + 2*2 = 15\n\nSubstituting values of fun(2), fun(3) and fun(4)\nfun(5) = 1 + 2*[15 + 2*5] = 51 " }, { "code": null, "e": 26473, "s": 26451, "text": "Quiz of this Question" }, { "code": null, "e": 26494, "s": 26473, "text": "GATE-CS-2015 (Set 2)" }, { "code": null, "e": 26520, "s": 26494, "text": "GATE-GATE-CS-2015 (Set 2)" }, { "code": null, "e": 26525, "s": 26520, "text": "GATE" }, { "code": null, "e": 26623, "s": 26525, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26657, "s": 26623, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26691, "s": 26657, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26725, "s": 26691, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 26758, "s": 26725, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26794, "s": 26758, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 26830, "s": 26794, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 26864, "s": 26830, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 26898, "s": 26864, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 26932, "s": 26898, "text": "GATE | GATE-CS-2009 | Question 38" } ]
PHP | urldecode() Function - GeeksforGeeks
23 May, 2019 The urldecode() function is an inbuilt function in PHP which is used to decode url which is encoded by encoded() function.Syntax: string urldecode( $input ) Parameters: This function accepts single parameter $input which holds the url to be decoded. Return Value: This function returns the decoded string on success. Below programs illustrate the urldecode() function in PHP:Program 1: <?php // PHP program to illustrate urldecode function // all sub domain of geeksforgeeksecho urldecode("https%3A%2F%2Fide.geeksforgeeks.org%2F"). "\n";echo urldecode("https%3A%2F%2Fpractice.geeksforgeeks.org%2F"). "\n";echo urldecode("https%3A%2F%2Fgeeksforgeeks.org%2F"). "\n";?> https://ide.geeksforgeeks.org/ https://practice.geeksforgeeks.org/ https://geeksforgeeks.org/ Program 2 : <?php // all sub domain of geeksforgeeks$url1 = "https%3A%2F%2Fide.geeksforgeeks.org%2F";$url2 = "https%3A%2F%2Fpractice.geeksforgeeks.org%2F";$url3 = "https%3A%2F%2Fgeeksforgeeks.org%2F"; // create an array $query = array($url1, $url2, $url3); // print decoded urlforeach ($query as $chunk) { printf(urldecode($chunk). "\n"); }?> https://ide.geeksforgeeks.org/ https://practice.geeksforgeeks.org/ https://geeksforgeeks.org/ Reference: http://php.net/manual/en/function.urldecode.php nidhi_biet PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime 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": 26087, "s": 26059, "text": "\n23 May, 2019" }, { "code": null, "e": 26217, "s": 26087, "text": "The urldecode() function is an inbuilt function in PHP which is used to decode url which is encoded by encoded() function.Syntax:" }, { "code": null, "e": 26244, "s": 26217, "text": "string urldecode( $input )" }, { "code": null, "e": 26337, "s": 26244, "text": "Parameters: This function accepts single parameter $input which holds the url to be decoded." }, { "code": null, "e": 26404, "s": 26337, "text": "Return Value: This function returns the decoded string on success." }, { "code": null, "e": 26473, "s": 26404, "text": "Below programs illustrate the urldecode() function in PHP:Program 1:" }, { "code": "<?php // PHP program to illustrate urldecode function // all sub domain of geeksforgeeksecho urldecode(\"https%3A%2F%2Fide.geeksforgeeks.org%2F\"). \"\\n\";echo urldecode(\"https%3A%2F%2Fpractice.geeksforgeeks.org%2F\"). \"\\n\";echo urldecode(\"https%3A%2F%2Fgeeksforgeeks.org%2F\"). \"\\n\";?>", "e": 26757, "s": 26473, "text": null }, { "code": null, "e": 26852, "s": 26757, "text": "https://ide.geeksforgeeks.org/\nhttps://practice.geeksforgeeks.org/\nhttps://geeksforgeeks.org/\n" }, { "code": null, "e": 26864, "s": 26852, "text": "Program 2 :" }, { "code": "<?php // all sub domain of geeksforgeeks$url1 = \"https%3A%2F%2Fide.geeksforgeeks.org%2F\";$url2 = \"https%3A%2F%2Fpractice.geeksforgeeks.org%2F\";$url3 = \"https%3A%2F%2Fgeeksforgeeks.org%2F\"; // create an array $query = array($url1, $url2, $url3); // print decoded urlforeach ($query as $chunk) { printf(urldecode($chunk). \"\\n\"); }?>", "e": 27209, "s": 26864, "text": null }, { "code": null, "e": 27304, "s": 27209, "text": "https://ide.geeksforgeeks.org/\nhttps://practice.geeksforgeeks.org/\nhttps://geeksforgeeks.org/\n" }, { "code": null, "e": 27363, "s": 27304, "text": "Reference: http://php.net/manual/en/function.urldecode.php" }, { "code": null, "e": 27374, "s": 27363, "text": "nidhi_biet" }, { "code": null, "e": 27387, "s": 27374, "text": "PHP-function" }, { "code": null, "e": 27391, "s": 27387, "text": "PHP" }, { "code": null, "e": 27408, "s": 27391, "text": "Web Technologies" }, { "code": null, "e": 27412, "s": 27408, "text": "PHP" }, { "code": null, "e": 27510, "s": 27412, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27560, "s": 27510, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27600, "s": 27560, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27661, "s": 27600, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 27711, "s": 27661, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 27756, "s": 27711, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 27796, "s": 27756, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27829, "s": 27796, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27874, "s": 27829, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27917, "s": 27874, "text": "How to fetch data from an API in ReactJS ?" } ]
HTML | DOM Input Date disabled Property - GeeksforGeeks
09 Dec, 2021 The Input date disabled property is used to set or return whether a date field should be disabled, or not. An element becomes unusable and un-clickable if it is disabled. Such elements are generally rendered in gray by browsers. The HTML disable attribute is reflected by the Date disabled property.Syntax: To return the disabled property: inputdateObject.disabled To set the disabled property: inputdateObject.disabled = true|false Property Value true|false: It is used to specify whether a date field should be disabled or not. It is false by default. Return Values: It returns a Boolean value which represents that the Input date field would be disabled or not. Below program illustrates the Date disabled property : Example: Disabling a Date field. html <!DOCTYPE html><html> <head> <title>Input Date disabled Property in HTML </title> <style> h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> Input Date disabled Property </h2> <br> <input type="date" id="test_Date"> <p>To disable the date field, double click the "Disable" button. </p> <button ondblclick="My_Date()">Disable </button> <script> function My_Date() { // Set disabled = true. document.getElementById( "test_Date").disabled = true; } </script> </body> </html> Output:Initially: Before clicking the disable button: After clicking the disable button: Supported Browsers: Apple Safari Internet Explorer Firefox Google Chrome Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. ManasChhabra2 chhabradhanvi HTML-DOM HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26139, "s": 26111, "text": "\n09 Dec, 2021" }, { "code": null, "e": 26448, "s": 26139, "text": "The Input date disabled property is used to set or return whether a date field should be disabled, or not. An element becomes unusable and un-clickable if it is disabled. Such elements are generally rendered in gray by browsers. The HTML disable attribute is reflected by the Date disabled property.Syntax: " }, { "code": null, "e": 26483, "s": 26448, "text": "To return the disabled property: " }, { "code": null, "e": 26508, "s": 26483, "text": "inputdateObject.disabled" }, { "code": null, "e": 26540, "s": 26508, "text": "To set the disabled property: " }, { "code": null, "e": 26578, "s": 26540, "text": "inputdateObject.disabled = true|false" }, { "code": null, "e": 26595, "s": 26578, "text": "Property Value " }, { "code": null, "e": 26701, "s": 26595, "text": "true|false: It is used to specify whether a date field should be disabled or not. It is false by default." }, { "code": null, "e": 26813, "s": 26701, "text": "Return Values: It returns a Boolean value which represents that the Input date field would be disabled or not. " }, { "code": null, "e": 26903, "s": 26813, "text": "Below program illustrates the Date disabled property : Example: Disabling a Date field. " }, { "code": null, "e": 26908, "s": 26903, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Input Date disabled Property in HTML </title> <style> h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> Input Date disabled Property </h2> <br> <input type=\"date\" id=\"test_Date\"> <p>To disable the date field, double click the \"Disable\" button. </p> <button ondblclick=\"My_Date()\">Disable </button> <script> function My_Date() { // Set disabled = true. document.getElementById( \"test_Date\").disabled = true; } </script> </body> </html>", "e": 27684, "s": 26908, "text": null }, { "code": null, "e": 27704, "s": 27684, "text": "Output:Initially: " }, { "code": null, "e": 27742, "s": 27704, "text": "Before clicking the disable button: " }, { "code": null, "e": 27779, "s": 27742, "text": "After clicking the disable button: " }, { "code": null, "e": 27801, "s": 27779, "text": "Supported Browsers: " }, { "code": null, "e": 27814, "s": 27801, "text": "Apple Safari" }, { "code": null, "e": 27832, "s": 27814, "text": "Internet Explorer" }, { "code": null, "e": 27840, "s": 27832, "text": "Firefox" }, { "code": null, "e": 27854, "s": 27840, "text": "Google Chrome" }, { "code": null, "e": 27860, "s": 27854, "text": "Opera" }, { "code": null, "e": 27999, "s": 27862, "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": 28013, "s": 27999, "text": "ManasChhabra2" }, { "code": null, "e": 28027, "s": 28013, "text": "chhabradhanvi" }, { "code": null, "e": 28036, "s": 28027, "text": "HTML-DOM" }, { "code": null, "e": 28041, "s": 28036, "text": "HTML" }, { "code": null, "e": 28058, "s": 28041, "text": "Web Technologies" }, { "code": null, "e": 28063, "s": 28058, "text": "HTML" }, { "code": null, "e": 28161, "s": 28063, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28185, "s": 28161, "text": "REST API (Introduction)" }, { "code": null, "e": 28226, "s": 28185, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 28263, "s": 28226, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28292, "s": 28263, "text": "Form validation using jQuery" }, { "code": null, "e": 28312, "s": 28292, "text": "Angular File Upload" }, { "code": null, "e": 28352, "s": 28312, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28385, "s": 28352, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28430, "s": 28385, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28473, "s": 28430, "text": "How to fetch data from an API in ReactJS ?" } ]