title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Choosing and Customizing Loss Functions for Image Processing | by Martin Isaksson | Towards Data Science
Picture this: you’re standing high up a mountain with limited visibility and your goal is to find your way to the bottom. How would you accomplish this? One possible method would be to look around for paths, rejecting those which go up because they would cost you too much time and energy only to learn that they don’t help you meet your goal, while analyzing and selecting from those that will get you to a lower point on the mountain. You then choose a downward path that you think will get you to the bottom using the least amount of time and energy. You then follow that path which leads you to a new point with new choices to make, and continue to repeat the process until you get to the bottom. This is what a machine learning (ML) algorithm does during training. More specifically, the optimizer, which in this mountain analogy roughly describes stochastic gradient descent (SGD) optimization, continually tries new weights and biases until it reaches its goal of finding the optimal values for the model to make accurate predictions. But how does the optimizer know if it’s trying good values and whether the results are trending in the right direction as it progresses through the training data? This is where a loss function comes in. A loss function plays a key role when training (optimizing) ML models. It essentially calculates how good the model is at making predictions using a given set of values (i.e., weights and biases). The calculated output is the loss or error, which is the difference between the prediction the model made using a set of parameter values versus actual ground-truth. For example, if using a neural network1 to perform image classification on blood-cell medical images, the loss function is used during training to gauge how well the model is able to correlate incoming pixels to varying levels of features across the network’s hidden layers, and to ultimately set the correct probabilities for each classification. In the blood-cell image example, earlier layers could represent basic patterns (e.g., arcs, curves, shapes etc.), while subsequent layers could start to represent the higher-level features of blood cells of interest to medical practitioners. Here, the loss function’s role is to help the optimizer correctly predict these different levels of features — from basic patterns through to the final blood cells. The term loss function (sometimes called error function) is often used interchangeably with cost function. However, it’s generally accepted that the former computes loss for one single training example, while the latter computes the average loss across all training data. The overall goal is to find parameter values across all training samples which minimize the average cost (i.e., decrease the cost to some acceptably small value). The cost function takes in all of the model’s parameters and outputs the cost as a single scalar. This function is used by the model’s optimizer which seeks to find the ideal set of parameters to minimize the cost (aka minimizing the function). As we’ll see in this blog, there are a number of cost functions you can use, and you can even customize your own. Thus choosing the right loss function for your use case is as important as having good data labels in order to impose subject matter expertise into a model. In other words, both are critical for reflecting what it means to have a correct model and what to optimize against. The model itself (i.e., the DNN operations) can then be thought of more or less as just a medium for holding and learning that information. Loss functions generally originate from different mathematical areas like statistical analysis, information theory etc., and thus employ a variety of equations for calculating loss in different ways. It shouldn’t come as any surprise then, that each loss function has its pros and cons, and selecting an appropriate loss function depends on many factors including the use case, type of data, optimization method, etc. Loss functions generally fall under two categories: Classification and Regression losses. Classification seeks to predict a value from a finite set of categories, while the goal of regression is to predict a continuous value based on a number of parameters. The following are some common loss functions that you’ll find in PerceptiLabs: Classification Loss Functions: Quadratic (aka mean squared error or MSE): averages the squared difference between predictions and ground truth, with a focus on the average magnitudes of errors regardless of direction2. Cross-Entropy (aka log loss): calculates the differences between the predicted class probabilities and those from ground truth across a logarithmic scale. Useful for object detection. Weighted Cross-Entropy: improves on Cross-Entropy accuracy by adding weights to certain aspects (e.g., certain object classes) which are under-represented in the data (e.g., objects occurring in fewer data samples3). Useful for imbalanced datasets (e.g., when the backgrounds of images over-represent certain objects while objects of interest in the foreground are under-represented). DICE: calculates the Dice coefficient which measures the overlap between the predicted and ground truth samples, where a result of 1 represents a perfect overlap. Useful for image segmentation. Regression Loss Functions: Mean Square Error/Quadratic Loss/L2 Loss: averages the squared difference between predictions and ground truth, with a focus on the average magnitudes of errors regardless of direction. Mean Absolute Error, L1 Loss (used by PerceptiLabs’ Regression component): sums the absolute differences between the predictions and ground truth, and finds the average. Loss functions are used in a variety of use cases. The following table shows common image processing use cases where you might apply these, and other loss functions: Configuring a loss function is extremely easy to do in PerceptiLabs — it’s simply a matter of selecting the desired loss function in your model’s Training component: PerceptiLabs will then update the component’s underlying TensorFlow code as required to integrate that loss function. For example, the following code snippet shows the code for a Training component configured with a Quadratic (MSE) loss function and an SGD optimizer: # Defining loss functionloss_tensor = tf.reduce_mean(tf.square(output_tensor - target_tensor))...optimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=0.001)layer_weight_tensors = {}layer_bias_tensors = {} layer_gradient_tensors = {}for node in graph.inner_nodes: ...compute gradientsupdate_weights = optimizer.minimize(loss_tensor, global_step=global_step) You can also easily customize the loss function by modifying the Training component’s code. Simply configure and create a different loss function and pass it to optimizer.minimize(). For example, the following code creates a cross-entropy loss function: # Defining loss functionn_classes = output_tensor.get_shape().as_list()[-1]flat_pred = tf.reshape(output_tensor, [-1, n_classes])flat_labels = tf.reshape(target_tensor, [-1, n_classes])loss_tensor = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=flat_labels, logits=flat_pred))...update_weights = optimizer.minimize(loss_tensor, global_step=global_step) When you train your model in PerceptiLabs, the Loss tab on the statistics window shows you both the calculated loss during one epoch, and the average loss over all epochs, and this is updated in real-time as the model trains. Since the goal is to minimize loss, you’ll want to see the Loss over all epochs graph gradually decrease, which means the model’s predictions are gradually improving at matching ground truth. Viewing this UI is one of the benefits of using PerceptiLabs, because you can quickly see if training is trending in the right direction, or if you should stop training and adjust your hyperparameters, change your loss function, or switch optimizers. Loss functions play a key role when training your model, and are an essential component for your optimizer. While the PerceptiLabs’ UI makes choosing a loss function a small detail, knowing which loss function to choose for a given use case and model architecture is really a big deal. For more information about loss functions, check out the following articles which do a great job of explaining some of them in detail: Cross-Entropy Loss Function Regression — Why Mean Square Error? How to Choose Loss Functions When Training Deep Learning Neural Networks And for those just starting out with ML or need a refresher on loss functions, be sure to check out Gradient descent, how neural networks learn. This is Part 2 of a great YouTube video series that explains how a neural network works and this episode covers the role of loss functions in gradient descent. 1 For an introduction or refresher on neural networks, check out this excellent YouTube video series.
[ { "code": null, "e": 873, "s": 172, "text": "Picture this: you’re standing high up a mountain with limited visibility and your goal is to find your way to the bottom. How would you accomplish this? One possible method would be to look around for paths, rejecting those which go up because they would cost you too much time and energy only to learn that they don’t help you meet your goal, while analyzing and selecting from those that will get you to a lower point on the mountain. You then choose a downward path that you think will get you to the bottom using the least amount of time and energy. You then follow that path which leads you to a new point with new choices to make, and continue to repeat the process until you get to the bottom." }, { "code": null, "e": 1417, "s": 873, "text": "This is what a machine learning (ML) algorithm does during training. More specifically, the optimizer, which in this mountain analogy roughly describes stochastic gradient descent (SGD) optimization, continually tries new weights and biases until it reaches its goal of finding the optimal values for the model to make accurate predictions. But how does the optimizer know if it’s trying good values and whether the results are trending in the right direction as it progresses through the training data? This is where a loss function comes in." }, { "code": null, "e": 1780, "s": 1417, "text": "A loss function plays a key role when training (optimizing) ML models. It essentially calculates how good the model is at making predictions using a given set of values (i.e., weights and biases). The calculated output is the loss or error, which is the difference between the prediction the model made using a set of parameter values versus actual ground-truth." }, { "code": null, "e": 2535, "s": 1780, "text": "For example, if using a neural network1 to perform image classification on blood-cell medical images, the loss function is used during training to gauge how well the model is able to correlate incoming pixels to varying levels of features across the network’s hidden layers, and to ultimately set the correct probabilities for each classification. In the blood-cell image example, earlier layers could represent basic patterns (e.g., arcs, curves, shapes etc.), while subsequent layers could start to represent the higher-level features of blood cells of interest to medical practitioners. Here, the loss function’s role is to help the optimizer correctly predict these different levels of features — from basic patterns through to the final blood cells." }, { "code": null, "e": 2970, "s": 2535, "text": "The term loss function (sometimes called error function) is often used interchangeably with cost function. However, it’s generally accepted that the former computes loss for one single training example, while the latter computes the average loss across all training data. The overall goal is to find parameter values across all training samples which minimize the average cost (i.e., decrease the cost to some acceptably small value)." }, { "code": null, "e": 3215, "s": 2970, "text": "The cost function takes in all of the model’s parameters and outputs the cost as a single scalar. This function is used by the model’s optimizer which seeks to find the ideal set of parameters to minimize the cost (aka minimizing the function)." }, { "code": null, "e": 3743, "s": 3215, "text": "As we’ll see in this blog, there are a number of cost functions you can use, and you can even customize your own. Thus choosing the right loss function for your use case is as important as having good data labels in order to impose subject matter expertise into a model. In other words, both are critical for reflecting what it means to have a correct model and what to optimize against. The model itself (i.e., the DNN operations) can then be thought of more or less as just a medium for holding and learning that information." }, { "code": null, "e": 4161, "s": 3743, "text": "Loss functions generally originate from different mathematical areas like statistical analysis, information theory etc., and thus employ a variety of equations for calculating loss in different ways. It shouldn’t come as any surprise then, that each loss function has its pros and cons, and selecting an appropriate loss function depends on many factors including the use case, type of data, optimization method, etc." }, { "code": null, "e": 4419, "s": 4161, "text": "Loss functions generally fall under two categories: Classification and Regression losses. Classification seeks to predict a value from a finite set of categories, while the goal of regression is to predict a continuous value based on a number of parameters." }, { "code": null, "e": 4498, "s": 4419, "text": "The following are some common loss functions that you’ll find in PerceptiLabs:" }, { "code": null, "e": 4529, "s": 4498, "text": "Classification Loss Functions:" }, { "code": null, "e": 4717, "s": 4529, "text": "Quadratic (aka mean squared error or MSE): averages the squared difference between predictions and ground truth, with a focus on the average magnitudes of errors regardless of direction2." }, { "code": null, "e": 4901, "s": 4717, "text": "Cross-Entropy (aka log loss): calculates the differences between the predicted class probabilities and those from ground truth across a logarithmic scale. Useful for object detection." }, { "code": null, "e": 5286, "s": 4901, "text": "Weighted Cross-Entropy: improves on Cross-Entropy accuracy by adding weights to certain aspects (e.g., certain object classes) which are under-represented in the data (e.g., objects occurring in fewer data samples3). Useful for imbalanced datasets (e.g., when the backgrounds of images over-represent certain objects while objects of interest in the foreground are under-represented)." }, { "code": null, "e": 5480, "s": 5286, "text": "DICE: calculates the Dice coefficient which measures the overlap between the predicted and ground truth samples, where a result of 1 represents a perfect overlap. Useful for image segmentation." }, { "code": null, "e": 5507, "s": 5480, "text": "Regression Loss Functions:" }, { "code": null, "e": 5693, "s": 5507, "text": "Mean Square Error/Quadratic Loss/L2 Loss: averages the squared difference between predictions and ground truth, with a focus on the average magnitudes of errors regardless of direction." }, { "code": null, "e": 5863, "s": 5693, "text": "Mean Absolute Error, L1 Loss (used by PerceptiLabs’ Regression component): sums the absolute differences between the predictions and ground truth, and finds the average." }, { "code": null, "e": 6029, "s": 5863, "text": "Loss functions are used in a variety of use cases. The following table shows common image processing use cases where you might apply these, and other loss functions:" }, { "code": null, "e": 6195, "s": 6029, "text": "Configuring a loss function is extremely easy to do in PerceptiLabs — it’s simply a matter of selecting the desired loss function in your model’s Training component:" }, { "code": null, "e": 6463, "s": 6195, "text": "PerceptiLabs will then update the component’s underlying TensorFlow code as required to integrate that loss function. For example, the following code snippet shows the code for a Training component configured with a Quadratic (MSE) loss function and an SGD optimizer:" }, { "code": null, "e": 6844, "s": 6463, "text": "# Defining loss functionloss_tensor = tf.reduce_mean(tf.square(output_tensor - target_tensor))...optimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=0.001)layer_weight_tensors = {}layer_bias_tensors = {} layer_gradient_tensors = {}for node in graph.inner_nodes:\t...compute gradientsupdate_weights = optimizer.minimize(loss_tensor, global_step=global_step)" }, { "code": null, "e": 7098, "s": 6844, "text": "You can also easily customize the loss function by modifying the Training component’s code. Simply configure and create a different loss function and pass it to optimizer.minimize(). For example, the following code creates a cross-entropy loss function:" }, { "code": null, "e": 7467, "s": 7098, "text": "# Defining loss functionn_classes = output_tensor.get_shape().as_list()[-1]flat_pred = tf.reshape(output_tensor, [-1, n_classes])flat_labels = tf.reshape(target_tensor, [-1, n_classes])loss_tensor = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=flat_labels, logits=flat_pred))...update_weights = optimizer.minimize(loss_tensor, global_step=global_step)" }, { "code": null, "e": 7693, "s": 7467, "text": "When you train your model in PerceptiLabs, the Loss tab on the statistics window shows you both the calculated loss during one epoch, and the average loss over all epochs, and this is updated in real-time as the model trains." }, { "code": null, "e": 8136, "s": 7693, "text": "Since the goal is to minimize loss, you’ll want to see the Loss over all epochs graph gradually decrease, which means the model’s predictions are gradually improving at matching ground truth. Viewing this UI is one of the benefits of using PerceptiLabs, because you can quickly see if training is trending in the right direction, or if you should stop training and adjust your hyperparameters, change your loss function, or switch optimizers." }, { "code": null, "e": 8422, "s": 8136, "text": "Loss functions play a key role when training your model, and are an essential component for your optimizer. While the PerceptiLabs’ UI makes choosing a loss function a small detail, knowing which loss function to choose for a given use case and model architecture is really a big deal." }, { "code": null, "e": 8557, "s": 8422, "text": "For more information about loss functions, check out the following articles which do a great job of explaining some of them in detail:" }, { "code": null, "e": 8585, "s": 8557, "text": "Cross-Entropy Loss Function" }, { "code": null, "e": 8621, "s": 8585, "text": "Regression — Why Mean Square Error?" }, { "code": null, "e": 8694, "s": 8621, "text": "How to Choose Loss Functions When Training Deep Learning Neural Networks" }, { "code": null, "e": 8999, "s": 8694, "text": "And for those just starting out with ML or need a refresher on loss functions, be sure to check out Gradient descent, how neural networks learn. This is Part 2 of a great YouTube video series that explains how a neural network works and this episode covers the role of loss functions in gradient descent." } ]
Linear Regression Algorithm from Scratch in Python: Step by Step | by Rashida Nasrin Sucky | Towards Data Science
The most basic machine learning algorithm has to be the linear regression algorithm with a single variable. Nowadays, there are so many advanced machine learning algorithms, libraries, and techniques available that linear regression may seem to be not important. But It is always a good idea to learn the basics. That way you will grasp the concepts very clearly. In this article, I will explain the linear regression algorithm step by step. Linear regression uses the very basic idea of prediction. Here is the formula: Y = C + BX We all learned this formula in school. Just to remind you, this is the equation of a straight line. Here, Y is the dependent variable, B is the slope and C is the intercept. Typically, for linear regression, it is written as: Here, ‘h’ is the hypothesis or the predicted dependent variable, X is the input feature, and theta0 and theta1 are the coefficients. Theta values are initialized randomly to start with. Then using gradient descent, we will update the theta value to minimize the cost function. Here is the explanation of cost function and gradient descent. The cost function determines how far the prediction is from the original dependent variable. Here is the formula for that The idea of any machine learning algorithm is to minimize the cost function so that the hypothesis is close to the original dependent variable. We need to optimize the theta value to do that. If we take the partial derivative of the cost function based on theta0 and theta1 respectively, we will get the gradient descent. To update the theta values we need to deduct the gradient descent from the corresponding theta values: After the partial derivative, the formulas above will turn out to be: Here, m is the number of training data and alpha is the learning rate. I am talking about one variable linear regression. That’s why I have only two theta values. If there are many variables, there will be theta values for each variable. The dataset I am going to use is from Andrew Ng’s machine learning course in Coursera. Here is the process of implementing a linear regression step by step in Python. Import the packages and the dataset. Import the packages and the dataset. import numpy as npimport pandas as pddf = pd.read_csv('ex1data1.txt', header = None)df.head() In this dataset, column zero is the input feature and column 1 is the output variable or dependent variable. We will use column 0 to predict column 1 using the straight-line formula above. 2. Plot column 1 against column 0. The relation between the input variable and the output variable is linear. Linear regression works best when the relationship is linear. 3. Initialize the theta values. I am initializing the theta values as zeros. But any other values should also work as well. theta = [0,0] 4. Define the hypothesis and the cost function as per the formulas discussed before. def hypothesis(theta, X): return theta[0] + theta[1]*Xdef cost_calc(theta, X, y): return (1/2*m) * np.sum((hypothesis(theta, X) - y)**2) 5. Calculate the number of training data as the length of the DataFrame. And then define the function for gradient descent. In this function, we will update the theta values until the cost function is it’s minimum. It may take any number of iteration. In each iteration, it will update the theta values and with each updated theta values we will calculate the cost to keep track of the cost. m = len(df)def gradient_descent(theta, X, y, epoch, alpha): cost = [] i = 0 while i < epoch: hx = hypothesis(theta, X) theta[0] -= alpha*(sum(hx-y)/m) theta[1] -= (alpha * np.sum((hx - y) * X))/m cost.append(cost_calc(theta, X, y)) i += 1 return theta, cost 6. Finally, define the predict function. It will get the updated theta from the gradient descent function and predict the hypothesis or the predicted output variable. def predict(theta, X, y, epoch, alpha): theta, cost = gradient_descent(theta, X, y, epoch, alpha) return hypothesis(theta, X), cost, theta 7. Using the predict function, find the hypothesis, cost, and updated theta values. I choose the learning rate as 0.01 and I will run this algorithm for 2000 epochs or iterations. y_predict, cost, theta = predict(theta, df[0], df[1], 2000, 0.01) The final theta values are -3.79 and 1.18. 8. Plot the original y and the hypothesis or the predicted y in the same graph. %matplotlib inlineimport matplotlib.pyplot as pltplt.figure()plt.scatter(df[0], df[1], label = 'Original y')plt.scatter(df[0], y_predict, label = 'predicted y')plt.legend(loc = "upper left")plt.xlabel("input feature")plt.ylabel("Original and Predicted Output")plt.show() The hypothesis plot is a straight line as expected from the formula and the line is passing through in an optimum position. 9. Remember, we kept track of the cost function in each iteration. Let’s plot the cost function. plt.figure()plt.scatter(range(0, len(cost)), cost)plt.show() As I mentioned before, our purpose was to optimize the theta values to minimize the cost. As you can see from this graph, the cost went down drastically in the beginning and then it became stable. That means the theta values are optimized correctly as we expected. I hope this was helpful. Here is the link to the dataset used in this article: github.com Here is the solution to some other machine learning algorithms: Multivariate Linear Regression in Python Step by Step Logistic Regression with Python Using Optimization Function
[ { "code": null, "e": 613, "s": 171, "text": "The most basic machine learning algorithm has to be the linear regression algorithm with a single variable. Nowadays, there are so many advanced machine learning algorithms, libraries, and techniques available that linear regression may seem to be not important. But It is always a good idea to learn the basics. That way you will grasp the concepts very clearly. In this article, I will explain the linear regression algorithm step by step." }, { "code": null, "e": 692, "s": 613, "text": "Linear regression uses the very basic idea of prediction. Here is the formula:" }, { "code": null, "e": 703, "s": 692, "text": "Y = C + BX" }, { "code": null, "e": 929, "s": 703, "text": "We all learned this formula in school. Just to remind you, this is the equation of a straight line. Here, Y is the dependent variable, B is the slope and C is the intercept. Typically, for linear regression, it is written as:" }, { "code": null, "e": 1269, "s": 929, "text": "Here, ‘h’ is the hypothesis or the predicted dependent variable, X is the input feature, and theta0 and theta1 are the coefficients. Theta values are initialized randomly to start with. Then using gradient descent, we will update the theta value to minimize the cost function. Here is the explanation of cost function and gradient descent." }, { "code": null, "e": 1391, "s": 1269, "text": "The cost function determines how far the prediction is from the original dependent variable. Here is the formula for that" }, { "code": null, "e": 1816, "s": 1391, "text": "The idea of any machine learning algorithm is to minimize the cost function so that the hypothesis is close to the original dependent variable. We need to optimize the theta value to do that. If we take the partial derivative of the cost function based on theta0 and theta1 respectively, we will get the gradient descent. To update the theta values we need to deduct the gradient descent from the corresponding theta values:" }, { "code": null, "e": 1886, "s": 1816, "text": "After the partial derivative, the formulas above will turn out to be:" }, { "code": null, "e": 2124, "s": 1886, "text": "Here, m is the number of training data and alpha is the learning rate. I am talking about one variable linear regression. That’s why I have only two theta values. If there are many variables, there will be theta values for each variable." }, { "code": null, "e": 2291, "s": 2124, "text": "The dataset I am going to use is from Andrew Ng’s machine learning course in Coursera. Here is the process of implementing a linear regression step by step in Python." }, { "code": null, "e": 2328, "s": 2291, "text": "Import the packages and the dataset." }, { "code": null, "e": 2365, "s": 2328, "text": "Import the packages and the dataset." }, { "code": null, "e": 2459, "s": 2365, "text": "import numpy as npimport pandas as pddf = pd.read_csv('ex1data1.txt', header = None)df.head()" }, { "code": null, "e": 2648, "s": 2459, "text": "In this dataset, column zero is the input feature and column 1 is the output variable or dependent variable. We will use column 0 to predict column 1 using the straight-line formula above." }, { "code": null, "e": 2683, "s": 2648, "text": "2. Plot column 1 against column 0." }, { "code": null, "e": 2820, "s": 2683, "text": "The relation between the input variable and the output variable is linear. Linear regression works best when the relationship is linear." }, { "code": null, "e": 2944, "s": 2820, "text": "3. Initialize the theta values. I am initializing the theta values as zeros. But any other values should also work as well." }, { "code": null, "e": 2958, "s": 2944, "text": "theta = [0,0]" }, { "code": null, "e": 3043, "s": 2958, "text": "4. Define the hypothesis and the cost function as per the formulas discussed before." }, { "code": null, "e": 3186, "s": 3043, "text": "def hypothesis(theta, X): return theta[0] + theta[1]*Xdef cost_calc(theta, X, y): return (1/2*m) * np.sum((hypothesis(theta, X) - y)**2)" }, { "code": null, "e": 3578, "s": 3186, "text": "5. Calculate the number of training data as the length of the DataFrame. And then define the function for gradient descent. In this function, we will update the theta values until the cost function is it’s minimum. It may take any number of iteration. In each iteration, it will update the theta values and with each updated theta values we will calculate the cost to keep track of the cost." }, { "code": null, "e": 3883, "s": 3578, "text": "m = len(df)def gradient_descent(theta, X, y, epoch, alpha): cost = [] i = 0 while i < epoch: hx = hypothesis(theta, X) theta[0] -= alpha*(sum(hx-y)/m) theta[1] -= (alpha * np.sum((hx - y) * X))/m cost.append(cost_calc(theta, X, y)) i += 1 return theta, cost" }, { "code": null, "e": 4050, "s": 3883, "text": "6. Finally, define the predict function. It will get the updated theta from the gradient descent function and predict the hypothesis or the predicted output variable." }, { "code": null, "e": 4195, "s": 4050, "text": "def predict(theta, X, y, epoch, alpha): theta, cost = gradient_descent(theta, X, y, epoch, alpha) return hypothesis(theta, X), cost, theta" }, { "code": null, "e": 4375, "s": 4195, "text": "7. Using the predict function, find the hypothesis, cost, and updated theta values. I choose the learning rate as 0.01 and I will run this algorithm for 2000 epochs or iterations." }, { "code": null, "e": 4441, "s": 4375, "text": "y_predict, cost, theta = predict(theta, df[0], df[1], 2000, 0.01)" }, { "code": null, "e": 4484, "s": 4441, "text": "The final theta values are -3.79 and 1.18." }, { "code": null, "e": 4564, "s": 4484, "text": "8. Plot the original y and the hypothesis or the predicted y in the same graph." }, { "code": null, "e": 4835, "s": 4564, "text": "%matplotlib inlineimport matplotlib.pyplot as pltplt.figure()plt.scatter(df[0], df[1], label = 'Original y')plt.scatter(df[0], y_predict, label = 'predicted y')plt.legend(loc = \"upper left\")plt.xlabel(\"input feature\")plt.ylabel(\"Original and Predicted Output\")plt.show()" }, { "code": null, "e": 4959, "s": 4835, "text": "The hypothesis plot is a straight line as expected from the formula and the line is passing through in an optimum position." }, { "code": null, "e": 5056, "s": 4959, "text": "9. Remember, we kept track of the cost function in each iteration. Let’s plot the cost function." }, { "code": null, "e": 5117, "s": 5056, "text": "plt.figure()plt.scatter(range(0, len(cost)), cost)plt.show()" }, { "code": null, "e": 5382, "s": 5117, "text": "As I mentioned before, our purpose was to optimize the theta values to minimize the cost. As you can see from this graph, the cost went down drastically in the beginning and then it became stable. That means the theta values are optimized correctly as we expected." }, { "code": null, "e": 5461, "s": 5382, "text": "I hope this was helpful. Here is the link to the dataset used in this article:" }, { "code": null, "e": 5472, "s": 5461, "text": "github.com" }, { "code": null, "e": 5536, "s": 5472, "text": "Here is the solution to some other machine learning algorithms:" }, { "code": null, "e": 5590, "s": 5536, "text": "Multivariate Linear Regression in Python Step by Step" } ]
lsof - Unix, Linux Command
lsof: list open files. lsof [ -?abChlnNOPRtUvVX ] [ -A A ] [ -c c ] [ +c c ] [ +|-d d ] [ +|-D D ] [ +|-e s ] [ +|-f [cfgGn] ] [ -F [f] ] [ -g[s] ] [ -i [i] ] [ -k k ] [ +|-L [l] ] [ +|-m m ] [ +|-M ][ -o [o] ] [ -p s ] [ +|-r [t[m]] ] [ -s [p:s] ] [ -S [t] ] [ -T [t] ] [ -u s ] [ +|-w ] [ -x [fl] ] [ -z [z] ] [ -Z [Z] ] [ -- ] [names] lsof [ -?abChlnNOPRtUvVX ] [ -A A ] [ -c c ] [ +c c ] [ +|-d d ] [ +|-D D ] [ +|-e s ] [ +|-f [cfgGn] ] [ -F [f] ] [ -g[s] ] [ -i [i] ] [ -k k ] [ +|-L [l] ] [ +|-m m ] [ +|-M ][ -o [o] ] [ -p s ] [ +|-r [t[m]] ] [ -s [p:s] ] [ -S [t] ] [ -T [t] ] [ -u s ] [ +|-w ] [ -x [fl] ] [ -z [z] ] [ -Z [Z] ] [ -- ] [names] An open file may be a regular file, a directory, a block special file, a character special file, an executing text reference, a library, a stream or a network file (Internet socket, NFS file or UNIX domain socket.) A specific file or all the files in a file system may be selected by path. Instead of a formatted display, lsof will produce output that can be parsed by other programs. In addition to producing a single output list, lsof will run in repeat mode. In repeat mode it will produce output, delay, then repeat the output operation until stopped with an interrupt or quit signal. Example-1: To list all Open Files: # lsof output: # lsof COMMAND PID TID USER FD TYPE DEVICE SIZE/OFF NODE NAMEinit 1 root cwd DIR 252,0 4096 2 /init 1 root rtd DIR 252,0 4096 2 /init 1 root txt REG 252,0 265848 54 /sbin/initinit 1 root mem REG 252,0 47712 393444 /lib/x86_64-linux-gnu/libnss_files-2.19.soinit 1 root mem REG 252,0 47760 393448 /lib/x86_64-linux-gnu/libnss_nis-2.19.soinit 1 root mem REG 252,0 97296 393438 /lib/x86_64-linux-gnu/libnsl-2.19.soinit 1 root mem REG 252,0 39824 393440 /lib/x86_64-linux-gnu/libnss_compat-2.19.soinit 1 root mem REG 252,0 14664 393401 /lib/x86_64-linux-gnu/libdl-2.19.soinit 1 root mem REG 252,0 252032 393460 /lib/x86_64-linux-gnu/libpcre.so.3.13.1init 1 root mem REG 252,0 141574 393475 /lib/x86_64-linux-gnu/libpthread-2.19.soinit 1 root mem REG 252,0 1840928 393385 /lib/x86_64-linux-gnu/libc-2.19.soinit 1 root mem REG 252,0 31792 393481 /lib/x86_64-linux-gnu/librt-2.19.soinit 1 root mem REG 252,0 43464 393417 /lib/x86_64-linux-gnu/libjson-c.so.2.0.0init 1 root mem REG 252,0 134296 393483 /lib/x86_64-linux-gnu/libselinux.so.1... kworker/0 5 root cwd DIR 252,0 4096 2 /kworker/0 5 root rtd DIR 252,0 4096 2 /kworker/0 5 root txt unknown /proc/5/exe more... Example-2: To list User Specific Opened Files: # lsof -u ubuntu output: COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEsshd 1427 ubuntu cwd DIR 252,0 4096 2 /sshd 1427 ubuntu rtd DIR 252,0 4096 2 /sshd 1427 ubuntu txt REG 252,0 766784 800542 /usr/sbin/sshdsshd 1427 ubuntu mem REG 252,0 14464 393517 /lib/x86_64-linux-gnu/security/pam_env.sosshd 1427 ubuntu mem REG 252,0 22896 393526 /lib/x86_64-linux-gnu/security/pam_limits.sosshd 1427 ubuntu mem REG 252,0 10320 393530 /lib/x86_64-linux-gnu/security/pam_mail.sosshd 1427 ubuntu mem REG 252,0 10344 393532 /lib/x86_64-linux-gnu/security/pam_motd.sosshd 1427 ubuntu mem REG 252,0 14592 393455 /lib/x86_64-linux-gnu/libpam_misc.so.0.82.0sshd 1427 ubuntu mem REG 252,0 38920 393435 /lib/x86_64-linux-gnu/libnih-dbus.so.1.0.0sshd 1427 ubuntu mem REG 252,0 96280 393437 /lib/x86_64-linux-gnu/libnih.so.1.0.0sshd 1427 ubuntu mem REG 252,0 108480 393390 /lib/x86_64-linux-gnu/libcgmanager.so.0.0.0sshd 1427 ubuntu mem REG 252,0 42864 398327 /lib/x86_64-linux-gnu/security/pam_systemd.sosshd 1427 ubuntu mem REG 252,0 10376 393550 /lib/x86_64-linux-gnu/security/pam_umask.sosshd 1427 ubuntu mem REG 252,0 10288 393524 /lib/x86_64-linux-gnu/security/pam_keyinit.sosshd 1427 ubuntu mem REG 252,0 10344 393529 /lib/x86_64-linux-gnu/security/pam_loginuid.sosshd 1427 ubuntu mem REG 252,0 18752 393540 /lib/x86_64-linux-gnu/security/pam_selinux.sosshd 1427 ubuntu mem REG 252,0 10272 393534 /lib/x86_64-linux-gnu/security/pam_nologin.sosshd 1427 ubuntu mem REG 252,0 18952 393388 /lib/x86_64-linux-gnu/libcap.so.2.24sshd 1427 ubuntu mem REG 252,0 10376 393513 /lib/x86_64-linux-gnu/security/pam_cap.sosshd 1427 ubuntu mem REG 252,0 6112 393535 /lib/x86_64-linux-gnu/security/pam_permit.sosshd 1427 ubuntu mem REG 252,0 6024 393515 /lib/x86_64-linux-gnu/security/pam_deny.sosshd 1427 ubuntu mem REG 252,0 60288 393551 /lib/x86_64-linux-gnu/security/pam_unix.sosshd 1427 ubuntu mem REG 252,0 22952 393442 /lib/x86_64-linux-gnu/libnss_dns-2.19.so Example-3: To find Processes running on Specific Port: # lsof -i TCP:22 output: # lsof -i TCP:22COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEsshd 1053 root 3u IPv4 13211 0t0 TCP *:ssh (LISTEN)sshd 1053 root 4u IPv6 13213 0t0 TCP *:ssh (LISTEN)sshd 1377 root 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1427 ubuntu 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1840 root 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED)sshd 1930 ubuntu 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED) Example-4: To list Only IPv4 & IPv6 Open Files: # lsof -i 4 # lsof -i 6 output: # lsof -i 4COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEdhclient 869 root 6u IPv4 11754 0t0 UDP *:bootpcdhclient 869 root 20u IPv4 11700 0t0 UDP *:26374sshd 1053 root 3u IPv4 13211 0t0 TCP *:ssh (LISTEN)dnsmasq 1372 libvirt-dnsmasq 4u IPv4 13970 0t0 UDP *:bootpsdnsmasq 1372 libvirt-dnsmasq 6u IPv4 13973 0t0 UDP 192.168.122.1:domaindnsmasq 1372 libvirt-dnsmasq 7u IPv4 13974 0t0 TCP 192.168.122.1:domain (LISTEN)sshd 1377 root 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1427 ubuntu 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1840 root 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED)sshd 1930 ubuntu 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED) # lsof -i 6COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEdhclient 869 root 21u IPv6 11701 0t0 UDP *:22830sshd 1053 root 4u IPv6 13213 0t0 TCP *:ssh (LISTEN) Example-5: To list Open Files of TCP Port ranges 1-1024: # lsof -i TCP:1-1024 output: # lsof -i TCP:1-1024COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEsshd 1053 root 3u IPv4 13211 0t0 TCP *:ssh (LISTEN)sshd 1053 root 4u IPv6 13213 0t0 TCP *:ssh (LISTEN)dnsmasq 1372 libvirt-dnsmasq 7u IPv4 13974 0t0 TCP 192.168.122.1:domain (LISTEN)sshd 1377 root 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1427 ubuntu 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1840 root 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED)sshd 1930 ubuntu 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED) Example-6: To Exclude User with ‘^’ Characte # lsof -i -u^root output: # lsof -i -u^rootCOMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEdnsmasq 1372 libvirt-dnsmasq 4u IPv4 13970 0t0 UDP *:bootpsdnsmasq 1372 libvirt-dnsmasq 6u IPv4 13973 0t0 UDP 192.168.122.1:domaindnsmasq 1372 libvirt-dnsmasq 7u IPv4 13974 0t0 TCP 192.168.122.1:domain (LISTEN)sshd 1427 ubuntu 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1930 ubuntu 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED) Example-7: To find Out who’s Looking What Files and Commands: # lsof -i -u user1 output: # lsof -i -u user1COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEdhclient 869 root 6u IPv4 11754 0t0 UDP *:bootpcdhclient 869 root 20u IPv4 11700 0t0 UDP *:26374dhclient 869 root 21u IPv6 11701 0t0 UDP *:22830sshd 1053 root 3u IPv4 13211 0t0 TCP *:ssh (LISTEN)sshd 1053 root 4u IPv6 13213 0t0 TCP *:ssh (LISTEN)dnsmasq 1372 libvirt-dnsmasq 4u IPv4 13970 0t0 UDP *:bootpsdnsmasq 1372 libvirt-dnsmasq 6u IPv4 13973 0t0 UDP 192.168.122.1:domaindnsmasq 1372 libvirt-dnsmasq 7u IPv4 13974 0t0 TCP 192.168.122.1:domain (LISTEN)sshd 1377 root 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1427 ubuntu 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1840 root 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED)sshd 1930 ubuntu 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED) Example-8: To list all Network Connections: # lsof -i output: # lsof -iCOMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEdhclient 869 root 6u IPv4 11754 0t0 UDP *:bootpcdhclient 869 root 20u IPv4 11700 0t0 UDP *:26374dhclient 869 root 21u IPv6 11701 0t0 UDP *:22830sshd 1053 root 3u IPv4 13211 0t0 TCP *:ssh (LISTEN)sshd 1053 root 4u IPv6 13213 0t0 TCP *:ssh (LISTEN)dnsmasq 1372 libvirt-dnsmasq 4u IPv4 13970 0t0 UDP *:bootpsdnsmasq 1372 libvirt-dnsmasq 6u IPv4 13973 0t0 UDP 192.168.122.1:domaindnsmasq 1372 libvirt-dnsmasq 7u IPv4 13974 0t0 TCP 192.168.122.1:domain (LISTEN)sshd 1377 root 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1427 ubuntu 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1840 root 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED)sshd 1930 ubuntu 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED) Example-9: To list processes which opened a specific file: # lsof /var/log/syslog output: # lsof /var/log/syslogCOMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMErsyslogd 687 syslog 1w REG 252,0 1812935 11325 /var/log/syslog Example-10: To list opened files under a directory: # lsof +D /var/log/ output: # lsof +D /var/log/COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEinit 1 root 14w REG 252,0 733 11346 /var/log/upstart/systemd-logind.logrsyslogd 687 syslog 1w REG 252,0 1813034 11325 /var/log/syslogrsyslogd 687 syslog 2w REG 252,0 1694014 11335 /var/log/kern.logrsyslogd 687 syslog 4w REG 252,0 39603 11870 /var/log/auth.loglibvirtd 1171 root 4w REG 252,0 0 135812 /var/log/libvirt/libvirtd.log Example-11: To list opened files based on process names: # lsof -c ssh -c init output: COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEinit 1 root cwd DIR 252,0 4096 2 /init 1 root rtd DIR 252,0 4096 2 /init 1 root txt REG 252,0 265848 54 /sbin/initinit 1 root mem REG 252,0 47712 393444 /lib/x86_64-linux-gnu/libnss_files-2.19.soinit 1 root mem REG 252,0 47760 393448 /lib/x86_64-linux-gnu/libnss_nis-2.19.soinit 1 root mem REG 252,0 97296 393438 /lib/x86_64-linux-gnu/libnsl-2.19.soinit 1 root mem REG 252,0 39824 393440 /lib/x86_64-linux-gnu/libnss_compat-2.19.soinit 1 root mem REG 252,0 14664 393401 /lib/x86_64-linux-gnu/libdl-2.19.soinit 1 root mem REG 252,0 252032 393460 /lib/x86_64-linux-gnu/libpcre.so.3.13.1init 1 root mem REG 252,0 141574 393475 /lib/x86_64-linux-gnu/libpthread-2.19.soinit 1 root mem REG 252,0 1840928 393385 /lib/x86_64-linux-gnu/libc-2.19.soinit 1 root mem REG 252,0 31792 393481 /lib/x86_64-linux-gnu/librt-2.19.soinit 1 root mem REG 252,0 43464 393417 /lib/x86_64-linux-gnu/libjson-c.so.2.0.0
[ { "code": null, "e": 10734, "s": 10711, "text": "lsof: list open files." }, { "code": null, "e": 11052, "s": 10734, "text": "lsof [ -?abChlnNOPRtUvVX ] [ -A A ] [ -c c ] [ +c c ] [ +|-d d ] [ +|-D D ] [ +|-e s ] [ +|-f [cfgGn] ] [ -F [f] ] [ -g[s] ] [ -i [i] ] \n[ -k k ] [ +|-L [l] ] [ +|-m m ] [ +|-M ][ -o [o] ] [ -p s ] [ +|-r [t[m]] ] [ -s [p:s] ] [ -S [t] ] [ -T [t] ] [ -u s ] [ +|-w ] \n[ -x [fl] ] [ -z [z] ] [ -Z [Z] ] [ -- ] [names]\n" }, { "code": null, "e": 11369, "s": 11052, "text": "lsof [ -?abChlnNOPRtUvVX ] [ -A A ] [ -c c ] [ +c c ] [ +|-d d ] [ +|-D D ] [ +|-e s ] [ +|-f [cfgGn] ] [ -F [f] ] [ -g[s] ] [ -i [i] ] \n[ -k k ] [ +|-L [l] ] [ +|-m m ] [ +|-M ][ -o [o] ] [ -p s ] [ +|-r [t[m]] ] [ -s [p:s] ] [ -S [t] ] [ -T [t] ] [ -u s ] [ +|-w ] \n[ -x [fl] ] [ -z [z] ] [ -Z [Z] ] [ -- ] [names]" }, { "code": null, "e": 11958, "s": 11369, "text": "An open file may be a regular file, a directory, a block special file, a character special file, an executing text reference, a library, a stream or a network file (Internet socket, NFS file or UNIX domain socket.) A specific file or all the files in a file system may be selected by path.\nInstead of a formatted display, lsof will produce output that can be parsed by other programs. In addition to producing a single output list, lsof will run in repeat mode. In repeat mode it will produce output, delay, then repeat the output operation until stopped with an interrupt or quit signal." }, { "code": null, "e": 11969, "s": 11958, "text": "Example-1:" }, { "code": null, "e": 11993, "s": 11969, "text": "To list all Open Files:" }, { "code": null, "e": 12000, "s": 11993, "text": "# lsof" }, { "code": null, "e": 12008, "s": 12000, "text": "output:" }, { "code": null, "e": 13806, "s": 12008, "text": "# lsof COMMAND PID TID USER FD TYPE DEVICE SIZE/OFF NODE NAMEinit 1 root cwd DIR 252,0 4096 2 /init 1 root rtd DIR 252,0 4096 2 /init 1 root txt REG 252,0 265848 54 /sbin/initinit 1 root mem REG 252,0 47712 393444 /lib/x86_64-linux-gnu/libnss_files-2.19.soinit 1 root mem REG 252,0 47760 393448 /lib/x86_64-linux-gnu/libnss_nis-2.19.soinit 1 root mem REG 252,0 97296 393438 /lib/x86_64-linux-gnu/libnsl-2.19.soinit 1 root mem REG 252,0 39824 393440 /lib/x86_64-linux-gnu/libnss_compat-2.19.soinit 1 root mem REG 252,0 14664 393401 /lib/x86_64-linux-gnu/libdl-2.19.soinit 1 root mem REG 252,0 252032 393460 /lib/x86_64-linux-gnu/libpcre.so.3.13.1init 1 root mem REG 252,0 141574 393475 /lib/x86_64-linux-gnu/libpthread-2.19.soinit 1 root mem REG 252,0 1840928 393385 /lib/x86_64-linux-gnu/libc-2.19.soinit 1 root mem REG 252,0 31792 393481 /lib/x86_64-linux-gnu/librt-2.19.soinit 1 root mem REG 252,0 43464 393417 /lib/x86_64-linux-gnu/libjson-c.so.2.0.0init 1 root mem REG 252,0 134296 393483 /lib/x86_64-linux-gnu/libselinux.so.1..." }, { "code": null, "e": 14090, "s": 13806, "text": "kworker/0 5 root cwd DIR 252,0 4096 2 /kworker/0 5 root rtd DIR 252,0 4096 2 /kworker/0 5 root txt unknown /proc/5/exe" }, { "code": null, "e": 14098, "s": 14090, "text": "more..." }, { "code": null, "e": 14109, "s": 14098, "text": "Example-2:" }, { "code": null, "e": 14145, "s": 14109, "text": "To list User Specific Opened Files:" }, { "code": null, "e": 14162, "s": 14145, "text": "# lsof -u ubuntu" }, { "code": null, "e": 14170, "s": 14162, "text": "output:" }, { "code": null, "e": 16647, "s": 14170, "text": "COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEsshd 1427 ubuntu cwd DIR 252,0 4096 2 /sshd 1427 ubuntu rtd DIR 252,0 4096 2 /sshd 1427 ubuntu txt REG 252,0 766784 800542 /usr/sbin/sshdsshd 1427 ubuntu mem REG 252,0 14464 393517 /lib/x86_64-linux-gnu/security/pam_env.sosshd 1427 ubuntu mem REG 252,0 22896 393526 /lib/x86_64-linux-gnu/security/pam_limits.sosshd 1427 ubuntu mem REG 252,0 10320 393530 /lib/x86_64-linux-gnu/security/pam_mail.sosshd 1427 ubuntu mem REG 252,0 10344 393532 /lib/x86_64-linux-gnu/security/pam_motd.sosshd 1427 ubuntu mem REG 252,0 14592 393455 /lib/x86_64-linux-gnu/libpam_misc.so.0.82.0sshd 1427 ubuntu mem REG 252,0 38920 393435 /lib/x86_64-linux-gnu/libnih-dbus.so.1.0.0sshd 1427 ubuntu mem REG 252,0 96280 393437 /lib/x86_64-linux-gnu/libnih.so.1.0.0sshd 1427 ubuntu mem REG 252,0 108480 393390 /lib/x86_64-linux-gnu/libcgmanager.so.0.0.0sshd 1427 ubuntu mem REG 252,0 42864 398327 /lib/x86_64-linux-gnu/security/pam_systemd.sosshd 1427 ubuntu mem REG 252,0 10376 393550 /lib/x86_64-linux-gnu/security/pam_umask.sosshd 1427 ubuntu mem REG 252,0 10288 393524 /lib/x86_64-linux-gnu/security/pam_keyinit.sosshd 1427 ubuntu mem REG 252,0 10344 393529 /lib/x86_64-linux-gnu/security/pam_loginuid.sosshd 1427 ubuntu mem REG 252,0 18752 393540 /lib/x86_64-linux-gnu/security/pam_selinux.sosshd 1427 ubuntu mem REG 252,0 10272 393534 /lib/x86_64-linux-gnu/security/pam_nologin.sosshd 1427 ubuntu mem REG 252,0 18952 393388 /lib/x86_64-linux-gnu/libcap.so.2.24sshd 1427 ubuntu mem REG 252,0 10376 393513 /lib/x86_64-linux-gnu/security/pam_cap.sosshd 1427 ubuntu mem REG 252,0 6112 393535 /lib/x86_64-linux-gnu/security/pam_permit.sosshd 1427 ubuntu mem REG 252,0 6024 393515 /lib/x86_64-linux-gnu/security/pam_deny.sosshd 1427 ubuntu mem REG 252,0 60288 393551 /lib/x86_64-linux-gnu/security/pam_unix.sosshd 1427 ubuntu mem REG 252,0 22952 393442 /lib/x86_64-linux-gnu/libnss_dns-2.19.so" }, { "code": null, "e": 16658, "s": 16647, "text": "Example-3:" }, { "code": null, "e": 16702, "s": 16658, "text": "To find Processes running on Specific Port:" }, { "code": null, "e": 16719, "s": 16702, "text": "# lsof -i TCP:22" }, { "code": null, "e": 16727, "s": 16719, "text": "output:" }, { "code": null, "e": 17419, "s": 16727, "text": "# lsof -i TCP:22COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEsshd 1053 root 3u IPv4 13211 0t0 TCP *:ssh (LISTEN)sshd 1053 root 4u IPv6 13213 0t0 TCP *:ssh (LISTEN)sshd 1377 root 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1427 ubuntu 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1840 root 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED)sshd 1930 ubuntu 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED)" }, { "code": null, "e": 17430, "s": 17419, "text": "Example-4:" }, { "code": null, "e": 17467, "s": 17430, "text": "To list Only IPv4 & IPv6 Open Files:" }, { "code": null, "e": 17479, "s": 17467, "text": "# lsof -i 4" }, { "code": null, "e": 17491, "s": 17479, "text": "# lsof -i 6" }, { "code": null, "e": 17499, "s": 17491, "text": "output:" }, { "code": null, "e": 18566, "s": 17499, "text": "# lsof -i 4COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEdhclient 869 root 6u IPv4 11754 0t0 UDP *:bootpcdhclient 869 root 20u IPv4 11700 0t0 UDP *:26374sshd 1053 root 3u IPv4 13211 0t0 TCP *:ssh (LISTEN)dnsmasq 1372 libvirt-dnsmasq 4u IPv4 13970 0t0 UDP *:bootpsdnsmasq 1372 libvirt-dnsmasq 6u IPv4 13973 0t0 UDP 192.168.122.1:domaindnsmasq 1372 libvirt-dnsmasq 7u IPv4 13974 0t0 TCP 192.168.122.1:domain (LISTEN)sshd 1377 root 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1427 ubuntu 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1840 root 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED)sshd 1930 ubuntu 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED)" }, { "code": null, "e": 18759, "s": 18566, "text": "# lsof -i 6COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEdhclient 869 root 21u IPv6 11701 0t0 UDP *:22830sshd 1053 root 4u IPv6 13213 0t0 TCP *:ssh (LISTEN)" }, { "code": null, "e": 18770, "s": 18759, "text": "Example-5:" }, { "code": null, "e": 18816, "s": 18770, "text": "To list Open Files of TCP Port ranges 1-1024:" }, { "code": null, "e": 18837, "s": 18816, "text": "# lsof -i TCP:1-1024" }, { "code": null, "e": 18845, "s": 18837, "text": "output:" }, { "code": null, "e": 19696, "s": 18845, "text": "# lsof -i TCP:1-1024COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEsshd 1053 root 3u IPv4 13211 0t0 TCP *:ssh (LISTEN)sshd 1053 root 4u IPv6 13213 0t0 TCP *:ssh (LISTEN)dnsmasq 1372 libvirt-dnsmasq 7u IPv4 13974 0t0 TCP 192.168.122.1:domain (LISTEN)sshd 1377 root 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1427 ubuntu 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1840 root 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED)sshd 1930 ubuntu 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED)" }, { "code": null, "e": 19707, "s": 19696, "text": "Example-6:" }, { "code": null, "e": 19741, "s": 19707, "text": "To Exclude User with ‘^’ Characte" }, { "code": null, "e": 19759, "s": 19741, "text": "# lsof -i -u^root" }, { "code": null, "e": 19767, "s": 19759, "text": "output:" }, { "code": null, "e": 20355, "s": 19767, "text": "# lsof -i -u^rootCOMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEdnsmasq 1372 libvirt-dnsmasq 4u IPv4 13970 0t0 UDP *:bootpsdnsmasq 1372 libvirt-dnsmasq 6u IPv4 13973 0t0 UDP 192.168.122.1:domaindnsmasq 1372 libvirt-dnsmasq 7u IPv4 13974 0t0 TCP 192.168.122.1:domain (LISTEN)sshd 1427 ubuntu 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1930 ubuntu 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED)" }, { "code": null, "e": 20366, "s": 20355, "text": "Example-7:" }, { "code": null, "e": 20417, "s": 20366, "text": "To find Out who’s Looking What Files and Commands:" }, { "code": null, "e": 20436, "s": 20417, "text": "# lsof -i -u user1" }, { "code": null, "e": 20444, "s": 20436, "text": "output:" }, { "code": null, "e": 21666, "s": 20444, "text": "# lsof -i -u user1COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEdhclient 869 root 6u IPv4 11754 0t0 UDP *:bootpcdhclient 869 root 20u IPv4 11700 0t0 UDP *:26374dhclient 869 root 21u IPv6 11701 0t0 UDP *:22830sshd 1053 root 3u IPv4 13211 0t0 TCP *:ssh (LISTEN)sshd 1053 root 4u IPv6 13213 0t0 TCP *:ssh (LISTEN)dnsmasq 1372 libvirt-dnsmasq 4u IPv4 13970 0t0 UDP *:bootpsdnsmasq 1372 libvirt-dnsmasq 6u IPv4 13973 0t0 UDP 192.168.122.1:domaindnsmasq 1372 libvirt-dnsmasq 7u IPv4 13974 0t0 TCP 192.168.122.1:domain (LISTEN)sshd 1377 root 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1427 ubuntu 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1840 root 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED)sshd 1930 ubuntu 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED)" }, { "code": null, "e": 21677, "s": 21666, "text": "Example-8:" }, { "code": null, "e": 21710, "s": 21677, "text": "To list all Network Connections:" }, { "code": null, "e": 21720, "s": 21710, "text": "# lsof -i" }, { "code": null, "e": 21728, "s": 21720, "text": "output:" }, { "code": null, "e": 22940, "s": 21728, "text": "# lsof -iCOMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEdhclient 869 root 6u IPv4 11754 0t0 UDP *:bootpcdhclient 869 root 20u IPv4 11700 0t0 UDP *:26374dhclient 869 root 21u IPv6 11701 0t0 UDP *:22830sshd 1053 root 3u IPv4 13211 0t0 TCP *:ssh (LISTEN)sshd 1053 root 4u IPv6 13213 0t0 TCP *:ssh (LISTEN)dnsmasq 1372 libvirt-dnsmasq 4u IPv4 13970 0t0 UDP *:bootpsdnsmasq 1372 libvirt-dnsmasq 6u IPv4 13973 0t0 UDP 192.168.122.1:domaindnsmasq 1372 libvirt-dnsmasq 7u IPv4 13974 0t0 TCP 192.168.122.1:domain (LISTEN)sshd 1377 root 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1427 ubuntu 3u IPv4 13987 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:63725 (ESTABLISHED)sshd 1840 root 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED)sshd 1930 ubuntu 3u IPv4 14871 0t0 TCP testserver.tutorailspoint.com:ssh->192.168.134.1:53307 (ESTABLISHED)" }, { "code": null, "e": 22951, "s": 22940, "text": "Example-9:" }, { "code": null, "e": 22999, "s": 22951, "text": "To list processes which opened a specific file:" }, { "code": null, "e": 23022, "s": 22999, "text": "# lsof /var/log/syslog" }, { "code": null, "e": 23030, "s": 23022, "text": "output:" }, { "code": null, "e": 23181, "s": 23030, "text": "# lsof /var/log/syslogCOMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMErsyslogd 687 syslog 1w REG 252,0 1812935 11325 /var/log/syslog" }, { "code": null, "e": 23193, "s": 23181, "text": "Example-10:" }, { "code": null, "e": 23233, "s": 23193, "text": "To list opened files under a directory:" }, { "code": null, "e": 23253, "s": 23233, "text": "# lsof +D /var/log/" }, { "code": null, "e": 23261, "s": 23253, "text": "output:" }, { "code": null, "e": 23734, "s": 23261, "text": "# lsof +D /var/log/COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEinit 1 root 14w REG 252,0 733 11346 /var/log/upstart/systemd-logind.logrsyslogd 687 syslog 1w REG 252,0 1813034 11325 /var/log/syslogrsyslogd 687 syslog 2w REG 252,0 1694014 11335 /var/log/kern.logrsyslogd 687 syslog 4w REG 252,0 39603 11870 /var/log/auth.loglibvirtd 1171 root 4w REG 252,0 0 135812 /var/log/libvirt/libvirtd.log" }, { "code": null, "e": 23746, "s": 23734, "text": "Example-11:" }, { "code": null, "e": 23791, "s": 23746, "text": "To list opened files based on process names:" }, { "code": null, "e": 23813, "s": 23791, "text": "# lsof -c ssh -c init" }, { "code": null, "e": 23821, "s": 23813, "text": "output:" } ]
Arduino - Ultrasonic Sensor
The HC-SR04 ultrasonic sensor uses SONAR to determine the distance of an object just like the bats do. It offers excellent non-contact range detection with high accuracy and stable readings in an easy-to-use package from 2 cm to 400 cm or 1” to 13 feet. The operation is not affected by sunlight or black material, although acoustically, soft materials like cloth can be difficult to detect. It comes complete with ultrasonic transmitter and receiver module. Power Supply − +5V DC Quiescent Current − <2mA Working Current − 15mA Effectual Angle − <15° Ranging Distance − 2cm – 400 cm/1′′ – 13ft Resolution − 0.3 cm Measuring Angle − 30 degree You will need the following components − 1 × Breadboard 1 × Arduino Uno R3 1 × ULTRASONIC Sensor (HC-SR04) Follow the circuit diagram and make the connections as shown in the image given below. Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New. const int pingPin = 7; // Trigger Pin of Ultrasonic Sensor const int echoPin = 6; // Echo Pin of Ultrasonic Sensor void setup() { Serial.begin(9600); // Starting Serial Terminal } void loop() { long duration, inches, cm; pinMode(pingPin, OUTPUT); digitalWrite(pingPin, LOW); delayMicroseconds(2); digitalWrite(pingPin, HIGH); delayMicroseconds(10); digitalWrite(pingPin, LOW); pinMode(echoPin, INPUT); duration = pulseIn(echoPin, HIGH); inches = microsecondsToInches(duration); cm = microsecondsToCentimeters(duration); Serial.print(inches); Serial.print("in, "); Serial.print(cm); Serial.print("cm"); Serial.println(); delay(100); } long microsecondsToInches(long microseconds) { return microseconds / 74 / 2; } long microsecondsToCentimeters(long microseconds) { return microseconds / 29 / 2; } The Ultrasonic sensor has four terminals - +5V, Trigger, Echo, and GND connected as follows − Connect the +5V pin to +5v on your Arduino board. Connect Trigger to digital pin 7 on your Arduino board. Connect Echo to digital pin 6 on your Arduino board. Connect GND with GND on Arduino. In our program, we have displayed the distance measured by the sensor in inches and cm via the serial port. You will see the distance measured by sensor in inches and cm on Arduino serial monitor.
[ { "code": null, "e": 3258, "s": 3004, "text": "The HC-SR04 ultrasonic sensor uses SONAR to determine the distance of an object just like the bats do. It offers excellent non-contact range detection with high accuracy and stable readings in an easy-to-use package from 2 cm to 400 cm or 1” to 13 feet." }, { "code": null, "e": 3463, "s": 3258, "text": "The operation is not affected by sunlight or black material, although acoustically, soft materials like cloth can be difficult to detect. It comes complete with ultrasonic transmitter and receiver module." }, { "code": null, "e": 3485, "s": 3463, "text": "Power Supply − +5V DC" }, { "code": null, "e": 3510, "s": 3485, "text": "Quiescent Current − <2mA" }, { "code": null, "e": 3533, "s": 3510, "text": "Working Current − 15mA" }, { "code": null, "e": 3556, "s": 3533, "text": "Effectual Angle − <15°" }, { "code": null, "e": 3599, "s": 3556, "text": "Ranging Distance − 2cm – 400 cm/1′′ – 13ft" }, { "code": null, "e": 3619, "s": 3599, "text": "Resolution − 0.3 cm" }, { "code": null, "e": 3647, "s": 3619, "text": "Measuring Angle − 30 degree" }, { "code": null, "e": 3688, "s": 3647, "text": "You will need the following components −" }, { "code": null, "e": 3703, "s": 3688, "text": "1 × Breadboard" }, { "code": null, "e": 3722, "s": 3703, "text": "1 × Arduino Uno R3" }, { "code": null, "e": 3754, "s": 3722, "text": "1 × ULTRASONIC Sensor (HC-SR04)" }, { "code": null, "e": 3841, "s": 3754, "text": "Follow the circuit diagram and make the connections as shown in the image given below." }, { "code": null, "e": 3987, "s": 3841, "text": "Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New." }, { "code": null, "e": 4848, "s": 3987, "text": "const int pingPin = 7; // Trigger Pin of Ultrasonic Sensor\nconst int echoPin = 6; // Echo Pin of Ultrasonic Sensor\n\nvoid setup() {\n Serial.begin(9600); // Starting Serial Terminal\n}\n\nvoid loop() {\n long duration, inches, cm;\n pinMode(pingPin, OUTPUT);\n digitalWrite(pingPin, LOW);\n delayMicroseconds(2);\n digitalWrite(pingPin, HIGH);\n delayMicroseconds(10);\n digitalWrite(pingPin, LOW);\n pinMode(echoPin, INPUT);\n duration = pulseIn(echoPin, HIGH);\n inches = microsecondsToInches(duration);\n cm = microsecondsToCentimeters(duration);\n Serial.print(inches);\n Serial.print(\"in, \");\n Serial.print(cm);\n Serial.print(\"cm\");\n Serial.println();\n delay(100);\n}\n\nlong microsecondsToInches(long microseconds) {\n return microseconds / 74 / 2;\n}\n\nlong microsecondsToCentimeters(long microseconds) {\n return microseconds / 29 / 2;\n}" }, { "code": null, "e": 4942, "s": 4848, "text": "The Ultrasonic sensor has four terminals - +5V, Trigger, Echo, and GND connected as follows −" }, { "code": null, "e": 4992, "s": 4942, "text": "Connect the +5V pin to +5v on your Arduino board." }, { "code": null, "e": 5048, "s": 4992, "text": "Connect Trigger to digital pin 7 on your Arduino board." }, { "code": null, "e": 5101, "s": 5048, "text": "Connect Echo to digital pin 6 on your Arduino board." }, { "code": null, "e": 5134, "s": 5101, "text": "Connect GND with GND on Arduino." }, { "code": null, "e": 5242, "s": 5134, "text": "In our program, we have displayed the distance measured by the sensor in inches and cm via the serial port." } ]
Insert node into the middle of the linked list
24 Jun, 2022 Given a linked list containing n nodes. The problem is to insert a new node with data x in the middle of the list. If n is even, then insert the new node after the (n/2)th node, else insert the new node after the (n+1)/2th node. Examples: Input : list: 1->2->4->5 x = 3 Output : 1->2->3->4->5 Input : list: 5->10->4->32->16 x = 41 Output : 5->10->4->41->32->16 Method 1(Using the length of the linked list): Find the number of nodes or length of the linked list using one traversal. Let it be len. Calculate c = (len/2), if len is even, else c = (len+1)/2, if len is odd. Traverse again the first c nodes and insert the new node after the cth node. C++ Java Python3 C# Javascript // C++ implementation to insert node at the middle// of the linked list#include <bits/stdc++.h> using namespace std; // structure of a nodestruct Node { int data; Node* next;}; // function to create and return a nodeNode* getNode(int data){ // allocating space Node* newNode = (Node*)malloc(sizeof(Node)); // inserting the required data newNode->data = data; newNode->next = NULL; return newNode;} // function to insert node at the middle// of the linked listvoid insertAtMid(Node** head_ref, int x){ // if list is empty if (*head_ref == NULL) *head_ref = getNode(x); else { // get a new node Node* newNode = getNode(x); Node* ptr = *head_ref; int len = 0; // calculate length of the linked list //, i.e, the number of nodes while (ptr != NULL) { len++; ptr = ptr->next; } // 'count' the number of nodes after which // the new node is to be inserted int count = ((len % 2) == 0) ? (len / 2) : (len + 1) / 2; ptr = *head_ref; // 'ptr' points to the node after which // the new node is to be inserted while (count-- > 1) ptr = ptr->next; // insert the 'newNode' and adjust the // required links newNode->next = ptr->next; ptr->next = newNode; }} // function to display the linked listvoid display(Node* head){ while (head != NULL) { cout << head->data << " "; head = head->next; }} // Driver program to test aboveint main(){ // Creating the list 1->2->4->5 Node* head = NULL; head = getNode(1); head->next = getNode(2); head->next->next = getNode(4); head->next->next->next = getNode(5); cout << "Linked list before insertion: "; display(head); int x = 3; insertAtMid(&head, x); cout << "\nLinked list after insertion: "; display(head); return 0;} // Java implementation to insert node// at the middle of the linked listimport java.util.*;import java.lang.*;import java.io.*; class LinkedList{ static Node head; // head of list /* Node Class */ static class Node { int data; Node next; // Constructor to create a new node Node(int d) { data = d; next = null; } } // function to insert node at the // middle of the linked list static void insertAtMid(int x) { // if list is empty if (head == null) head = new Node(x); else { // get a new node Node newNode = new Node(x); Node ptr = head; int len = 0; // calculate length of the linked list //, i.e, the number of nodes while (ptr != null) { len++; ptr = ptr.next; } // 'count' the number of nodes after which // the new node is to be inserted int count = ((len % 2) == 0) ? (len / 2) : (len + 1) / 2; ptr = head; // 'ptr' points to the node after which // the new node is to be inserted while (count-- > 1) ptr = ptr.next; // insert the 'newNode' and adjust // the required links newNode.next = ptr.next; ptr.next = newNode; } } // function to display the linked list static void display() { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } } // Driver program to test above public static void main (String[] args) { // Creating the list 1.2.4.5 head = null; head = new Node(1); head.next = new Node(2); head.next.next = new Node(4); head.next.next.next = new Node(5); System.out.println("Linked list before "+ "insertion: "); display(); int x = 3; insertAtMid(x); System.out.println("\nLinked list after"+ " insertion: "); display(); } } // This article is contributed by Chhavi # Python3 implementation to insert node# at the middle of a linked list # Node classclass Node: # constructor to create a new node def __init__(self, data): self.data = data self.next = None # function to insert node at the# middle of linked list given the headdef insertAtMid(head, x): if(head == None): #if the list is empty head = Node(x) else: # create a new node for the value # to be inserted newNode = Node(x) ptr = head length = 0 # calculate the length of the linked # list while(ptr != None): ptr = ptr.next length += 1 # 'count' the number of node after which # the new node has to be inserted if(length % 2 == 0): count = length / 2 else: (length + 1) / 2 ptr = head # move ptr to the node after which # the new node has to inserted while(count > 1): count -= 1 ptr = ptr.next # insert the 'newNode' and adjust # links accordingly newNode.next = ptr.next ptr.next = newNode # function to display the linked listdef display(head): temp = head while(temp != None): print(str(temp.data), end = " ") temp = temp.next # Driver Code # Creating the linked list 1.2.4.5head = Node(1)head.next = Node(2)head.next.next = Node(4)head.next.next.next = Node(5) print("Linked list before insertion: ", end = "")display(head) # inserting 3 in the middle of the linked list.x = 3insertAtMid(head, x) print("\nLinked list after insertion: " , end = "")display(head) # This code is contributed by Pranav Devarakonda // C# implementation to insert node // at the middle of the linked list using System; public class LinkedList { static Node head; // head of list /* Node Class */ public class Node { public int data; public Node next; // Constructor to create a new node public Node(int d) { data = d; next = null; } } // function to insert node at the // middle of the linked list static void insertAtMid(int x) { // if list is empty if (head == null) head = new Node(x); else { // get a new node Node newNode = new Node(x); Node ptr = head; int len = 0; // calculate length of the linked list //, i.e, the number of nodes while (ptr != null) { len++; ptr = ptr.next; } // 'count' the number of nodes after which // the new node is to be inserted int count = ((len % 2) == 0) ? (len / 2) : (len + 1) / 2; ptr = head; // 'ptr' points to the node after which // the new node is to be inserted while (count-- > 1) ptr = ptr.next; // insert the 'newNode' and adjust // the required links newNode.next = ptr.next; ptr.next = newNode; } } // function to display the linked list static void display() { Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } } // Driver code public static void Main () { // Creating the list 1.2.4.5 head = null; head = new Node(1); head.next = new Node(2); head.next.next = new Node(4); head.next.next.next = new Node(5); Console.WriteLine("Linked list before "+ "insertion: "); display(); int x = 3; insertAtMid(x); Console.WriteLine("\nLinked list after"+ " insertion: "); display(); } } /* This code contributed by PrinciRaj1992 */ <script> // Javascript implementation to insert node// at the middle of the linked list var head; // head of list /* Node Class */ class Node { // Constructor to create a new node constructor(d) { this.data = d; this.next = null; } } // function to insert node at the // middle of the linked list function insertAtMid(x) { // if list is empty if (head == null) head = new Node(x); else { // get a new node var newNode = new Node(x); var ptr = head; var len = 0; // calculate length of the linked list // , i.e, the number of nodes while (ptr != null) { len++; ptr = ptr.next; } // 'count' the number of nodes after which // the new node is to be inserted var count = ((len % 2) == 0) ? (len / 2) : (len + 1) / 2; ptr = head; // 'ptr' points to the node after which // the new node is to be inserted while (count-- > 1) ptr = ptr.next; // insert the 'newNode' and adjust // the required links newNode.next = ptr.next; ptr.next = newNode; } } // function to display the linked list function display() { var temp = head; while (temp != null) { document.write(temp.data + " "); temp = temp.next; } } // Driver program to test above // Creating the list 1.2.4.5 head = new Node(1); head.next = new Node(2); head.next.next = new Node(4); head.next.next.next = new Node(5); document.write("Linked list before " + "insertion: "); display(); var x = 3; insertAtMid(x); document.write("<br/>Linked list after" + " insertion: "); display(); // This code contributed by Rajput-Ji </script> Output: Linked list before insertion: 1 2 4 5 Linked list after insertion: 1 2 3 4 5 Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of nodes in the linked list. Auxiliary Space: O(1), as we are not using any extra space. Method 2(Using two pointers): Based on the tortoise and hare algorithm which uses two pointers, one known as slow and the other known as fast. This algorithm helps in finding the middle node of the linked list. It is explained in the front and black split procedure of this post. Now, you can insert the new node after the middle node obtained from the above process. This approach requires only a single traversal of the list. C++ Java Python3 C# Javascript // C++ implementation to insert node at the middle// of the linked list#include <bits/stdc++.h> using namespace std; // structure of a nodestruct Node { int data; Node* next;}; // function to create and return a nodeNode* getNode(int data){ // allocating space Node* newNode = (Node*)malloc(sizeof(Node)); // inserting the required data newNode->data = data; newNode->next = NULL; return newNode;} // function to insert node at the middle// of the linked listvoid insertAtMid(Node** head_ref, int x){ // if list is empty if (*head_ref == NULL) *head_ref = getNode(x); else { // get a new node Node* newNode = getNode(x); // assign values to the slow and fast // pointers Node* slow = *head_ref; Node* fast = (*head_ref)->next; while (fast && fast->next) { // move slow pointer to next node slow = slow->next; // move fast pointer two nodes at a time fast = fast->next->next; } // insert the 'newNode' and adjust the // required links newNode->next = slow->next; slow->next = newNode; }} // function to display the linked listvoid display(Node* head){ while (head != NULL) { cout << head->data << " "; head = head->next; }} // Driver program to test aboveint main(){ // Creating the list 1->2->4->5 Node* head = NULL; head = getNode(1); head->next = getNode(2); head->next->next = getNode(4); head->next->next->next = getNode(5); cout << "Linked list before insertion: "; display(head); int x = 3; insertAtMid(&head, x); cout << "\nLinked list after insertion: "; display(head); return 0;} // Java implementation to insert node // at the middle of the linked listimport java.util.*;import java.lang.*;import java.io.*; class LinkedList{ static Node head; // head of list /* Node Class */ static class Node { int data; Node next; // Constructor to create a new node Node(int d) { data = d; next = null; } } // function to insert node at the // middle of the linked list static void insertAtMid(int x) { // if list is empty if (head == null) head = new Node(x); else { // get a new node Node newNode = new Node(x); // assign values to the slow // and fast pointers Node slow = head; Node fast = head.next; while (fast != null && fast.next != null) { // move slow pointer to next node slow = slow.next; // move fast pointer two nodes // at a time fast = fast.next.next; } // insert the 'newNode' and adjust // the required links newNode.next = slow.next; slow.next = newNode; } } // function to display the linked list static void display() { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } } // Driver program to test above public static void main (String[] args) { // Creating the list 1.2.4.5 head = null; head = new Node(1); head.next = new Node(2); head.next.next = new Node(4); head.next.next.next = new Node(5); System.out.println("Linked list before"+ " insertion: "); display(); int x = 3; insertAtMid(x); System.out.println("\nLinked list after"+ " insertion: "); display(); } } // This article is contributed by Chhavi # Python implementation to insert node # at the middle of the linked list # Node Classclass Node : def __init__(self, d): self.data = d self.next = None class LinkedList: # function to insert node at the # middle of the linked list def __init__(self): self.head = None # Function to insert a new node # at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def insertAtMid(self, x): # if list is empty if (self.head == None): self.head = Node(x) else: # get a new node newNode = Node(x) # assign values to the slow # and fast pointers slow = self.head fast = self.head.next while (fast != None and fast.next != None): # move slow pointer to next node slow = slow.next # move fast pointer two nodes # at a time fast = fast.next.next # insert the 'newNode' and # adjust the required links newNode.next = slow.next slow.next = newNode # function to display the linked list def display(self): temp = self.head while (temp != None): print(temp.data, end = " "), temp = temp.next # Driver Code # Creating the list 1.2.4.5 ll = LinkedList()ll.push(5)ll.push(4)ll.push(2)ll.push(1)print("Linked list before insertion: "),ll.display() x = 3ll.insertAtMid(x) print("\nLinked list after insertion: "),ll.display() # This code is contributed by prerna saini // C# implementation to insert node // at the middle of the linked listusing System; public class LinkedList{ static Node head; // head of list /* Node Class */ class Node { public int data; public Node next; // Constructor to create a new node public Node(int d) { data = d; next = null; } } // function to insert node at the // middle of the linked list static void insertAtMid(int x) { // if list is empty if (head == null) head = new Node(x); else { // get a new node Node newNode = new Node(x); // assign values to the slow // and fast pointers Node slow = head; Node fast = head.next; while (fast != null && fast.next != null) { // move slow pointer to next node slow = slow.next; // move fast pointer two nodes // at a time fast = fast.next.next; } // insert the 'newNode' and adjust // the required links newNode.next = slow.next; slow.next = newNode; } } // function to display the linked list static void display() { Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } } // Driver code public static void Main (String[] args) { // Creating the list 1.2.4.5 head = null; head = new Node(1); head.next = new Node(2); head.next.next = new Node(4); head.next.next.next = new Node(5); Console.WriteLine("Linked list before"+ " insertion: "); display(); int x = 3; insertAtMid(x); Console.WriteLine("\nLinked list after"+ " insertion: "); display(); } } // This code is contributed by Rajput-Ji <script> // Javascript implementation to insert node // at the middle of the linked list var head; // head of list /* Node Class */ class Node { // Constructor to create a new nodeconstructor(val) { this.data = val; this.next = null;}} // function to insert node at the // middle of the linked list function insertAtMid(x) { // if list is empty if (head == null) head = new Node(x); else { // get a new node var newNode = new Node(x); // assign values to the slow // and fast pointers var slow = head; var fast = head.next; while (fast != null && fast.next != null) { // move slow pointer to next node slow = slow.next; // move fast pointer two nodes // at a time fast = fast.next.next; } // insert the 'newNode' and adjust // the required links newNode.next = slow.next; slow.next = newNode; } } // function to display the linked list function display() { var temp = head; while (temp != null) { document.write(temp.data + " "); temp = temp.next; } } // Driver program to test above // Creating the list 1.2.4.5 head = null; head = new Node(1); head.next = new Node(2); head.next.next = new Node(4); head.next.next.next = new Node(5); document.write( "Linked list before" + " insertion: " ); display(); var x = 3; insertAtMid(x); document.write( "<br/>Linked list after" + " insertion: " ); display(); // This code is contributed by todaysgaurav </script> Output: Linked list before insertion: 1 2 4 5 Linked list after insertion: 1 2 3 4 5 Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of nodes in the linked list. Auxiliary Space: O(1), as we are not using any extra space. This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. prerna saini Rajput-Ji princiraj1992 Pranav Devarakonda viveknathani todaysgaurav arorakashish0911 rohan07 Tortoise-Hare-Approach Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. LinkedList in Java Introduction to Data Structures Doubly Linked List | Set 1 (Introduction and Insertion) Merge two sorted linked lists What is Data Structure: Types, Classifications and Applications Linked List vs Array Merge Sort for Linked Lists Implementing a Linked List in Java using Class Add two numbers represented by linked lists | Set 1 Function to check if a singly linked list is palindrome
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Jun, 2022" }, { "code": null, "e": 282, "s": 53, "text": "Given a linked list containing n nodes. The problem is to insert a new node with data x in the middle of the list. If n is even, then insert the new node after the (n/2)th node, else insert the new node after the (n+1)/2th node." }, { "code": null, "e": 293, "s": 282, "text": "Examples: " }, { "code": null, "e": 432, "s": 293, "text": "Input : list: 1->2->4->5\n x = 3\nOutput : 1->2->3->4->5\n\nInput : list: 5->10->4->32->16\n x = 41\nOutput : 5->10->4->41->32->16" }, { "code": null, "e": 722, "s": 432, "text": "Method 1(Using the length of the linked list): Find the number of nodes or length of the linked list using one traversal. Let it be len. Calculate c = (len/2), if len is even, else c = (len+1)/2, if len is odd. Traverse again the first c nodes and insert the new node after the cth node. " }, { "code": null, "e": 726, "s": 722, "text": "C++" }, { "code": null, "e": 731, "s": 726, "text": "Java" }, { "code": null, "e": 739, "s": 731, "text": "Python3" }, { "code": null, "e": 742, "s": 739, "text": "C#" }, { "code": null, "e": 753, "s": 742, "text": "Javascript" }, { "code": "// C++ implementation to insert node at the middle// of the linked list#include <bits/stdc++.h> using namespace std; // structure of a nodestruct Node { int data; Node* next;}; // function to create and return a nodeNode* getNode(int data){ // allocating space Node* newNode = (Node*)malloc(sizeof(Node)); // inserting the required data newNode->data = data; newNode->next = NULL; return newNode;} // function to insert node at the middle// of the linked listvoid insertAtMid(Node** head_ref, int x){ // if list is empty if (*head_ref == NULL) *head_ref = getNode(x); else { // get a new node Node* newNode = getNode(x); Node* ptr = *head_ref; int len = 0; // calculate length of the linked list //, i.e, the number of nodes while (ptr != NULL) { len++; ptr = ptr->next; } // 'count' the number of nodes after which // the new node is to be inserted int count = ((len % 2) == 0) ? (len / 2) : (len + 1) / 2; ptr = *head_ref; // 'ptr' points to the node after which // the new node is to be inserted while (count-- > 1) ptr = ptr->next; // insert the 'newNode' and adjust the // required links newNode->next = ptr->next; ptr->next = newNode; }} // function to display the linked listvoid display(Node* head){ while (head != NULL) { cout << head->data << \" \"; head = head->next; }} // Driver program to test aboveint main(){ // Creating the list 1->2->4->5 Node* head = NULL; head = getNode(1); head->next = getNode(2); head->next->next = getNode(4); head->next->next->next = getNode(5); cout << \"Linked list before insertion: \"; display(head); int x = 3; insertAtMid(&head, x); cout << \"\\nLinked list after insertion: \"; display(head); return 0;}", "e": 2732, "s": 753, "text": null }, { "code": "// Java implementation to insert node// at the middle of the linked listimport java.util.*;import java.lang.*;import java.io.*; class LinkedList{ static Node head; // head of list /* Node Class */ static class Node { int data; Node next; // Constructor to create a new node Node(int d) { data = d; next = null; } } // function to insert node at the // middle of the linked list static void insertAtMid(int x) { // if list is empty if (head == null) head = new Node(x); else { // get a new node Node newNode = new Node(x); Node ptr = head; int len = 0; // calculate length of the linked list //, i.e, the number of nodes while (ptr != null) { len++; ptr = ptr.next; } // 'count' the number of nodes after which // the new node is to be inserted int count = ((len % 2) == 0) ? (len / 2) : (len + 1) / 2; ptr = head; // 'ptr' points to the node after which // the new node is to be inserted while (count-- > 1) ptr = ptr.next; // insert the 'newNode' and adjust // the required links newNode.next = ptr.next; ptr.next = newNode; } } // function to display the linked list static void display() { Node temp = head; while (temp != null) { System.out.print(temp.data + \" \"); temp = temp.next; } } // Driver program to test above public static void main (String[] args) { // Creating the list 1.2.4.5 head = null; head = new Node(1); head.next = new Node(2); head.next.next = new Node(4); head.next.next.next = new Node(5); System.out.println(\"Linked list before \"+ \"insertion: \"); display(); int x = 3; insertAtMid(x); System.out.println(\"\\nLinked list after\"+ \" insertion: \"); display(); } } // This article is contributed by Chhavi", "e": 5036, "s": 2732, "text": null }, { "code": "# Python3 implementation to insert node# at the middle of a linked list # Node classclass Node: # constructor to create a new node def __init__(self, data): self.data = data self.next = None # function to insert node at the# middle of linked list given the headdef insertAtMid(head, x): if(head == None): #if the list is empty head = Node(x) else: # create a new node for the value # to be inserted newNode = Node(x) ptr = head length = 0 # calculate the length of the linked # list while(ptr != None): ptr = ptr.next length += 1 # 'count' the number of node after which # the new node has to be inserted if(length % 2 == 0): count = length / 2 else: (length + 1) / 2 ptr = head # move ptr to the node after which # the new node has to inserted while(count > 1): count -= 1 ptr = ptr.next # insert the 'newNode' and adjust # links accordingly newNode.next = ptr.next ptr.next = newNode # function to display the linked listdef display(head): temp = head while(temp != None): print(str(temp.data), end = \" \") temp = temp.next # Driver Code # Creating the linked list 1.2.4.5head = Node(1)head.next = Node(2)head.next.next = Node(4)head.next.next.next = Node(5) print(\"Linked list before insertion: \", end = \"\")display(head) # inserting 3 in the middle of the linked list.x = 3insertAtMid(head, x) print(\"\\nLinked list after insertion: \" , end = \"\")display(head) # This code is contributed by Pranav Devarakonda", "e": 6749, "s": 5036, "text": null }, { "code": "// C# implementation to insert node // at the middle of the linked list using System; public class LinkedList { static Node head; // head of list /* Node Class */ public class Node { public int data; public Node next; // Constructor to create a new node public Node(int d) { data = d; next = null; } } // function to insert node at the // middle of the linked list static void insertAtMid(int x) { // if list is empty if (head == null) head = new Node(x); else { // get a new node Node newNode = new Node(x); Node ptr = head; int len = 0; // calculate length of the linked list //, i.e, the number of nodes while (ptr != null) { len++; ptr = ptr.next; } // 'count' the number of nodes after which // the new node is to be inserted int count = ((len % 2) == 0) ? (len / 2) : (len + 1) / 2; ptr = head; // 'ptr' points to the node after which // the new node is to be inserted while (count-- > 1) ptr = ptr.next; // insert the 'newNode' and adjust // the required links newNode.next = ptr.next; ptr.next = newNode; } } // function to display the linked list static void display() { Node temp = head; while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; } } // Driver code public static void Main () { // Creating the list 1.2.4.5 head = null; head = new Node(1); head.next = new Node(2); head.next.next = new Node(4); head.next.next.next = new Node(5); Console.WriteLine(\"Linked list before \"+ \"insertion: \"); display(); int x = 3; insertAtMid(x); Console.WriteLine(\"\\nLinked list after\"+ \" insertion: \"); display(); } } /* This code contributed by PrinciRaj1992 */", "e": 9100, "s": 6749, "text": null }, { "code": "<script> // Javascript implementation to insert node// at the middle of the linked list var head; // head of list /* Node Class */ class Node { // Constructor to create a new node constructor(d) { this.data = d; this.next = null; } } // function to insert node at the // middle of the linked list function insertAtMid(x) { // if list is empty if (head == null) head = new Node(x); else { // get a new node var newNode = new Node(x); var ptr = head; var len = 0; // calculate length of the linked list // , i.e, the number of nodes while (ptr != null) { len++; ptr = ptr.next; } // 'count' the number of nodes after which // the new node is to be inserted var count = ((len % 2) == 0) ? (len / 2) : (len + 1) / 2; ptr = head; // 'ptr' points to the node after which // the new node is to be inserted while (count-- > 1) ptr = ptr.next; // insert the 'newNode' and adjust // the required links newNode.next = ptr.next; ptr.next = newNode; } } // function to display the linked list function display() { var temp = head; while (temp != null) { document.write(temp.data + \" \"); temp = temp.next; } } // Driver program to test above // Creating the list 1.2.4.5 head = new Node(1); head.next = new Node(2); head.next.next = new Node(4); head.next.next.next = new Node(5); document.write(\"Linked list before \" + \"insertion: \"); display(); var x = 3; insertAtMid(x); document.write(\"<br/>Linked list after\" + \" insertion: \"); display(); // This code contributed by Rajput-Ji </script>", "e": 11147, "s": 9100, "text": null }, { "code": null, "e": 11156, "s": 11147, "text": "Output: " }, { "code": null, "e": 11233, "s": 11156, "text": "Linked list before insertion: 1 2 4 5\nLinked list after insertion: 1 2 3 4 5" }, { "code": null, "e": 11351, "s": 11233, "text": "Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of nodes in the linked list." }, { "code": null, "e": 11411, "s": 11351, "text": "Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 11840, "s": 11411, "text": "Method 2(Using two pointers): Based on the tortoise and hare algorithm which uses two pointers, one known as slow and the other known as fast. This algorithm helps in finding the middle node of the linked list. It is explained in the front and black split procedure of this post. Now, you can insert the new node after the middle node obtained from the above process. This approach requires only a single traversal of the list. " }, { "code": null, "e": 11844, "s": 11840, "text": "C++" }, { "code": null, "e": 11849, "s": 11844, "text": "Java" }, { "code": null, "e": 11857, "s": 11849, "text": "Python3" }, { "code": null, "e": 11860, "s": 11857, "text": "C#" }, { "code": null, "e": 11871, "s": 11860, "text": "Javascript" }, { "code": "// C++ implementation to insert node at the middle// of the linked list#include <bits/stdc++.h> using namespace std; // structure of a nodestruct Node { int data; Node* next;}; // function to create and return a nodeNode* getNode(int data){ // allocating space Node* newNode = (Node*)malloc(sizeof(Node)); // inserting the required data newNode->data = data; newNode->next = NULL; return newNode;} // function to insert node at the middle// of the linked listvoid insertAtMid(Node** head_ref, int x){ // if list is empty if (*head_ref == NULL) *head_ref = getNode(x); else { // get a new node Node* newNode = getNode(x); // assign values to the slow and fast // pointers Node* slow = *head_ref; Node* fast = (*head_ref)->next; while (fast && fast->next) { // move slow pointer to next node slow = slow->next; // move fast pointer two nodes at a time fast = fast->next->next; } // insert the 'newNode' and adjust the // required links newNode->next = slow->next; slow->next = newNode; }} // function to display the linked listvoid display(Node* head){ while (head != NULL) { cout << head->data << \" \"; head = head->next; }} // Driver program to test aboveint main(){ // Creating the list 1->2->4->5 Node* head = NULL; head = getNode(1); head->next = getNode(2); head->next->next = getNode(4); head->next->next->next = getNode(5); cout << \"Linked list before insertion: \"; display(head); int x = 3; insertAtMid(&head, x); cout << \"\\nLinked list after insertion: \"; display(head); return 0;}", "e": 13619, "s": 11871, "text": null }, { "code": "// Java implementation to insert node // at the middle of the linked listimport java.util.*;import java.lang.*;import java.io.*; class LinkedList{ static Node head; // head of list /* Node Class */ static class Node { int data; Node next; // Constructor to create a new node Node(int d) { data = d; next = null; } } // function to insert node at the // middle of the linked list static void insertAtMid(int x) { // if list is empty if (head == null) head = new Node(x); else { // get a new node Node newNode = new Node(x); // assign values to the slow // and fast pointers Node slow = head; Node fast = head.next; while (fast != null && fast.next != null) { // move slow pointer to next node slow = slow.next; // move fast pointer two nodes // at a time fast = fast.next.next; } // insert the 'newNode' and adjust // the required links newNode.next = slow.next; slow.next = newNode; } } // function to display the linked list static void display() { Node temp = head; while (temp != null) { System.out.print(temp.data + \" \"); temp = temp.next; } } // Driver program to test above public static void main (String[] args) { // Creating the list 1.2.4.5 head = null; head = new Node(1); head.next = new Node(2); head.next.next = new Node(4); head.next.next.next = new Node(5); System.out.println(\"Linked list before\"+ \" insertion: \"); display(); int x = 3; insertAtMid(x); System.out.println(\"\\nLinked list after\"+ \" insertion: \"); display(); } } // This article is contributed by Chhavi", "e": 15737, "s": 13619, "text": null }, { "code": "# Python implementation to insert node # at the middle of the linked list # Node Classclass Node : def __init__(self, d): self.data = d self.next = None class LinkedList: # function to insert node at the # middle of the linked list def __init__(self): self.head = None # Function to insert a new node # at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def insertAtMid(self, x): # if list is empty if (self.head == None): self.head = Node(x) else: # get a new node newNode = Node(x) # assign values to the slow # and fast pointers slow = self.head fast = self.head.next while (fast != None and fast.next != None): # move slow pointer to next node slow = slow.next # move fast pointer two nodes # at a time fast = fast.next.next # insert the 'newNode' and # adjust the required links newNode.next = slow.next slow.next = newNode # function to display the linked list def display(self): temp = self.head while (temp != None): print(temp.data, end = \" \"), temp = temp.next # Driver Code # Creating the list 1.2.4.5 ll = LinkedList()ll.push(5)ll.push(4)ll.push(2)ll.push(1)print(\"Linked list before insertion: \"),ll.display() x = 3ll.insertAtMid(x) print(\"\\nLinked list after insertion: \"),ll.display() # This code is contributed by prerna saini", "e": 17514, "s": 15737, "text": null }, { "code": "// C# implementation to insert node // at the middle of the linked listusing System; public class LinkedList{ static Node head; // head of list /* Node Class */ class Node { public int data; public Node next; // Constructor to create a new node public Node(int d) { data = d; next = null; } } // function to insert node at the // middle of the linked list static void insertAtMid(int x) { // if list is empty if (head == null) head = new Node(x); else { // get a new node Node newNode = new Node(x); // assign values to the slow // and fast pointers Node slow = head; Node fast = head.next; while (fast != null && fast.next != null) { // move slow pointer to next node slow = slow.next; // move fast pointer two nodes // at a time fast = fast.next.next; } // insert the 'newNode' and adjust // the required links newNode.next = slow.next; slow.next = newNode; } } // function to display the linked list static void display() { Node temp = head; while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; } } // Driver code public static void Main (String[] args) { // Creating the list 1.2.4.5 head = null; head = new Node(1); head.next = new Node(2); head.next.next = new Node(4); head.next.next.next = new Node(5); Console.WriteLine(\"Linked list before\"+ \" insertion: \"); display(); int x = 3; insertAtMid(x); Console.WriteLine(\"\\nLinked list after\"+ \" insertion: \"); display(); } } // This code is contributed by Rajput-Ji", "e": 19598, "s": 17514, "text": null }, { "code": "<script> // Javascript implementation to insert node // at the middle of the linked list var head; // head of list /* Node Class */ class Node { // Constructor to create a new nodeconstructor(val) { this.data = val; this.next = null;}} // function to insert node at the // middle of the linked list function insertAtMid(x) { // if list is empty if (head == null) head = new Node(x); else { // get a new node var newNode = new Node(x); // assign values to the slow // and fast pointers var slow = head; var fast = head.next; while (fast != null && fast.next != null) { // move slow pointer to next node slow = slow.next; // move fast pointer two nodes // at a time fast = fast.next.next; } // insert the 'newNode' and adjust // the required links newNode.next = slow.next; slow.next = newNode; } } // function to display the linked list function display() { var temp = head; while (temp != null) { document.write(temp.data + \" \"); temp = temp.next; } } // Driver program to test above // Creating the list 1.2.4.5 head = null; head = new Node(1); head.next = new Node(2); head.next.next = new Node(4); head.next.next.next = new Node(5); document.write( \"Linked list before\" + \" insertion: \" ); display(); var x = 3; insertAtMid(x); document.write( \"<br/>Linked list after\" + \" insertion: \" ); display(); // This code is contributed by todaysgaurav </script>", "e": 21416, "s": 19598, "text": null }, { "code": null, "e": 21425, "s": 21416, "text": "Output: " }, { "code": null, "e": 21502, "s": 21425, "text": "Linked list before insertion: 1 2 4 5\nLinked list after insertion: 1 2 3 4 5" }, { "code": null, "e": 21620, "s": 21502, "text": "Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of nodes in the linked list." }, { "code": null, "e": 21680, "s": 21620, "text": "Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 22104, "s": 21680, "text": "This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above." }, { "code": null, "e": 22117, "s": 22104, "text": "prerna saini" }, { "code": null, "e": 22127, "s": 22117, "text": "Rajput-Ji" }, { "code": null, "e": 22141, "s": 22127, "text": "princiraj1992" }, { "code": null, "e": 22160, "s": 22141, "text": "Pranav Devarakonda" }, { "code": null, "e": 22173, "s": 22160, "text": "viveknathani" }, { "code": null, "e": 22186, "s": 22173, "text": "todaysgaurav" }, { "code": null, "e": 22203, "s": 22186, "text": "arorakashish0911" }, { "code": null, "e": 22211, "s": 22203, "text": "rohan07" }, { "code": null, "e": 22234, "s": 22211, "text": "Tortoise-Hare-Approach" }, { "code": null, "e": 22246, "s": 22234, "text": "Linked List" }, { "code": null, "e": 22258, "s": 22246, "text": "Linked List" }, { "code": null, "e": 22356, "s": 22258, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 22375, "s": 22356, "text": "LinkedList in Java" }, { "code": null, "e": 22407, "s": 22375, "text": "Introduction to Data Structures" }, { "code": null, "e": 22463, "s": 22407, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 22493, "s": 22463, "text": "Merge two sorted linked lists" }, { "code": null, "e": 22557, "s": 22493, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 22578, "s": 22557, "text": "Linked List vs Array" }, { "code": null, "e": 22606, "s": 22578, "text": "Merge Sort for Linked Lists" }, { "code": null, "e": 22653, "s": 22606, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 22705, "s": 22653, "text": "Add two numbers represented by linked lists | Set 1" } ]
Select Columns with Specific Data Types in Pandas Dataframe
02 Dec, 2020 In this article, we will see how to select columns with specific data types from a dataframe. This operation can be performed using the DataFrame.select_dtypes() method in pandas module. Syntax: DataFrame.select_dtypes(include=None, exclude=None)Parameters : include, exclude : A selection of dtypes or strings to be included/excluded. At least one of these parameters must be supplied.Return : The subset of the frame including the dtypes in include and excluding the dtypes in exclude. Step-by-step Approach: First, import modules then load the dataset. Python3 # import required moduleimport pandas as pd # assign datasetdf = pd.read_csv("train.csv") Then we will find types of data present in our dataset using dataframe.info() method. Python3 # display description# of the datasetdf.info() Output: Now, we will use DataFrame.select_dtypes() to select a specific datatype. Python3 # store columns with specific data typeinteger_columns = df.select_dtypes(include=['int64']).columnsfloat_columns = df.select_dtypes(include=['float64']).columnsobject_columns = df.select_dtypes(include=['object']).columns Finally, display the column having a particular data type. Python3 # display columnsprint('\nint64 columns:\n', integer_columns)print('\nfloat64 columns:\n', float_columns)print('\nobject columns:\n', object_columns) Output: Below is the complete program based on the above approach: Python3 # import required moduleimport pandas as pd # assign datasetdf = pd.read_csv("train.csv") # store columns with specific data typeinteger_columns = df.select_dtypes(include=['int64']).columnsfloat_columns = df.select_dtypes(include=['float64']).columnsobject_columns = df.select_dtypes(include=['object']).columns # display columnsprint('\nint64 columns:\n',integer_columns)print('\nfloat64 columns:\n',float_columns)print('\nobject columns:\n',object_columns) Output: Example: Here we are going to extract columns of the below dataset: Python3 # import required moduleimport pandas as pdfrom vega_datasets import data # assign datasetdf = data.seattle_weather() # display datasetdf.sample(10) Output: Now, we are going to display all the columns having float64 as the data type. Python3 # import required moduleimport pandas as pdfrom vega_datasets import data # assign datasetdf = data.seattle_weather() # display description# of datasetdf.info() # store columns with specific data typecolumns = df.select_dtypes(include=['float64']).columns # display columnsprint('\nColumns:\n', columns) Output: Python pandas-dataFrame Python Pandas-exercise 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 ? Python Classes and Objects Python | os.path.join() method Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Dec, 2020" }, { "code": null, "e": 215, "s": 28, "text": "In this article, we will see how to select columns with specific data types from a dataframe. This operation can be performed using the DataFrame.select_dtypes() method in pandas module." }, { "code": null, "e": 516, "s": 215, "text": "Syntax: DataFrame.select_dtypes(include=None, exclude=None)Parameters : include, exclude : A selection of dtypes or strings to be included/excluded. At least one of these parameters must be supplied.Return : The subset of the frame including the dtypes in include and excluding the dtypes in exclude." }, { "code": null, "e": 539, "s": 516, "text": "Step-by-step Approach:" }, { "code": null, "e": 584, "s": 539, "text": "First, import modules then load the dataset." }, { "code": null, "e": 592, "s": 584, "text": "Python3" }, { "code": "# import required moduleimport pandas as pd # assign datasetdf = pd.read_csv(\"train.csv\")", "e": 683, "s": 592, "text": null }, { "code": null, "e": 769, "s": 683, "text": "Then we will find types of data present in our dataset using dataframe.info() method." }, { "code": null, "e": 777, "s": 769, "text": "Python3" }, { "code": "# display description# of the datasetdf.info()", "e": 824, "s": 777, "text": null }, { "code": null, "e": 832, "s": 824, "text": "Output:" }, { "code": null, "e": 906, "s": 832, "text": "Now, we will use DataFrame.select_dtypes() to select a specific datatype." }, { "code": null, "e": 914, "s": 906, "text": "Python3" }, { "code": "# store columns with specific data typeinteger_columns = df.select_dtypes(include=['int64']).columnsfloat_columns = df.select_dtypes(include=['float64']).columnsobject_columns = df.select_dtypes(include=['object']).columns", "e": 1137, "s": 914, "text": null }, { "code": null, "e": 1196, "s": 1137, "text": "Finally, display the column having a particular data type." }, { "code": null, "e": 1204, "s": 1196, "text": "Python3" }, { "code": "# display columnsprint('\\nint64 columns:\\n', integer_columns)print('\\nfloat64 columns:\\n', float_columns)print('\\nobject columns:\\n', object_columns)", "e": 1354, "s": 1204, "text": null }, { "code": null, "e": 1362, "s": 1354, "text": "Output:" }, { "code": null, "e": 1421, "s": 1362, "text": "Below is the complete program based on the above approach:" }, { "code": null, "e": 1429, "s": 1421, "text": "Python3" }, { "code": "# import required moduleimport pandas as pd # assign datasetdf = pd.read_csv(\"train.csv\") # store columns with specific data typeinteger_columns = df.select_dtypes(include=['int64']).columnsfloat_columns = df.select_dtypes(include=['float64']).columnsobject_columns = df.select_dtypes(include=['object']).columns # display columnsprint('\\nint64 columns:\\n',integer_columns)print('\\nfloat64 columns:\\n',float_columns)print('\\nobject columns:\\n',object_columns)", "e": 1892, "s": 1429, "text": null }, { "code": null, "e": 1900, "s": 1892, "text": "Output:" }, { "code": null, "e": 1909, "s": 1900, "text": "Example:" }, { "code": null, "e": 1968, "s": 1909, "text": "Here we are going to extract columns of the below dataset:" }, { "code": null, "e": 1976, "s": 1968, "text": "Python3" }, { "code": "# import required moduleimport pandas as pdfrom vega_datasets import data # assign datasetdf = data.seattle_weather() # display datasetdf.sample(10)", "e": 2127, "s": 1976, "text": null }, { "code": null, "e": 2135, "s": 2127, "text": "Output:" }, { "code": null, "e": 2213, "s": 2135, "text": "Now, we are going to display all the columns having float64 as the data type." }, { "code": null, "e": 2221, "s": 2213, "text": "Python3" }, { "code": "# import required moduleimport pandas as pdfrom vega_datasets import data # assign datasetdf = data.seattle_weather() # display description# of datasetdf.info() # store columns with specific data typecolumns = df.select_dtypes(include=['float64']).columns # display columnsprint('\\nColumns:\\n', columns)", "e": 2529, "s": 2221, "text": null }, { "code": null, "e": 2537, "s": 2529, "text": "Output:" }, { "code": null, "e": 2561, "s": 2537, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2584, "s": 2561, "text": "Python Pandas-exercise" }, { "code": null, "e": 2598, "s": 2584, "text": "Python-pandas" }, { "code": null, "e": 2605, "s": 2598, "text": "Python" }, { "code": null, "e": 2703, "s": 2605, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2735, "s": 2703, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2762, "s": 2735, "text": "Python Classes and Objects" }, { "code": null, "e": 2793, "s": 2762, "text": "Python | os.path.join() method" }, { "code": null, "e": 2814, "s": 2793, "text": "Python OOPs Concepts" }, { "code": null, "e": 2870, "s": 2814, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2893, "s": 2870, "text": "Introduction To PYTHON" }, { "code": null, "e": 2935, "s": 2893, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2977, "s": 2935, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3016, "s": 2977, "text": "Python | datetime.timedelta() function" } ]
C# | Getting a subset of the elements from the source ArrayList
01 Feb, 2019 ArrayList.GetRange(Int32, Int32) Method is used to get an ArrayList which will represent a subset of the elements in the source ArrayList. Syntax: public virtual System.Collections.ArrayList GetRange (int index, int count); Parameters: index: It is of Int32 type and represents the zero-based ArrayList index at which the range starts.count: It is of Int32 type and represents the number of elements in the range. Return Value: This method returns an ArrayList which represents a subset of the elements in the source ArrayList. Exceptions: ArgumentOutOfRangeException: If the value of the index is less than zero, or if the value of count is less than zero. ArgumentException: If the value of an index and count does not denote a valid range of elements in the ArrayList. Below programs illustrate the above-discussed method: Example 1: // C# program to illustrate the// concept of GetRange() Methodusing System;using System.Collections; class GFG { // Main method public static void Main() { // Creates and initializes // a new ArrayList. ArrayList myarraylist = new ArrayList(); myarraylist.Add("Welcome"); myarraylist.Add("to"); myarraylist.Add("Geeks"); myarraylist.Add("for"); myarraylist.Add("Geeks"); myarraylist.Add("portal"); // Creates and initializes queue Queue mynewList = new Queue(); mynewList.Enqueue("This"); mynewList.Enqueue("is"); mynewList.Enqueue("C#"); mynewList.Enqueue("tutorial"); // Displays the values of six // elements starting at index 0. ArrayList newarraylist = myarraylist.GetRange(0, 6); Console.WriteLine("Elements are:"); Displaydata(newarraylist, '\n'); // Replaces the values of six elements // starting at index 1 with the values // in the queue. myarraylist.SetRange(2, mynewList); // Displays the values of six // elements starting at index 0. newarraylist = myarraylist.GetRange(0, 6); Console.WriteLine("\nNow elements are:"); Displaydata(newarraylist, '\n'); } public static void Displaydata(IEnumerable myvalueList, char mySeparator) { foreach(Object obj in myvalueList) Console.Write("{0}{1}", mySeparator, obj); Console.WriteLine(); }} Output: Elements are: Welcome to Geeks for Geeks portal Now elements are: Welcome to This is C# tutorial Example 2: // C# program to illustrate the// concept of GetRange() Methodusing System;using System.Collections; class GFG { // Main method public static void Main() { // Creates and initializes a new ArrayList. ArrayList myarraylist = new ArrayList(); myarraylist.Add("Welcome"); myarraylist.Add("to"); myarraylist.Add("Geeks"); myarraylist.Add("for"); myarraylist.Add("Geeks"); myarraylist.Add("portal"); // Creates and initializes queue Queue mynewList = new Queue(); mynewList.Enqueue("This"); mynewList.Enqueue("is"); mynewList.Enqueue("C#"); mynewList.Enqueue("tutorial"); // Displays the values of six elements ArrayList newarraylist = myarraylist.GetRange(-1, 6); Console.WriteLine("Elements are:"); Displaydata(newarraylist, '\n'); // Replaces the values of six elements // starting at index 1 with the // values in the queue. myarraylist.SetRange(2, mynewList); // Displays the values of six // elements starting at index 0. newarraylist = myarraylist.GetRange(0, 6); Console.WriteLine("Now elements are:"); Displaydata(newarraylist, '\n'); } public static void Displaydata(IEnumerable myvalueList, char mySeparator) { foreach(Object obj in myvalueList) Console.Write("{0}{1}", mySeparator, obj); Console.WriteLine(); }} Runtime Error: Unhandled Exception:System.ArgumentOutOfRangeException: Non-negative number required.Parameter name: index Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.getrange?view=netframework-4.7.2#System_Collections_ArrayList_GetRange_System_Int32_System_Int32_ CSharp-Collections-ArrayList CSharp-Collections-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Feb, 2019" }, { "code": null, "e": 167, "s": 28, "text": "ArrayList.GetRange(Int32, Int32) Method is used to get an ArrayList which will represent a subset of the elements in the source ArrayList." }, { "code": null, "e": 175, "s": 167, "text": "Syntax:" }, { "code": null, "e": 252, "s": 175, "text": "public virtual System.Collections.ArrayList GetRange (int index, int count);" }, { "code": null, "e": 264, "s": 252, "text": "Parameters:" }, { "code": null, "e": 442, "s": 264, "text": "index: It is of Int32 type and represents the zero-based ArrayList index at which the range starts.count: It is of Int32 type and represents the number of elements in the range." }, { "code": null, "e": 556, "s": 442, "text": "Return Value: This method returns an ArrayList which represents a subset of the elements in the source ArrayList." }, { "code": null, "e": 568, "s": 556, "text": "Exceptions:" }, { "code": null, "e": 686, "s": 568, "text": "ArgumentOutOfRangeException: If the value of the index is less than zero, or if the value of count is less than zero." }, { "code": null, "e": 800, "s": 686, "text": "ArgumentException: If the value of an index and count does not denote a valid range of elements in the ArrayList." }, { "code": null, "e": 854, "s": 800, "text": "Below programs illustrate the above-discussed method:" }, { "code": null, "e": 865, "s": 854, "text": "Example 1:" }, { "code": "// C# program to illustrate the// concept of GetRange() Methodusing System;using System.Collections; class GFG { // Main method public static void Main() { // Creates and initializes // a new ArrayList. ArrayList myarraylist = new ArrayList(); myarraylist.Add(\"Welcome\"); myarraylist.Add(\"to\"); myarraylist.Add(\"Geeks\"); myarraylist.Add(\"for\"); myarraylist.Add(\"Geeks\"); myarraylist.Add(\"portal\"); // Creates and initializes queue Queue mynewList = new Queue(); mynewList.Enqueue(\"This\"); mynewList.Enqueue(\"is\"); mynewList.Enqueue(\"C#\"); mynewList.Enqueue(\"tutorial\"); // Displays the values of six // elements starting at index 0. ArrayList newarraylist = myarraylist.GetRange(0, 6); Console.WriteLine(\"Elements are:\"); Displaydata(newarraylist, '\\n'); // Replaces the values of six elements // starting at index 1 with the values // in the queue. myarraylist.SetRange(2, mynewList); // Displays the values of six // elements starting at index 0. newarraylist = myarraylist.GetRange(0, 6); Console.WriteLine(\"\\nNow elements are:\"); Displaydata(newarraylist, '\\n'); } public static void Displaydata(IEnumerable myvalueList, char mySeparator) { foreach(Object obj in myvalueList) Console.Write(\"{0}{1}\", mySeparator, obj); Console.WriteLine(); }}", "e": 2420, "s": 865, "text": null }, { "code": null, "e": 2428, "s": 2420, "text": "Output:" }, { "code": null, "e": 2529, "s": 2428, "text": "Elements are:\n\nWelcome\nto\nGeeks\nfor\nGeeks\nportal\n\nNow elements are:\n\nWelcome\nto\nThis\nis\nC#\ntutorial\n" }, { "code": null, "e": 2540, "s": 2529, "text": "Example 2:" }, { "code": "// C# program to illustrate the// concept of GetRange() Methodusing System;using System.Collections; class GFG { // Main method public static void Main() { // Creates and initializes a new ArrayList. ArrayList myarraylist = new ArrayList(); myarraylist.Add(\"Welcome\"); myarraylist.Add(\"to\"); myarraylist.Add(\"Geeks\"); myarraylist.Add(\"for\"); myarraylist.Add(\"Geeks\"); myarraylist.Add(\"portal\"); // Creates and initializes queue Queue mynewList = new Queue(); mynewList.Enqueue(\"This\"); mynewList.Enqueue(\"is\"); mynewList.Enqueue(\"C#\"); mynewList.Enqueue(\"tutorial\"); // Displays the values of six elements ArrayList newarraylist = myarraylist.GetRange(-1, 6); Console.WriteLine(\"Elements are:\"); Displaydata(newarraylist, '\\n'); // Replaces the values of six elements // starting at index 1 with the // values in the queue. myarraylist.SetRange(2, mynewList); // Displays the values of six // elements starting at index 0. newarraylist = myarraylist.GetRange(0, 6); Console.WriteLine(\"Now elements are:\"); Displaydata(newarraylist, '\\n'); } public static void Displaydata(IEnumerable myvalueList, char mySeparator) { foreach(Object obj in myvalueList) Console.Write(\"{0}{1}\", mySeparator, obj); Console.WriteLine(); }}", "e": 4054, "s": 2540, "text": null }, { "code": null, "e": 4069, "s": 4054, "text": "Runtime Error:" }, { "code": null, "e": 4176, "s": 4069, "text": "Unhandled Exception:System.ArgumentOutOfRangeException: Non-negative number required.Parameter name: index" }, { "code": null, "e": 4187, "s": 4176, "text": "Reference:" }, { "code": null, "e": 4358, "s": 4187, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.getrange?view=netframework-4.7.2#System_Collections_ArrayList_GetRange_System_Int32_System_Int32_" }, { "code": null, "e": 4387, "s": 4358, "text": "CSharp-Collections-ArrayList" }, { "code": null, "e": 4416, "s": 4387, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 4430, "s": 4416, "text": "CSharp-method" }, { "code": null, "e": 4433, "s": 4430, "text": "C#" } ]
Round to next greater multiple of 8
04 Jul, 2022 Given an unsigned integer x. Round it up to the next greater multiple of 8 using bitwise operations only.Examples: Input : 35 Output : 40 Input : 64 Output : 64 (As 64 is already a multiple of 8. So, no modification is done.) Solution 1: We first add 7 and get a number x + 7, then we use the technique to find next smaller multiple of 8 for (x+7). For example, if x = 12, we add 7 to get 19. Now we find next smaller multiple of 19, which is 16.Solution 2: An efficient approach to solve this problem using bitwise AND operation is: x = (x + 7) &(-8) This will round up x to the next greater multiple of 8. C++ Java Python 3 C# PHP Javascript // CPP program to find smallest greater multiple// of 8 for a given number#include <bits/stdc++.h>using namespace std; // Returns next greater multiple of 8int RoundUp(int& x){ return ((x + 7) & (-8));} int main(){ int x = 39; cout << RoundUp(x); return 0;} // Java program to find smallest// greater multiple of 8 for// a given numberimport java.util.*;import java.lang.*; // Returns next greater// multiple of 8class GFG{ static int RoundUp(int x) { return ((x + 7) & (-8)); } // Driver Code public static void main(String args[]) { int x = 39; System.out.println(RoundUp(x)); }} // This code is contributed// by Akanksha Rai(Abby_akku) # Python 3 program to find# smallest greater multiple# of 8 for a given number # Returns next greater# multiple of 8def RoundUp(x): return ((x + 7) & (-8)) # Driver Codex = 39print(RoundUp(x)) # This code is contributed# by prerna saini // C# program to find smallest// greater multiple of 8 for// a given numberusing System; // Returns next greater// multiple of 8class GFG{ static int RoundUp(int x) { return ((x + 7) & (-8)); } // Driver Code public static void Main() { int x = 39; Console.WriteLine(RoundUp(x)); }} // This code is contributed// by SoumikMondal <?php// PHP program to find smallest greater// multiple of 8 for a given number // Returns next greater// multiple of 8function RoundUp($x){ return (($x + 7) & (-8));} // Driver Code$x = 39;echo RoundUp($x); // This code is contributed// by Akanksha Rai(Abby_akku)?> <script> // Javascript program to find smallest // greater multiple of 8 for // a given number // Returns next greater // multiple of 8 function RoundUp(x) { return ((x + 7) & (-8)); } let x = 39; document.write(RoundUp(x)); </script> 40 Time Complexity: O(1) Space Complexity: O(1) Solution 3: An efficient approach to solve this problem is using shift operators, as the next greater multiple of 8 can be obtained as the product of 8 and (num + 7) / 8. C++ Javascript // CPP program to find smallest greater multiple// of 8 for a given number#include <bits/stdc++.h>using namespace std; // Returns next greater multiple of 8int RoundUp(int& x){ return ((x + 7) >> 3) << 3;} //Driver Codeint main(){ int x = 39; //Function call cout << RoundUp(x); return 0;} //This code is contributed by phasing17 // JavaScript program to find smallest greater multiple// of 8 for a given number // Returns next greater multiple of 8function RoundUp(x){ return ((x + 7) >> 3) << 3;} // Driver Codelet x = 39; // Function callconsole.log(RoundUp(x)); // This code is contributed by phasing17 40 Time Complexity: O(1) Auxiliary Space: O(1) SoumikMondal Akanksha_Rai prerna saini suresh07 phasing17 Bitwise-AND divisibility Bit Magic Technical Scripter Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Jul, 2022" }, { "code": null, "e": 171, "s": 54, "text": "Given an unsigned integer x. Round it up to the next greater multiple of 8 using bitwise operations only.Examples: " }, { "code": null, "e": 283, "s": 171, "text": "Input : 35\nOutput : 40\n\nInput : 64\nOutput : 64 (As 64 is already a multiple of 8. So, no modification is done.)" }, { "code": null, "e": 669, "s": 285, "text": "Solution 1: We first add 7 and get a number x + 7, then we use the technique to find next smaller multiple of 8 for (x+7). For example, if x = 12, we add 7 to get 19. Now we find next smaller multiple of 19, which is 16.Solution 2: An efficient approach to solve this problem using bitwise AND operation is: x = (x + 7) &(-8) This will round up x to the next greater multiple of 8. " }, { "code": null, "e": 673, "s": 669, "text": "C++" }, { "code": null, "e": 678, "s": 673, "text": "Java" }, { "code": null, "e": 687, "s": 678, "text": "Python 3" }, { "code": null, "e": 690, "s": 687, "text": "C#" }, { "code": null, "e": 694, "s": 690, "text": "PHP" }, { "code": null, "e": 705, "s": 694, "text": "Javascript" }, { "code": "// CPP program to find smallest greater multiple// of 8 for a given number#include <bits/stdc++.h>using namespace std; // Returns next greater multiple of 8int RoundUp(int& x){ return ((x + 7) & (-8));} int main(){ int x = 39; cout << RoundUp(x); return 0;}", "e": 975, "s": 705, "text": null }, { "code": "// Java program to find smallest// greater multiple of 8 for// a given numberimport java.util.*;import java.lang.*; // Returns next greater// multiple of 8class GFG{ static int RoundUp(int x) { return ((x + 7) & (-8)); } // Driver Code public static void main(String args[]) { int x = 39; System.out.println(RoundUp(x)); }} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 1403, "s": 975, "text": null }, { "code": "# Python 3 program to find# smallest greater multiple# of 8 for a given number # Returns next greater# multiple of 8def RoundUp(x): return ((x + 7) & (-8)) # Driver Codex = 39print(RoundUp(x)) # This code is contributed# by prerna saini", "e": 1647, "s": 1403, "text": null }, { "code": "// C# program to find smallest// greater multiple of 8 for// a given numberusing System; // Returns next greater// multiple of 8class GFG{ static int RoundUp(int x) { return ((x + 7) & (-8)); } // Driver Code public static void Main() { int x = 39; Console.WriteLine(RoundUp(x)); }} // This code is contributed// by SoumikMondal", "e": 2023, "s": 1647, "text": null }, { "code": "<?php// PHP program to find smallest greater// multiple of 8 for a given number // Returns next greater// multiple of 8function RoundUp($x){ return (($x + 7) & (-8));} // Driver Code$x = 39;echo RoundUp($x); // This code is contributed// by Akanksha Rai(Abby_akku)?>", "e": 2293, "s": 2023, "text": null }, { "code": "<script> // Javascript program to find smallest // greater multiple of 8 for // a given number // Returns next greater // multiple of 8 function RoundUp(x) { return ((x + 7) & (-8)); } let x = 39; document.write(RoundUp(x)); </script>", "e": 2577, "s": 2293, "text": null }, { "code": null, "e": 2580, "s": 2577, "text": "40" }, { "code": null, "e": 2625, "s": 2580, "text": "Time Complexity: O(1) Space Complexity: O(1)" }, { "code": null, "e": 2637, "s": 2625, "text": "Solution 3:" }, { "code": null, "e": 2796, "s": 2637, "text": "An efficient approach to solve this problem is using shift operators, as the next greater multiple of 8 can be obtained as the product of 8 and (num + 7) / 8." }, { "code": null, "e": 2800, "s": 2796, "text": "C++" }, { "code": null, "e": 2811, "s": 2800, "text": "Javascript" }, { "code": "// CPP program to find smallest greater multiple// of 8 for a given number#include <bits/stdc++.h>using namespace std; // Returns next greater multiple of 8int RoundUp(int& x){ return ((x + 7) >> 3) << 3;} //Driver Codeint main(){ int x = 39; //Function call cout << RoundUp(x); return 0;} //This code is contributed by phasing17", "e": 3161, "s": 2811, "text": null }, { "code": "// JavaScript program to find smallest greater multiple// of 8 for a given number // Returns next greater multiple of 8function RoundUp(x){ return ((x + 7) >> 3) << 3;} // Driver Codelet x = 39; // Function callconsole.log(RoundUp(x)); // This code is contributed by phasing17", "e": 3445, "s": 3161, "text": null }, { "code": null, "e": 3448, "s": 3445, "text": "40" }, { "code": null, "e": 3493, "s": 3448, "text": "Time Complexity: O(1) Auxiliary Space: O(1) " }, { "code": null, "e": 3506, "s": 3493, "text": "SoumikMondal" }, { "code": null, "e": 3519, "s": 3506, "text": "Akanksha_Rai" }, { "code": null, "e": 3532, "s": 3519, "text": "prerna saini" }, { "code": null, "e": 3541, "s": 3532, "text": "suresh07" }, { "code": null, "e": 3551, "s": 3541, "text": "phasing17" }, { "code": null, "e": 3563, "s": 3551, "text": "Bitwise-AND" }, { "code": null, "e": 3576, "s": 3563, "text": "divisibility" }, { "code": null, "e": 3586, "s": 3576, "text": "Bit Magic" }, { "code": null, "e": 3605, "s": 3586, "text": "Technical Scripter" }, { "code": null, "e": 3615, "s": 3605, "text": "Bit Magic" } ]
Python IMDbPY – Getting movie ID from searched movies
22 Apr, 2020 In this article we will see how we can get the movie id from searched movies, movie id is basically unique id given to each movie as movie name can be same but id will be distinct. We use search_movie method to search movies with the same name. In order to get movie id we use movieID method. Syntax : movies[0].movieID Here movies is the list of movies returned by search_movie and movies[0] refer to first element in list Argument : It takes no argument. Return : It return string which is Movie ID Below is the implementation. # importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # name name = "Udta punjab" # searching the name search = ia.search_movie(name) # loop for printing the name and idfor i in range(len(search)): # getting the id id = search[i].movieID # printing it print(search[i]['title'] + " : " + id ) Output : Udta Punjab : 4434004 Diljit Dosanjh (Udta Punjab) : 6574338 Another example : # importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # name name = "3 idiots" # searching the name search = ia.search_movie(name) # loop for printing the name and idfor i in range(len(search)): # getting the id id = search[i].movieID # printing it print(search[i]['title'] + " : " + id ) Output : 3 Idiots : 1187043 3 idiotas : 3685624 3 Idiots : 12049418 3 Idiots w/ GUNS : 0222441 3 Idiots on Wheels : 6689378 3 Idiots Try Candy! : 8474256 3 Idiots; How Cho Copes with Slump : 9419952 The Idiots : 0154421 Idiots : 0341476 Vidiots : 5830890 Idiotest : 3607166 Idiotsitter : 3532050 The Idiot : 0043614 Idioten : 7147976 Idiots : 1687235 4 Idiots : 6470848 Idiots : 2622956 The Idiot : 0051762 Idiots : 6866900 Idiot : 0366028 Python IMDbPY-module 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 Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 273, "s": 28, "text": "In this article we will see how we can get the movie id from searched movies, movie id is basically unique id given to each movie as movie name can be same but id will be distinct. We use search_movie method to search movies with the same name." }, { "code": null, "e": 321, "s": 273, "text": "In order to get movie id we use movieID method." }, { "code": null, "e": 348, "s": 321, "text": "Syntax : movies[0].movieID" }, { "code": null, "e": 452, "s": 348, "text": "Here movies is the list of movies returned by search_movie and movies[0] refer to first element in list" }, { "code": null, "e": 485, "s": 452, "text": "Argument : It takes no argument." }, { "code": null, "e": 529, "s": 485, "text": "Return : It return string which is Movie ID" }, { "code": null, "e": 558, "s": 529, "text": "Below is the implementation." }, { "code": "# importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # name name = \"Udta punjab\" # searching the name search = ia.search_movie(name) # loop for printing the name and idfor i in range(len(search)): # getting the id id = search[i].movieID # printing it print(search[i]['title'] + \" : \" + id )", "e": 907, "s": 558, "text": null }, { "code": null, "e": 916, "s": 907, "text": "Output :" }, { "code": null, "e": 978, "s": 916, "text": "Udta Punjab : 4434004\nDiljit Dosanjh (Udta Punjab) : 6574338\n" }, { "code": null, "e": 996, "s": 978, "text": "Another example :" }, { "code": "# importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # name name = \"3 idiots\" # searching the name search = ia.search_movie(name) # loop for printing the name and idfor i in range(len(search)): # getting the id id = search[i].movieID # printing it print(search[i]['title'] + \" : \" + id )", "e": 1342, "s": 996, "text": null }, { "code": null, "e": 1351, "s": 1342, "text": "Output :" }, { "code": null, "e": 1783, "s": 1351, "text": "3 Idiots : 1187043\n3 idiotas : 3685624\n3 Idiots : 12049418\n3 Idiots w/ GUNS : 0222441\n3 Idiots on Wheels : 6689378\n3 Idiots Try Candy! : 8474256\n3 Idiots; How Cho Copes with Slump : 9419952\nThe Idiots : 0154421\nIdiots : 0341476\nVidiots : 5830890\nIdiotest : 3607166\nIdiotsitter : 3532050\nThe Idiot : 0043614\nIdioten : 7147976\nIdiots : 1687235\n4 Idiots : 6470848\nIdiots : 2622956\nThe Idiot : 0051762\nIdiots : 6866900\nIdiot : 0366028\n" }, { "code": null, "e": 1804, "s": 1783, "text": "Python IMDbPY-module" }, { "code": null, "e": 1811, "s": 1804, "text": "Python" }, { "code": null, "e": 1909, "s": 1811, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1927, "s": 1909, "text": "Python Dictionary" }, { "code": null, "e": 1969, "s": 1927, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1991, "s": 1969, "text": "Enumerate() in Python" }, { "code": null, "e": 2017, "s": 1991, "text": "Python String | replace()" }, { "code": null, "e": 2049, "s": 2017, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2078, "s": 2049, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2105, "s": 2078, "text": "Python Classes and Objects" }, { "code": null, "e": 2126, "s": 2105, "text": "Python OOPs Concepts" }, { "code": null, "e": 2162, "s": 2126, "text": "Convert integer to string in Python" } ]
The CSS3 rotate3d() Function
The rotate3d() function in CSS is used to rotate an element in 3D space. Set the amount and angle of rotation as parameter of rotate3d(). Let us see an example − Live Demo <!DOCTYPE html> <html> <head> <style> .demo { transform: rotate3d(1, 1, 1, 45deg); } .skew_img { transform-origin: left; transform: skew(-0.10turn, 30deg); } </style> </head> <body> <h1>Learn</h1> <img class="demo" src= "https://www.tutorialspoint.com/numpy/images/numpy-mini-logo.jpg" alt="Numpy"> <img class="skew_img" src= "https://www.tutorialspoint.com/apache_spark/images/apache-spark-mini-logo.jpg" alt="Apache Spark"> </body> </html> Let us now see another example − Live Demo <!DOCTYPE html> <html> <head> <style> .demo { transform: rotate3d(1, 2, 0, 30deg); color: red; font-family: sans-serif; font-size: 30px; } .skew_img { transform-origin: left; transform: skew(-0.10turn, 30deg); } </style> </head> <body> <h1>Learn</h1> <p class="demo">Learn Apache Spark</p> <img class="skew_img" src= "https://www.tutorialspoint.com/apache_spark/images/apache-spark-mini-logo.jpg" alt="Apache Spark"> </body> </html>
[ { "code": null, "e": 1325, "s": 1187, "text": "The rotate3d() function in CSS is used to rotate an element in 3D space. Set the amount and angle of rotation as parameter of rotate3d()." }, { "code": null, "e": 1349, "s": 1325, "text": "Let us see an example −" }, { "code": null, "e": 1360, "s": 1349, "text": " Live Demo" }, { "code": null, "e": 1811, "s": 1360, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n.demo {\n transform: rotate3d(1, 1, 1, 45deg);\n}\n.skew_img {\n transform-origin: left;\n transform: skew(-0.10turn, 30deg);\n}\n</style>\n</head>\n<body>\n<h1>Learn</h1>\n<img class=\"demo\" src=\n\"https://www.tutorialspoint.com/numpy/images/numpy-mini-logo.jpg\"\nalt=\"Numpy\">\n<img class=\"skew_img\" src=\n\"https://www.tutorialspoint.com/apache_spark/images/apache-spark-mini-logo.jpg\"\nalt=\"Apache Spark\">\n</body>\n</html>" }, { "code": null, "e": 1844, "s": 1811, "text": "Let us now see another example −" }, { "code": null, "e": 1855, "s": 1844, "text": " Live Demo" }, { "code": null, "e": 2306, "s": 1855, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n.demo {\n transform: rotate3d(1, 2, 0, 30deg);\n color: red;\n font-family: sans-serif;\n font-size: 30px;\n}\n.skew_img {\n transform-origin: left;\n transform: skew(-0.10turn, 30deg);\n}\n</style>\n</head>\n<body>\n<h1>Learn</h1>\n<p class=\"demo\">Learn Apache Spark</p>\n<img class=\"skew_img\" src=\n\"https://www.tutorialspoint.com/apache_spark/images/apache-spark-mini-logo.jpg\"\nalt=\"Apache Spark\">\n</body>\n</html>" } ]
Python | Find position of a character in given string
28 Apr, 2021 Given a string and a character, your task is to find the first position of the character in the string. These types of problem are very competitive programming where you need to locate the position of the character in a string.Let’s discuss a few methods to solve the problem.Method #1: Using Naive Method Python3 # Python3 code to demonstrate# to find the first position of the character# in a given string # Initializing stringini_string = 'abcdef' # Character to findc = "b"# printing initial string and characterprint ("initial_string : ", ini_string, "\ncharacter_to_find : ", c) # Using Naive Methodres = Nonefor i in range(0, len(ini_string)): if ini_string[i] == c: res = i + 1 break if res == None: print ("No such character available in string")else: print ("Character {} is present at {}".format(c, str(res))) initial_string : abcdef character_to_find : b Character b is present at 2 Method #2: Using findThis method returns -1 in case character not present. Python3 # Python3 code to demonstrate# to find first position of character# in a given string # Initializing stringini_string = 'abcdef'ini_string2 = 'xyze' # Character to findc = "b"# printing initial string and characterprint ("initial_strings : ", ini_string, " ", ini_string2, "\ncharacter_to_find : ", c) # Using find Methodres1 = ini_string.find(c)res2 = ini_string2.find(c) if res1 == -1: print ("No such character available in string {}".format( ini_string))else: print ("Character {} in string {} is present at {}".format( c, ini_string, str(res1 + 1))) if res2 == -1: print ("No such character available in string {}".format( ini_string2))else: print ("Character {} in string {} is present at {}".format( c, ini_string2, str(res2 + 1))) Output: initial_strings : abcdef xyze character_to_find : b Character b in string abcdef is present at 2 No such character available in string xyze Method #3: Using index()This Method raises Value Error in case if character not present Python3 # Python3 code to demonstrate# to find first position of character# in a given string # Initializing stringini_string1 = 'xyze' # Character to findc = "b"# printing initial string and characterprint ("initial_strings : ", ini_string1, "\ncharacter_to_find : ", c) # Using index Methodtry: res = ini_string1.index(c) print ("Character {} in string {} is present at {}".format( c, ini_string1, str(res + 1)))except ValueError as e: print ("No such character available in string {}".format(ini_string1)) Output: initial_strings : xyze character_to_find : b No such character available in string xyze arorakashish0911 Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Apr, 2021" }, { "code": null, "e": 360, "s": 52, "text": "Given a string and a character, your task is to find the first position of the character in the string. These types of problem are very competitive programming where you need to locate the position of the character in a string.Let’s discuss a few methods to solve the problem.Method #1: Using Naive Method " }, { "code": null, "e": 368, "s": 360, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to find the first position of the character# in a given string # Initializing stringini_string = 'abcdef' # Character to findc = \"b\"# printing initial string and characterprint (\"initial_string : \", ini_string, \"\\ncharacter_to_find : \", c) # Using Naive Methodres = Nonefor i in range(0, len(ini_string)): if ini_string[i] == c: res = i + 1 break if res == None: print (\"No such character available in string\")else: print (\"Character {} is present at {}\".format(c, str(res)))", "e": 902, "s": 368, "text": null }, { "code": null, "e": 979, "s": 902, "text": "initial_string : abcdef \ncharacter_to_find : b\nCharacter b is present at 2" }, { "code": null, "e": 1060, "s": 981, "text": " Method #2: Using findThis method returns -1 in case character not present. " }, { "code": null, "e": 1068, "s": 1060, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to find first position of character# in a given string # Initializing stringini_string = 'abcdef'ini_string2 = 'xyze' # Character to findc = \"b\"# printing initial string and characterprint (\"initial_strings : \", ini_string, \" \", ini_string2, \"\\ncharacter_to_find : \", c) # Using find Methodres1 = ini_string.find(c)res2 = ini_string2.find(c) if res1 == -1: print (\"No such character available in string {}\".format( ini_string))else: print (\"Character {} in string {} is present at {}\".format( c, ini_string, str(res1 + 1))) if res2 == -1: print (\"No such character available in string {}\".format( ini_string2))else: print (\"Character {} in string {} is present at {}\".format( c, ini_string2, str(res2 + 1)))", "e": 1990, "s": 1068, "text": null }, { "code": null, "e": 1998, "s": 1990, "text": "Output:" }, { "code": null, "e": 2144, "s": 1998, "text": "initial_strings : abcdef xyze \ncharacter_to_find : b\nCharacter b in string abcdef is present at 2\nNo such character available in string xyze" }, { "code": null, "e": 2236, "s": 2144, "text": " Method #3: Using index()This Method raises Value Error in case if character not present " }, { "code": null, "e": 2244, "s": 2236, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to find first position of character# in a given string # Initializing stringini_string1 = 'xyze' # Character to findc = \"b\"# printing initial string and characterprint (\"initial_strings : \", ini_string1, \"\\ncharacter_to_find : \", c) # Using index Methodtry: res = ini_string1.index(c) print (\"Character {} in string {} is present at {}\".format( c, ini_string1, str(res + 1)))except ValueError as e: print (\"No such character available in string {}\".format(ini_string1))", "e": 2799, "s": 2244, "text": null }, { "code": null, "e": 2807, "s": 2799, "text": "Output:" }, { "code": null, "e": 2899, "s": 2807, "text": "initial_strings : xyze \ncharacter_to_find : b\nNo such character available in string xyze" }, { "code": null, "e": 2916, "s": 2899, "text": "arorakashish0911" }, { "code": null, "e": 2939, "s": 2916, "text": "Python string-programs" }, { "code": null, "e": 2946, "s": 2939, "text": "Python" }, { "code": null, "e": 2962, "s": 2946, "text": "Python Programs" }, { "code": null, "e": 3060, "s": 2962, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3102, "s": 3060, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3124, "s": 3102, "text": "Enumerate() in Python" }, { "code": null, "e": 3156, "s": 3124, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3185, "s": 3156, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3212, "s": 3185, "text": "Python Classes and Objects" }, { "code": null, "e": 3234, "s": 3212, "text": "Defaultdict in Python" }, { "code": null, "e": 3273, "s": 3234, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3311, "s": 3273, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3360, "s": 3311, "text": "Python | Convert string dictionary to dictionary" } ]
Difference between Python and JavaScript
24 Nov, 2021 In this article, we will know about Javascript & Python, the purpose of their usage, along with knowing the difference between them. Python: Python is a high-level general-purpose programming language that was developed to emphasize code readability and allow them to work quickly and efficiently. Python is used for web applications, Game Development, Machine Learning, and Artificial Intelligence. Example: This is a simple Python program to print “Hello World”. Python3 # Python program to print 'Hello world'print("Hello World") Output: Hello World Usage of Python in various domains Benefits of Python: It is a high-level Object-oriented language having user-friendly data structures.Open source and community development.It is versatile, easy to read, learn and write.It supports an extensive range of libraries(NumPy for numerical calculations, Pandas for data analytics, etc).It is a dynamically typed language ie., there is no need to mention data type based on the value assigned, it takes data type.Ideal for prototypes – provide more functionality with less codingHighly Efficient(Python’s clean object-oriented design provides enhanced process control, and the language is equipped with excellent text processing and integration capabilities, as well as its own unit testing framework, which makes it more efficient.) It is a high-level Object-oriented language having user-friendly data structures. Open source and community development. It is versatile, easy to read, learn and write. It supports an extensive range of libraries(NumPy for numerical calculations, Pandas for data analytics, etc). It is a dynamically typed language ie., there is no need to mention data type based on the value assigned, it takes data type. Ideal for prototypes – provide more functionality with less coding Highly Efficient(Python’s clean object-oriented design provides enhanced process control, and the language is equipped with excellent text processing and integration capabilities, as well as its own unit testing framework, which makes it more efficient.) JavaScript: JavaScript is a programming language that conforms to the ECMAScript specification. It is a high-level scripting language introduced by Netscape to be run on the client-side of the web browser. It can insert dynamic text into HTML. JavaScript is also known as the browser’s language. Example: This is a simple program that will print “Hello World” using Javascript. Javascript // JavaScript program to print 'Hello world' <script> console.log('Hello World'); </script> Output: "Hello World" Usage of the Javascript in various domains Benefits of Javascript: JavaScript has the ability to support all modern browsers and produce an equivalent result.Global companies support community development by creating projects that are important. An example is Google (created Angular framework) or Facebook (created the React.js framework).Regardless of where you host JavaScript, it always gets executed on the client environment to save lots of bandwidth and make the execution process fast.In JavaScript, XMLHttpRequest is an important object that was designed by Microsoft. The object calls made by XMLHttpRequest as an asynchronous HTTP request to the server to transfer the data to both sides without reloading the page. JavaScript has the ability to support all modern browsers and produce an equivalent result. Global companies support community development by creating projects that are important. An example is Google (created Angular framework) or Facebook (created the React.js framework). Regardless of where you host JavaScript, it always gets executed on the client environment to save lots of bandwidth and make the execution process fast. In JavaScript, XMLHttpRequest is an important object that was designed by Microsoft. The object calls made by XMLHttpRequest as an asynchronous HTTP request to the server to transfer the data to both sides without reloading the page. Difference between Python and JavaScript: There are significant differences for both of them, which are discussed below: Python is a high-level general-purpose interpreted programming language that was developed to emphasize code readability. JavaScript is a programming language that conforms to the ECMAScript specification. It is a scripting language used for developing both desktop and web applications. It is a client-side scripting language. It uses a class-based inheritance model. It uses a prototype-based inheritance model. In this, an exception is raised when the function is called with the wrong parameters. It does not care about the functions are called with correct parameters or not. List, set, and dict are mutable while int, tuple, bool, Unicode are immutable in python. In JavaScript, only objects and arrays are mutable. It uses a more conservative programming paradigm similar to C, C++, and Java. It is a language of the web browser and one of the easiest to use. It has a comprehensive standard library. It has a limited set of utility objects. bhaskargeeksforgeeks JavaScript-Misc Python-Miscellaneous JavaScript Python Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Nov, 2021" }, { "code": null, "e": 162, "s": 28, "text": "In this article, we will know about Javascript & Python, the purpose of their usage, along with knowing the difference between them. " }, { "code": null, "e": 429, "s": 162, "text": "Python: Python is a high-level general-purpose programming language that was developed to emphasize code readability and allow them to work quickly and efficiently. Python is used for web applications, Game Development, Machine Learning, and Artificial Intelligence." }, { "code": null, "e": 494, "s": 429, "text": "Example: This is a simple Python program to print “Hello World”." }, { "code": null, "e": 502, "s": 494, "text": "Python3" }, { "code": "# Python program to print 'Hello world'print(\"Hello World\")", "e": 562, "s": 502, "text": null }, { "code": null, "e": 570, "s": 562, "text": "Output:" }, { "code": null, "e": 582, "s": 570, "text": "Hello World" }, { "code": null, "e": 617, "s": 582, "text": "Usage of Python in various domains" }, { "code": null, "e": 637, "s": 617, "text": "Benefits of Python:" }, { "code": null, "e": 1360, "s": 637, "text": "It is a high-level Object-oriented language having user-friendly data structures.Open source and community development.It is versatile, easy to read, learn and write.It supports an extensive range of libraries(NumPy for numerical calculations, Pandas for data analytics, etc).It is a dynamically typed language ie., there is no need to mention data type based on the value assigned, it takes data type.Ideal for prototypes – provide more functionality with less codingHighly Efficient(Python’s clean object-oriented design provides enhanced process control, and the language is equipped with excellent text processing and integration capabilities, as well as its own unit testing framework, which makes it more efficient.)" }, { "code": null, "e": 1442, "s": 1360, "text": "It is a high-level Object-oriented language having user-friendly data structures." }, { "code": null, "e": 1481, "s": 1442, "text": "Open source and community development." }, { "code": null, "e": 1529, "s": 1481, "text": "It is versatile, easy to read, learn and write." }, { "code": null, "e": 1640, "s": 1529, "text": "It supports an extensive range of libraries(NumPy for numerical calculations, Pandas for data analytics, etc)." }, { "code": null, "e": 1767, "s": 1640, "text": "It is a dynamically typed language ie., there is no need to mention data type based on the value assigned, it takes data type." }, { "code": null, "e": 1834, "s": 1767, "text": "Ideal for prototypes – provide more functionality with less coding" }, { "code": null, "e": 2089, "s": 1834, "text": "Highly Efficient(Python’s clean object-oriented design provides enhanced process control, and the language is equipped with excellent text processing and integration capabilities, as well as its own unit testing framework, which makes it more efficient.)" }, { "code": null, "e": 2385, "s": 2089, "text": "JavaScript: JavaScript is a programming language that conforms to the ECMAScript specification. It is a high-level scripting language introduced by Netscape to be run on the client-side of the web browser. It can insert dynamic text into HTML. JavaScript is also known as the browser’s language." }, { "code": null, "e": 2467, "s": 2385, "text": "Example: This is a simple program that will print “Hello World” using Javascript." }, { "code": null, "e": 2478, "s": 2467, "text": "Javascript" }, { "code": "// JavaScript program to print 'Hello world' <script> console.log('Hello World'); </script>", "e": 2571, "s": 2478, "text": null }, { "code": null, "e": 2579, "s": 2571, "text": "Output:" }, { "code": null, "e": 2593, "s": 2579, "text": "\"Hello World\"" }, { "code": null, "e": 2636, "s": 2593, "text": "Usage of the Javascript in various domains" }, { "code": null, "e": 2660, "s": 2636, "text": "Benefits of Javascript:" }, { "code": null, "e": 3320, "s": 2660, "text": "JavaScript has the ability to support all modern browsers and produce an equivalent result.Global companies support community development by creating projects that are important. An example is Google (created Angular framework) or Facebook (created the React.js framework).Regardless of where you host JavaScript, it always gets executed on the client environment to save lots of bandwidth and make the execution process fast.In JavaScript, XMLHttpRequest is an important object that was designed by Microsoft. The object calls made by XMLHttpRequest as an asynchronous HTTP request to the server to transfer the data to both sides without reloading the page." }, { "code": null, "e": 3412, "s": 3320, "text": "JavaScript has the ability to support all modern browsers and produce an equivalent result." }, { "code": null, "e": 3595, "s": 3412, "text": "Global companies support community development by creating projects that are important. An example is Google (created Angular framework) or Facebook (created the React.js framework)." }, { "code": null, "e": 3749, "s": 3595, "text": "Regardless of where you host JavaScript, it always gets executed on the client environment to save lots of bandwidth and make the execution process fast." }, { "code": null, "e": 3983, "s": 3749, "text": "In JavaScript, XMLHttpRequest is an important object that was designed by Microsoft. The object calls made by XMLHttpRequest as an asynchronous HTTP request to the server to transfer the data to both sides without reloading the page." }, { "code": null, "e": 4104, "s": 3983, "text": "Difference between Python and JavaScript: There are significant differences for both of them, which are discussed below:" }, { "code": null, "e": 4226, "s": 4104, "text": "Python is a high-level general-purpose interpreted programming language that was developed to emphasize code readability." }, { "code": null, "e": 4310, "s": 4226, "text": "JavaScript is a programming language that conforms to the ECMAScript specification." }, { "code": null, "e": 4392, "s": 4310, "text": "It is a scripting language used for developing both desktop and web applications." }, { "code": null, "e": 4432, "s": 4392, "text": "It is a client-side scripting language." }, { "code": null, "e": 4473, "s": 4432, "text": "It uses a class-based inheritance model." }, { "code": null, "e": 4518, "s": 4473, "text": "It uses a prototype-based inheritance model." }, { "code": null, "e": 4605, "s": 4518, "text": "In this, an exception is raised when the function is called with the wrong parameters." }, { "code": null, "e": 4685, "s": 4605, "text": "It does not care about the functions are called with correct parameters or not." }, { "code": null, "e": 4774, "s": 4685, "text": "List, set, and dict are mutable while int, tuple, bool, Unicode are immutable in python." }, { "code": null, "e": 4826, "s": 4774, "text": "In JavaScript, only objects and arrays are mutable." }, { "code": null, "e": 4904, "s": 4826, "text": "It uses a more conservative programming paradigm similar to C, C++, and Java." }, { "code": null, "e": 4971, "s": 4904, "text": "It is a language of the web browser and one of the easiest to use." }, { "code": null, "e": 5012, "s": 4971, "text": "It has a comprehensive standard library." }, { "code": null, "e": 5053, "s": 5012, "text": "It has a limited set of utility objects." }, { "code": null, "e": 5074, "s": 5053, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 5090, "s": 5074, "text": "JavaScript-Misc" }, { "code": null, "e": 5111, "s": 5090, "text": "Python-Miscellaneous" }, { "code": null, "e": 5122, "s": 5111, "text": "JavaScript" }, { "code": null, "e": 5129, "s": 5122, "text": "Python" }, { "code": null, "e": 5146, "s": 5129, "text": "Web Technologies" }, { "code": null, "e": 5173, "s": 5146, "text": "Web technologies Questions" }, { "code": null, "e": 5271, "s": 5173, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5332, "s": 5271, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5404, "s": 5332, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 5444, "s": 5404, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 5485, "s": 5444, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 5527, "s": 5485, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 5555, "s": 5527, "text": "Read JSON file using Python" }, { "code": null, "e": 5577, "s": 5555, "text": "Python map() function" }, { "code": null, "e": 5627, "s": 5577, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 5645, "s": 5627, "text": "Python Dictionary" } ]
What is the correct JSON content type ?
01 Aug, 2021 Content-Type is an HTTP header that is used to indicate the media type of the resource and in the case of responses, it tells the browser about what actually content type of the returned content is. In case of any POST or PUT requests, the client tells the server about the kind of data sent.To know about the type of content the browser is going to encounter, it does a MIME sniffing. MIME or Multipurpose Internet Mail Extension is a specification for non-text e-mail attachments. It allows the mail client or Web browser to send and receive different file formats as an attachment over the Email. For receiving a JSON request, it is important to mention or tell the browser about the type of request it is going to receive. So we set its MIME type by mentioning it in the Content-Type. We can do the same in two ways: MIME type: application/json MIME type: application/javascript MIME type: application/json It is used when it is not known how this data will be used. When the information is to be just extracted from the server in JSON format, it may be through a link or from any file, in that case, it is used. In this, the client-side only gets the data in JSON format that can be used as a link to data and can be formatted in real-time by any front end framework. Example: In this example, the MIME-type is application/json as it is just extracting the dictionary from that variable and putting it in JSON format, and showing it. php <?php// Setting the headerheader('Content-Type:application/json'); // Initializing the directory$dir =[ ['Id'=> 1, 'Name' => 'Geeks' ], ['Id'=> 2, 'Name' => 'for'], ['Id'=> 3, 'Name' => 'Geeks'], ];// Shows the json dataecho json_encode($dir);?> Output: [{"Id":1, "Name":"Geeks"}, {"Id":2, "Name":"for"}, {"Id":3, "Name":"Geeks"}] MIME type: application/javascript It is used when the use of the data is predefined. It is used by applications in which there are calls by the client-side ajax applications. It is used when the data is of type JSON-P or JSONP. JSONP or JavaScript Object Notation with Padding is used when the API is wrapped in a function call. The function is defined in the client-side JavaScript code and the API is passed to it as a parameter and thus it acts as executable JavaScript code. Example: In this example, the MIME-type is application/javascript as it is just extracting the dictionary from a variable, extract it in JSON format and then send it as a parameter to a function call at a client-side. php <?php // Using application/javascriptheader('Content-Type:application/javascript');$dir =[ ['Id'=> 1, 'Name' => 'Geeks' ], ['Id'=> 2, 'Name' => 'for'], ['Id'=> 3, 'Name' => 'Geeks'], ]; // Making a function call to the client side // using Function_call()// Sending JSON data as a parameter to client.echo "Function_call(".json_encode($dir).");"; ?> Output: Function_call([{"Id":1, "Name":"Geeks"}, {"Id":2, "Name":"for"}, {"Id":3, "Name":"Geeks"}]) It is recommended to use application/json instead of application/javascript because the JSON data is not considered as a javascript code. It is a standard and thus is given a separate content type as i.e. application/json. krshubhamam025 JSON PHP-Misc Picked PHP Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? PHP in_array() Function How to delete an array element based on key in PHP? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Aug, 2021" }, { "code": null, "e": 851, "s": 28, "text": "Content-Type is an HTTP header that is used to indicate the media type of the resource and in the case of responses, it tells the browser about what actually content type of the returned content is. In case of any POST or PUT requests, the client tells the server about the kind of data sent.To know about the type of content the browser is going to encounter, it does a MIME sniffing. MIME or Multipurpose Internet Mail Extension is a specification for non-text e-mail attachments. It allows the mail client or Web browser to send and receive different file formats as an attachment over the Email. For receiving a JSON request, it is important to mention or tell the browser about the type of request it is going to receive. So we set its MIME type by mentioning it in the Content-Type. We can do the same in two ways: " }, { "code": null, "e": 879, "s": 851, "text": "MIME type: application/json" }, { "code": null, "e": 913, "s": 879, "text": "MIME type: application/javascript" }, { "code": null, "e": 1305, "s": 913, "text": "MIME type: application/json It is used when it is not known how this data will be used. When the information is to be just extracted from the server in JSON format, it may be through a link or from any file, in that case, it is used. In this, the client-side only gets the data in JSON format that can be used as a link to data and can be formatted in real-time by any front end framework. " }, { "code": null, "e": 1473, "s": 1305, "text": "Example: In this example, the MIME-type is application/json as it is just extracting the dictionary from that variable and putting it in JSON format, and showing it. " }, { "code": null, "e": 1477, "s": 1473, "text": "php" }, { "code": "<?php// Setting the headerheader('Content-Type:application/json'); // Initializing the directory$dir =[ ['Id'=> 1, 'Name' => 'Geeks' ], ['Id'=> 2, 'Name' => 'for'], ['Id'=> 3, 'Name' => 'Geeks'], ];// Shows the json dataecho json_encode($dir);?>", "e": 1737, "s": 1477, "text": null }, { "code": null, "e": 1747, "s": 1737, "text": "Output: " }, { "code": null, "e": 1824, "s": 1747, "text": "[{\"Id\":1, \"Name\":\"Geeks\"}, {\"Id\":2, \"Name\":\"for\"}, {\"Id\":3, \"Name\":\"Geeks\"}]" }, { "code": null, "e": 2304, "s": 1824, "text": "MIME type: application/javascript It is used when the use of the data is predefined. It is used by applications in which there are calls by the client-side ajax applications. It is used when the data is of type JSON-P or JSONP. JSONP or JavaScript Object Notation with Padding is used when the API is wrapped in a function call. The function is defined in the client-side JavaScript code and the API is passed to it as a parameter and thus it acts as executable JavaScript code. " }, { "code": null, "e": 2524, "s": 2304, "text": "Example: In this example, the MIME-type is application/javascript as it is just extracting the dictionary from a variable, extract it in JSON format and then send it as a parameter to a function call at a client-side. " }, { "code": null, "e": 2528, "s": 2524, "text": "php" }, { "code": "<?php // Using application/javascriptheader('Content-Type:application/javascript');$dir =[ ['Id'=> 1, 'Name' => 'Geeks' ], ['Id'=> 2, 'Name' => 'for'], ['Id'=> 3, 'Name' => 'Geeks'], ]; // Making a function call to the client side // using Function_call()// Sending JSON data as a parameter to client.echo \"Function_call(\".json_encode($dir).\");\"; ?>", "e": 2892, "s": 2528, "text": null }, { "code": null, "e": 2902, "s": 2892, "text": "Output: " }, { "code": null, "e": 2995, "s": 2902, "text": "Function_call([{\"Id\":1, \"Name\":\"Geeks\"}, {\"Id\":2, \"Name\":\"for\"}, \n{\"Id\":3, \"Name\":\"Geeks\"}])" }, { "code": null, "e": 3220, "s": 2995, "text": "It is recommended to use application/json instead of application/javascript because the JSON data is not considered as a javascript code. It is a standard and thus is given a separate content type as i.e. application/json. " }, { "code": null, "e": 3235, "s": 3220, "text": "krshubhamam025" }, { "code": null, "e": 3240, "s": 3235, "text": "JSON" }, { "code": null, "e": 3249, "s": 3240, "text": "PHP-Misc" }, { "code": null, "e": 3256, "s": 3249, "text": "Picked" }, { "code": null, "e": 3260, "s": 3256, "text": "PHP" }, { "code": null, "e": 3277, "s": 3260, "text": "Web Technologies" }, { "code": null, "e": 3304, "s": 3277, "text": "Web technologies Questions" }, { "code": null, "e": 3308, "s": 3304, "text": "PHP" }, { "code": null, "e": 3406, "s": 3308, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3451, "s": 3406, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 3475, "s": 3451, "text": "PHP in_array() Function" }, { "code": null, "e": 3527, "s": 3475, "text": "How to delete an array element based on key in PHP?" }, { "code": null, "e": 3577, "s": 3527, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 3617, "s": 3577, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 3650, "s": 3617, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3712, "s": 3650, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3773, "s": 3712, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3823, "s": 3773, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python BeautifulSoup – find all class
26 Nov, 2020 Prerequisite:- Requests , BeautifulSoup The task is to write a program to find all the classes for a given Website URL. In Beautiful Soup there is no in-built method to find all classes. Module needed: bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal. pip install bs4 requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal. pip install requests Methods #1: Finding the class in a given HTML document. Approach: Create an HTML doc. Import module. Parse the content into BeautifulSoup. Iterate the data by class name. Code: Python3 # html codehtml_doc = """<html><head><title>Welcome to geeksforgeeks</title></head><body><p class="title"><b>Geeks</b></p> <p class="body">geeksforgeeks a computer science portal for geeks</body>""" # import modulefrom bs4 import BeautifulSoup # parse html contentsoup = BeautifulSoup( html_doc , 'html.parser') # Finding by class namesoup.find( class_ = "body" ) Output: <p class="body">geeksforgeeks a computer science portal for geeks </p> Methods #2: Below is the program to find all class in a URL. Approach: Import module Make requests instance and pass into URL Pass the requests into a Beautifulsoup() function Then we will iterate all tags and fetch class name Code: Python3 # Import Modulefrom bs4 import BeautifulSoupimport requests # Website URLURL = 'https://www.geeksforgeeks.org/' # class list setclass_list = set() # Page content from Website URLpage = requests.get( URL ) # parse html contentsoup = BeautifulSoup( page.content , 'html.parser') # get all tagstags = {tag.name for tag in soup.find_all()} # iterate all tagsfor tag in tags: # find all element of tag for i in soup.find_all( tag ): # if tag has attribute of class if i.has_attr( "class" ): if len( i['class'] ) != 0: class_list.add(" ".join( i['class'])) print( class_list ) Output: Technical Scripter 2020 Web-scraping Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Nov, 2020" }, { "code": null, "e": 68, "s": 28, "text": "Prerequisite:- Requests , BeautifulSoup" }, { "code": null, "e": 215, "s": 68, "text": "The task is to write a program to find all the classes for a given Website URL. In Beautiful Soup there is no in-built method to find all classes." }, { "code": null, "e": 230, "s": 215, "text": "Module needed:" }, { "code": null, "e": 423, "s": 230, "text": "bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 441, "s": 423, "text": "pip install bs4\n\n" }, { "code": null, "e": 625, "s": 441, "text": "requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 648, "s": 625, "text": "pip install requests\n\n" }, { "code": null, "e": 704, "s": 648, "text": "Methods #1: Finding the class in a given HTML document." }, { "code": null, "e": 714, "s": 704, "text": "Approach:" }, { "code": null, "e": 734, "s": 714, "text": "Create an HTML doc." }, { "code": null, "e": 749, "s": 734, "text": "Import module." }, { "code": null, "e": 787, "s": 749, "text": "Parse the content into BeautifulSoup." }, { "code": null, "e": 819, "s": 787, "text": "Iterate the data by class name." }, { "code": null, "e": 825, "s": 819, "text": "Code:" }, { "code": null, "e": 833, "s": 825, "text": "Python3" }, { "code": "# html codehtml_doc = \"\"\"<html><head><title>Welcome to geeksforgeeks</title></head><body><p class=\"title\"><b>Geeks</b></p> <p class=\"body\">geeksforgeeks a computer science portal for geeks</body>\"\"\" # import modulefrom bs4 import BeautifulSoup # parse html contentsoup = BeautifulSoup( html_doc , 'html.parser') # Finding by class namesoup.find( class_ = \"body\" )", "e": 1204, "s": 833, "text": null }, { "code": null, "e": 1212, "s": 1204, "text": "Output:" }, { "code": null, "e": 1283, "s": 1212, "text": "<p class=\"body\">geeksforgeeks a computer science portal for geeks\n</p>" }, { "code": null, "e": 1346, "s": 1285, "text": "Methods #2: Below is the program to find all class in a URL." }, { "code": null, "e": 1356, "s": 1346, "text": "Approach:" }, { "code": null, "e": 1370, "s": 1356, "text": "Import module" }, { "code": null, "e": 1411, "s": 1370, "text": "Make requests instance and pass into URL" }, { "code": null, "e": 1461, "s": 1411, "text": "Pass the requests into a Beautifulsoup() function" }, { "code": null, "e": 1512, "s": 1461, "text": "Then we will iterate all tags and fetch class name" }, { "code": null, "e": 1518, "s": 1512, "text": "Code:" }, { "code": null, "e": 1526, "s": 1518, "text": "Python3" }, { "code": "# Import Modulefrom bs4 import BeautifulSoupimport requests # Website URLURL = 'https://www.geeksforgeeks.org/' # class list setclass_list = set() # Page content from Website URLpage = requests.get( URL ) # parse html contentsoup = BeautifulSoup( page.content , 'html.parser') # get all tagstags = {tag.name for tag in soup.find_all()} # iterate all tagsfor tag in tags: # find all element of tag for i in soup.find_all( tag ): # if tag has attribute of class if i.has_attr( \"class\" ): if len( i['class'] ) != 0: class_list.add(\" \".join( i['class'])) print( class_list )", "e": 2156, "s": 1526, "text": null }, { "code": null, "e": 2164, "s": 2156, "text": "Output:" }, { "code": null, "e": 2188, "s": 2164, "text": "Technical Scripter 2020" }, { "code": null, "e": 2201, "s": 2188, "text": "Web-scraping" }, { "code": null, "e": 2208, "s": 2201, "text": "Python" }, { "code": null, "e": 2227, "s": 2208, "text": "Technical Scripter" }, { "code": null, "e": 2325, "s": 2227, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2343, "s": 2325, "text": "Python Dictionary" }, { "code": null, "e": 2385, "s": 2343, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2407, "s": 2385, "text": "Enumerate() in Python" }, { "code": null, "e": 2442, "s": 2407, "text": "Read a file line by line in Python" }, { "code": null, "e": 2468, "s": 2442, "text": "Python String | replace()" }, { "code": null, "e": 2500, "s": 2468, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2529, "s": 2500, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2556, "s": 2529, "text": "Python Classes and Objects" }, { "code": null, "e": 2586, "s": 2556, "text": "Iterate over a list in Python" } ]
Slicing range() function in Python
03 Nov, 2021 range() allows users to generate a series of numbers within a given range. Depending on how many arguments the user is passing to the function, the user can decide where that series of numbers will begin and end as well as how big the difference will be between one number and the next.range() takes mainly three arguments. start: integer starting from which the sequence of integers is to be returned stop: integer before which the sequence of integers is to be returned.The range of integers end at stop – 1. step: integer value which determines the increment between each integer in the sequence Note: For more information, refer to Python range() function Example: # Python Program to # show range() basics # printing a number for i in range(10): print(i, end =" ") print() Output: 0 1 2 3 4 5 6 7 8 9 In Python, range objects are not iterators but are iterables. So slicing a range() function does not return an iterator but returns an iterable instead. Example: # Python program to demonstrate# slicing of range function a = range(100) # Slicing range functionans = a[:50]print(ans) Output: range(0, 50) Now our new range ‘ans’ has numbers from 0 to 50 (50 exclusive). So a generalization for understanding this is a[start : end : the difference between numbers] So doing something like ans = a[10:89:3] will have a range of numbers starting from 10 till 89 with a difference of 3 in between them. Example: # Python program to demonstrate# slicing of range function a = range(100) # Slicing range functionans = a[10:89:3]print(ans) ans = a[::5]print(ans) Output: range(10, 89, 3) range(0, 100, 5) contactmm python-basics 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": 53, "s": 25, "text": "\n03 Nov, 2021" }, { "code": null, "e": 377, "s": 53, "text": "range() allows users to generate a series of numbers within a given range. Depending on how many arguments the user is passing to the function, the user can decide where that series of numbers will begin and end as well as how big the difference will be between one number and the next.range() takes mainly three arguments." }, { "code": null, "e": 455, "s": 377, "text": "start: integer starting from which the sequence of integers is to be returned" }, { "code": null, "e": 564, "s": 455, "text": "stop: integer before which the sequence of integers is to be returned.The range of integers end at stop – 1." }, { "code": null, "e": 652, "s": 564, "text": "step: integer value which determines the increment between each integer in the sequence" }, { "code": null, "e": 713, "s": 652, "text": "Note: For more information, refer to Python range() function" }, { "code": null, "e": 722, "s": 713, "text": "Example:" }, { "code": "# Python Program to # show range() basics # printing a number for i in range(10): print(i, end =\" \") print()", "e": 840, "s": 722, "text": null }, { "code": null, "e": 848, "s": 840, "text": "Output:" }, { "code": null, "e": 869, "s": 848, "text": "0 1 2 3 4 5 6 7 8 9 " }, { "code": null, "e": 1022, "s": 869, "text": "In Python, range objects are not iterators but are iterables. So slicing a range() function does not return an iterator but returns an iterable instead." }, { "code": null, "e": 1031, "s": 1022, "text": "Example:" }, { "code": "# Python program to demonstrate# slicing of range function a = range(100) # Slicing range functionans = a[:50]print(ans)", "e": 1156, "s": 1031, "text": null }, { "code": null, "e": 1164, "s": 1156, "text": "Output:" }, { "code": null, "e": 1177, "s": 1164, "text": "range(0, 50)" }, { "code": null, "e": 1289, "s": 1177, "text": "Now our new range ‘ans’ has numbers from 0 to 50 (50 exclusive). So a generalization for understanding this is " }, { "code": null, "e": 1337, "s": 1289, "text": "a[start : end : the difference between numbers]" }, { "code": null, "e": 1473, "s": 1337, "text": "So doing something like ans = a[10:89:3] will have a range of numbers starting from 10 till 89 with a difference of 3 in between them. " }, { "code": null, "e": 1482, "s": 1473, "text": "Example:" }, { "code": "# Python program to demonstrate# slicing of range function a = range(100) # Slicing range functionans = a[10:89:3]print(ans) ans = a[::5]print(ans)", "e": 1635, "s": 1482, "text": null }, { "code": null, "e": 1643, "s": 1635, "text": "Output:" }, { "code": null, "e": 1677, "s": 1643, "text": "range(10, 89, 3)\nrange(0, 100, 5)" }, { "code": null, "e": 1687, "s": 1677, "text": "contactmm" }, { "code": null, "e": 1701, "s": 1687, "text": "python-basics" }, { "code": null, "e": 1708, "s": 1701, "text": "Python" }, { "code": null, "e": 1806, "s": 1708, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1824, "s": 1806, "text": "Python Dictionary" }, { "code": null, "e": 1866, "s": 1824, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1888, "s": 1866, "text": "Enumerate() in Python" }, { "code": null, "e": 1923, "s": 1888, "text": "Read a file line by line in Python" }, { "code": null, "e": 1949, "s": 1923, "text": "Python String | replace()" }, { "code": null, "e": 1981, "s": 1949, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2010, "s": 1981, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2037, "s": 2010, "text": "Python Classes and Objects" }, { "code": null, "e": 2067, "s": 2037, "text": "Iterate over a list in Python" } ]
How to normalize an array in NumPy in Python?
08 Dec, 2021 In this article, we are going to discuss how to normalize 1D and 2D arrays in Python using NumPy. Normalization refers to scaling values of an array to the desired range. Suppose, we have an array = [1,2,3] and to normalize it in range [0,1] means that it will convert array [1,2,3] to [0, 0.5, 1] as 1, 2 and 3 are equidistant. Array [1,2,4] -> [0, 0.3, 1] This can also be done in a Range i.e. instead of [0,1], we will use [3,7]. Now, Array [1,2,3] -> [3,5,7] and Array [1,2,4] -> [3,4.3,7] Let’s see examples with code Example 1: Python3 # import moduleimport numpy as np # explicit function to normalize arraydef normalize(arr, t_min, t_max): norm_arr = [] diff = t_max - t_min diff_arr = max(arr) - min(arr) for i in arr: temp = (((i - min(arr))*diff)/diff_arr) + t_min norm_arr.append(temp) return norm_arr # gives range staring from 1 and ending at 3 array_1d = np.arange(1,4) range_to_normalize = (0,1)normalized_array_1d = normalize(array_1d, range_to_normalize[0], range_to_normalize[1]) # display original and normalized arrayprint("Original Array = ",array_1d)print("Normalized Array = ",normalized_array_1d) Output: Example 2: Now, Lets input array is [1,2,4,8,10,15] and range is again [0,1] Python3 # import moduleimport numpy as np # explicit function to normalize arraydef normalize(arr, t_min, t_max): norm_arr = [] diff = t_max - t_min diff_arr = max(arr) - min(arr) for i in arr: temp = (((i - min(arr))*diff)/diff_arr) + t_min norm_arr.append(temp) return norm_arr # assign array and rangearray_1d = [1, 2, 4, 8, 10, 15]range_to_normalize = (0, 1)normalized_array_1d = normalize( array_1d, range_to_normalize[0], range_to_normalize[1]) # display original and normalized arrayprint("Original Array = ", array_1d)print("Normalized Array = ", normalized_array_1d) Output: To normalize a 2D-Array or matrix we need NumPy library. For matrix, general normalization is using The Euclidean norm or Frobenius norm. The formula for Simple normalization is Here, v is the matrix and |v| is the determinant or also called The Euclidean norm. v-cap is the normalized matrix. Below are some examples to implement the above: Example 1: Python3 # import moduleimport numpy as np # explicit function to normalize arraydef normalize_2d(matrix): norm = np.linalg.norm(matrix) matrix = matrix/norm # normalized matrix return matrix # gives and array staring from -2# and ending at 13array = np.arange(16) - 2 # converts 1d array to a matrixmatrix = array.reshape(4, 4)print("Simple Matrix \n", matrix)normalized_matrix = normalize_2d(matrix)print("\nSimple Matrix \n", normalized_matrix) Output: Example 2: We can also use other norms like 1-norm or 2-norm Python3 # import moduleimport numpy as np def normalize_2d(matrix): # Only this is changed to use 2-norm put 2 instead of 1 norm = np.linalg.norm(matrix, 1) # normalized matrix matrix = matrix/norm return matrix # gives and array staring from -2 and ending at 13array = np.arange(16) - 2 # converts 1d array to a matrixmatrix = array.reshape(4, 4) print("Simple Matrix \n", matrix)normalized_matrix = normalize_2d(matrix)print("\nSimple Matrix \n", normalized_matrix) Output: In this way, we can perform normalization with NumPy in python. anikaseth98 Picked Python-numpy 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 Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Dec, 2021" }, { "code": null, "e": 224, "s": 52, "text": "In this article, we are going to discuss how to normalize 1D and 2D arrays in Python using NumPy. Normalization refers to scaling values of an array to the desired range. " }, { "code": null, "e": 382, "s": 224, "text": "Suppose, we have an array = [1,2,3] and to normalize it in range [0,1] means that it will convert array [1,2,3] to [0, 0.5, 1] as 1, 2 and 3 are equidistant." }, { "code": null, "e": 411, "s": 382, "text": "Array [1,2,4] -> [0, 0.3, 1]" }, { "code": null, "e": 486, "s": 411, "text": "This can also be done in a Range i.e. instead of [0,1], we will use [3,7]." }, { "code": null, "e": 491, "s": 486, "text": "Now," }, { "code": null, "e": 516, "s": 491, "text": "Array [1,2,3] -> [3,5,7]" }, { "code": null, "e": 520, "s": 516, "text": "and" }, { "code": null, "e": 547, "s": 520, "text": "Array [1,2,4] -> [3,4.3,7]" }, { "code": null, "e": 576, "s": 547, "text": "Let’s see examples with code" }, { "code": null, "e": 587, "s": 576, "text": "Example 1:" }, { "code": null, "e": 595, "s": 587, "text": "Python3" }, { "code": "# import moduleimport numpy as np # explicit function to normalize arraydef normalize(arr, t_min, t_max): norm_arr = [] diff = t_max - t_min diff_arr = max(arr) - min(arr) for i in arr: temp = (((i - min(arr))*diff)/diff_arr) + t_min norm_arr.append(temp) return norm_arr # gives range staring from 1 and ending at 3 array_1d = np.arange(1,4) range_to_normalize = (0,1)normalized_array_1d = normalize(array_1d, range_to_normalize[0], range_to_normalize[1]) # display original and normalized arrayprint(\"Original Array = \",array_1d)print(\"Normalized Array = \",normalized_array_1d)", "e": 1276, "s": 595, "text": null }, { "code": null, "e": 1284, "s": 1276, "text": "Output:" }, { "code": null, "e": 1295, "s": 1284, "text": "Example 2:" }, { "code": null, "e": 1362, "s": 1295, "text": "Now, Lets input array is [1,2,4,8,10,15] and range is again [0,1] " }, { "code": null, "e": 1370, "s": 1362, "text": "Python3" }, { "code": "# import moduleimport numpy as np # explicit function to normalize arraydef normalize(arr, t_min, t_max): norm_arr = [] diff = t_max - t_min diff_arr = max(arr) - min(arr) for i in arr: temp = (((i - min(arr))*diff)/diff_arr) + t_min norm_arr.append(temp) return norm_arr # assign array and rangearray_1d = [1, 2, 4, 8, 10, 15]range_to_normalize = (0, 1)normalized_array_1d = normalize( array_1d, range_to_normalize[0], range_to_normalize[1]) # display original and normalized arrayprint(\"Original Array = \", array_1d)print(\"Normalized Array = \", normalized_array_1d)", "e": 1975, "s": 1370, "text": null }, { "code": null, "e": 1983, "s": 1975, "text": "Output:" }, { "code": null, "e": 2121, "s": 1983, "text": "To normalize a 2D-Array or matrix we need NumPy library. For matrix, general normalization is using The Euclidean norm or Frobenius norm." }, { "code": null, "e": 2162, "s": 2121, "text": "The formula for Simple normalization is " }, { "code": null, "e": 2278, "s": 2162, "text": "Here, v is the matrix and |v| is the determinant or also called The Euclidean norm. v-cap is the normalized matrix." }, { "code": null, "e": 2326, "s": 2278, "text": "Below are some examples to implement the above:" }, { "code": null, "e": 2337, "s": 2326, "text": "Example 1:" }, { "code": null, "e": 2345, "s": 2337, "text": "Python3" }, { "code": "# import moduleimport numpy as np # explicit function to normalize arraydef normalize_2d(matrix): norm = np.linalg.norm(matrix) matrix = matrix/norm # normalized matrix return matrix # gives and array staring from -2# and ending at 13array = np.arange(16) - 2 # converts 1d array to a matrixmatrix = array.reshape(4, 4)print(\"Simple Matrix \\n\", matrix)normalized_matrix = normalize_2d(matrix)print(\"\\nSimple Matrix \\n\", normalized_matrix)", "e": 2797, "s": 2345, "text": null }, { "code": null, "e": 2805, "s": 2797, "text": "Output:" }, { "code": null, "e": 2816, "s": 2805, "text": "Example 2:" }, { "code": null, "e": 2866, "s": 2816, "text": "We can also use other norms like 1-norm or 2-norm" }, { "code": null, "e": 2874, "s": 2866, "text": "Python3" }, { "code": "# import moduleimport numpy as np def normalize_2d(matrix): # Only this is changed to use 2-norm put 2 instead of 1 norm = np.linalg.norm(matrix, 1) # normalized matrix matrix = matrix/norm return matrix # gives and array staring from -2 and ending at 13array = np.arange(16) - 2 # converts 1d array to a matrixmatrix = array.reshape(4, 4) print(\"Simple Matrix \\n\", matrix)normalized_matrix = normalize_2d(matrix)print(\"\\nSimple Matrix \\n\", normalized_matrix)", "e": 3355, "s": 2874, "text": null }, { "code": null, "e": 3363, "s": 3355, "text": "Output:" }, { "code": null, "e": 3427, "s": 3363, "text": "In this way, we can perform normalization with NumPy in python." }, { "code": null, "e": 3439, "s": 3427, "text": "anikaseth98" }, { "code": null, "e": 3446, "s": 3439, "text": "Picked" }, { "code": null, "e": 3459, "s": 3446, "text": "Python-numpy" }, { "code": null, "e": 3466, "s": 3459, "text": "Python" }, { "code": null, "e": 3564, "s": 3466, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3596, "s": 3564, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3623, "s": 3596, "text": "Python Classes and Objects" }, { "code": null, "e": 3644, "s": 3623, "text": "Python OOPs Concepts" }, { "code": null, "e": 3667, "s": 3644, "text": "Introduction To PYTHON" }, { "code": null, "e": 3723, "s": 3667, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3754, "s": 3723, "text": "Python | os.path.join() method" }, { "code": null, "e": 3796, "s": 3754, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3838, "s": 3796, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3877, "s": 3838, "text": "Python | Get unique values from a list" } ]
Count Primes in Ranges
09 Jun, 2022 Given a range [L, R], we need to find the count of total numbers of prime numbers in the range [L, R] where 0 <= L <= R < 10000. Consider that there are a large number of queries for different ranges.Examples: Input : Query 1 : L = 1, R = 10 Query 2 : L = 5, R = 10 Output : 4 2 Explanation Primes in the range L = 1 to R = 10 are {2, 3, 5, 7}. Therefore for query, answer is 4 {2, 3, 5, 7}. For the second query, answer is 2 {5, 7}. A simple solution is to do the following for every query [L, R]. Traverse from L to R, check if current number is prime. If yes, increment the count. Finally, return the count.An efficient solution is to use Sieve of Eratosthenes to find all primes up to the given limit. Then we compute a prefix array to store counts till every value before limit. Once we have a prefix array, we can answer queries in O(1) time. We just need to return prefix[R] – prefix[L-1]. C++ Java Python3 C# PHP Javascript // CPP program to answer queries for count of// primes in given range.#include <bits/stdc++.h>using namespace std; const int MAX = 10000; // prefix[i] is going to store count of primes// till i (including i).int prefix[MAX + 1]; void buildPrefix(){ // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. bool prime[MAX + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } } // Build prefix array prefix[0] = prefix[1] = 0; for (int p = 2; p <= MAX; p++) { prefix[p] = prefix[p - 1]; if (prime[p]) prefix[p]++; }} // Returns count of primes in range from L to// R (both inclusive).int query(int L, int R){ return prefix[R] - prefix[L - 1];} // Driver codeint main(){ buildPrefix(); int L = 5, R = 10; cout << query(L, R) << endl; L = 1, R = 10; cout << query(L, R) << endl; return 0;} // Java program to answer queries for// count of primes in given range.import java.util.*; class GFG { static final int MAX = 10000; // prefix[i] is going to store count// of primes till i (including i).static int prefix[] = new int[MAX + 1]; static void buildPrefix() { // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. boolean prime[] = new boolean[MAX + 1]; Arrays.fill(prime, true); for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } } // Build prefix array prefix[0] = prefix[1] = 0; for (int p = 2; p <= MAX; p++) { prefix[p] = prefix[p - 1]; if (prime[p]) prefix[p]++; }} // Returns count of primes in range// from L to R (both inclusive).static int query(int L, int R){ return prefix[R] - prefix[L - 1];} // Driver codepublic static void main(String[] args) { buildPrefix(); int L = 5, R = 10; System.out.println(query(L, R)); L = 1; R = 10; System.out.println(query(L, R));}} // This code is contributed by Anant Agarwal. # Python3 program to answer queries for# count of primes in given range.MAX = 10000 # prefix[i] is going to# store count of primes# till i (including i).prefix =[0]*(MAX + 1) def buildPrefix(): # Create a boolean array value in # prime[i] will "prime[0..n]". A # finally be false if i is Not a # prime, else true. prime = [1]*(MAX + 1) p = 2 while(p * p <= MAX): # If prime[p] is not changed, # then it is a prime if (prime[p] == 1): # Update all multiples of p i = p * 2 while(i <= MAX): prime[i] = 0 i += p p+=1 # Build prefix array # prefix[0] = prefix[1] = 0; for p in range(2,MAX+1): prefix[p] = prefix[p - 1] if (prime[p]==1): prefix[p]+=1 # Returns count of primes# in range from L to# R (both inclusive).def query(L, R): return prefix[R]-prefix[L - 1] # Driver codeif __name__=='__main__': buildPrefix() L = 5 R = 10 print(query(L, R)) L = 1 R = 10 print(query(L, R)) # This code is contributed by mits. // C# program to answer// queries for count of// primes in given range.using System; class GFG{static int MAX = 10000; // prefix[i] is going// to store count of// primes till i (including i).static int[] prefix = new int[MAX + 1]; static void buildPrefix(){ // Create a boolean array // "prime[0..n]". A value // in prime[i] will finally // be false if i is Not a // prime, else true. bool[] prime = new bool[MAX + 1]; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is // not changed, then // it is a prime if (prime[p] == false) { // Update all // multiples of p for (int i = p * 2; i <= MAX; i += p) prime[i] = true; } } // Build prefix array prefix[0] = prefix[1] = 0; for (int p = 2; p <= MAX; p++) { prefix[p] = prefix[p - 1]; if (prime[p] == false) prefix[p]++; }} // Returns count of primes// in range from L to R// (both inclusive).static int query(int L, int R){ return prefix[R] - prefix[L - 1];} // Driver codepublic static void Main(){ buildPrefix(); int L = 5, R = 10; Console.WriteLine(query(L, R)); L = 1; R = 10; Console.WriteLine(query(L, R));}} // This code is contributed// by mits. <?php// PHP program to answer queries for// count of primes in given range.$MAX = 10000; // prefix[i] is going to// store count of primes// till i (including i).$prefix = array_fill(0, ($MAX + 1), 0); function buildPrefix(){ global $MAX, $prefix; // Create a boolean array value in // prime[i] will "prime[0..n]". A // finally be false if i is Not a // prime, else true. $prime = array_fill(0, ($MAX + 1), true); for ($p = 2; $p * $p <= $MAX; $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $MAX; $i += $p) $prime[$i] = false; } } // Build prefix array // $prefix[0] = $prefix[1] = 0; for ($p = 2; $p <= $MAX; $p++) { $prefix[$p] = $prefix[$p - 1]; if ($prime[$p]) $prefix[$p]++; }} // Returns count of primes// in range from L to// R (both inclusive).function query($L, $R){ global $prefix; return $prefix[$R] - $prefix[$L - 1];} // Driver codebuildPrefix(); $L = 5;$R = 10;echo query($L, $R) . "\n"; $L = 1;$R = 10;echo query($L, $R) . "\n"; // This code is contributed by mits.?> <script> // Javascript program to answer queries for// count of primes in given range. let MAX = 10000; // prefix[i] is going to store count// of primes till i (including i).let prefix = []; function buildPrefix() { // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. let prime = []; for (let p = 1; p <= MAX +1; p++) { prime[p] = true; } for (let p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= MAX; i += p) prime[i] = false; } } // Build prefix array prefix[0] = prefix[1] = 0; for (let p = 2; p <= MAX; p++) { prefix[p] = prefix[p - 1]; if (prime[p]) prefix[p]++; }} // Returns count of primes in range// from L to R (both inclusive).function query(L, R){ return prefix[R] - prefix[L - 1];} // driver program buildPrefix(); let L = 5, R = 10; document.write(query(L, R) + "<br/>"); L = 1; R = 10; document.write(query(L, R)); </script> Output: 2 4 Time Complexity: O(n*log(log(n))) Auxiliary Space: O(n) Here, n is the size of the prime array, Which is MAX here This article is contributed by ShivamKD. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ssharshavardhan Mithun Kumar Akanksha_Rai sanjoy_62 sachinvinod1904 array-range-queries prefix-sum Prime Number sieve Mathematical prefix-sum Mathematical Prime Number sieve 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 Find minimum number of coins that make a given value Minimum number of jumps to reach end Algorithm to solve Rubik's Cube The Knight's tour problem | Backtracking-1 Program for Decimal to Binary Conversion Modulo Operator (%) in C/C++ with Examples Modulo 10^9+7 (1000000007)
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Jun, 2022" }, { "code": null, "e": 266, "s": 54, "text": "Given a range [L, R], we need to find the count of total numbers of prime numbers in the range [L, R] where 0 <= L <= R < 10000. Consider that there are a large number of queries for different ranges.Examples: " }, { "code": null, "e": 509, "s": 266, "text": "Input : Query 1 : L = 1, R = 10\n Query 2 : L = 5, R = 10\nOutput : 4\n 2\nExplanation\nPrimes in the range L = 1 to R = 10 are \n{2, 3, 5, 7}. Therefore for query, answer \nis 4 {2, 3, 5, 7}.\nFor the second query, answer is 2 {5, 7}." }, { "code": null, "e": 976, "s": 511, "text": "A simple solution is to do the following for every query [L, R]. Traverse from L to R, check if current number is prime. If yes, increment the count. Finally, return the count.An efficient solution is to use Sieve of Eratosthenes to find all primes up to the given limit. Then we compute a prefix array to store counts till every value before limit. Once we have a prefix array, we can answer queries in O(1) time. We just need to return prefix[R] – prefix[L-1]. " }, { "code": null, "e": 980, "s": 976, "text": "C++" }, { "code": null, "e": 985, "s": 980, "text": "Java" }, { "code": null, "e": 993, "s": 985, "text": "Python3" }, { "code": null, "e": 996, "s": 993, "text": "C#" }, { "code": null, "e": 1000, "s": 996, "text": "PHP" }, { "code": null, "e": 1011, "s": 1000, "text": "Javascript" }, { "code": "// CPP program to answer queries for count of// primes in given range.#include <bits/stdc++.h>using namespace std; const int MAX = 10000; // prefix[i] is going to store count of primes// till i (including i).int prefix[MAX + 1]; void buildPrefix(){ // Create a boolean array \"prime[0..n]\". A // value in prime[i] will finally be false // if i is Not a prime, else true. bool prime[MAX + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } } // Build prefix array prefix[0] = prefix[1] = 0; for (int p = 2; p <= MAX; p++) { prefix[p] = prefix[p - 1]; if (prime[p]) prefix[p]++; }} // Returns count of primes in range from L to// R (both inclusive).int query(int L, int R){ return prefix[R] - prefix[L - 1];} // Driver codeint main(){ buildPrefix(); int L = 5, R = 10; cout << query(L, R) << endl; L = 1, R = 10; cout << query(L, R) << endl; return 0;}", "e": 2202, "s": 1011, "text": null }, { "code": "// Java program to answer queries for// count of primes in given range.import java.util.*; class GFG { static final int MAX = 10000; // prefix[i] is going to store count// of primes till i (including i).static int prefix[] = new int[MAX + 1]; static void buildPrefix() { // Create a boolean array \"prime[0..n]\". A // value in prime[i] will finally be false // if i is Not a prime, else true. boolean prime[] = new boolean[MAX + 1]; Arrays.fill(prime, true); for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } } // Build prefix array prefix[0] = prefix[1] = 0; for (int p = 2; p <= MAX; p++) { prefix[p] = prefix[p - 1]; if (prime[p]) prefix[p]++; }} // Returns count of primes in range// from L to R (both inclusive).static int query(int L, int R){ return prefix[R] - prefix[L - 1];} // Driver codepublic static void main(String[] args) { buildPrefix(); int L = 5, R = 10; System.out.println(query(L, R)); L = 1; R = 10; System.out.println(query(L, R));}} // This code is contributed by Anant Agarwal.", "e": 3470, "s": 2202, "text": null }, { "code": "# Python3 program to answer queries for# count of primes in given range.MAX = 10000 # prefix[i] is going to# store count of primes# till i (including i).prefix =[0]*(MAX + 1) def buildPrefix(): # Create a boolean array value in # prime[i] will \"prime[0..n]\". A # finally be false if i is Not a # prime, else true. prime = [1]*(MAX + 1) p = 2 while(p * p <= MAX): # If prime[p] is not changed, # then it is a prime if (prime[p] == 1): # Update all multiples of p i = p * 2 while(i <= MAX): prime[i] = 0 i += p p+=1 # Build prefix array # prefix[0] = prefix[1] = 0; for p in range(2,MAX+1): prefix[p] = prefix[p - 1] if (prime[p]==1): prefix[p]+=1 # Returns count of primes# in range from L to# R (both inclusive).def query(L, R): return prefix[R]-prefix[L - 1] # Driver codeif __name__=='__main__': buildPrefix() L = 5 R = 10 print(query(L, R)) L = 1 R = 10 print(query(L, R)) # This code is contributed by mits.", "e": 4563, "s": 3470, "text": null }, { "code": "// C# program to answer// queries for count of// primes in given range.using System; class GFG{static int MAX = 10000; // prefix[i] is going// to store count of// primes till i (including i).static int[] prefix = new int[MAX + 1]; static void buildPrefix(){ // Create a boolean array // \"prime[0..n]\". A value // in prime[i] will finally // be false if i is Not a // prime, else true. bool[] prime = new bool[MAX + 1]; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is // not changed, then // it is a prime if (prime[p] == false) { // Update all // multiples of p for (int i = p * 2; i <= MAX; i += p) prime[i] = true; } } // Build prefix array prefix[0] = prefix[1] = 0; for (int p = 2; p <= MAX; p++) { prefix[p] = prefix[p - 1]; if (prime[p] == false) prefix[p]++; }} // Returns count of primes// in range from L to R// (both inclusive).static int query(int L, int R){ return prefix[R] - prefix[L - 1];} // Driver codepublic static void Main(){ buildPrefix(); int L = 5, R = 10; Console.WriteLine(query(L, R)); L = 1; R = 10; Console.WriteLine(query(L, R));}} // This code is contributed// by mits.", "e": 5849, "s": 4563, "text": null }, { "code": "<?php// PHP program to answer queries for// count of primes in given range.$MAX = 10000; // prefix[i] is going to// store count of primes// till i (including i).$prefix = array_fill(0, ($MAX + 1), 0); function buildPrefix(){ global $MAX, $prefix; // Create a boolean array value in // prime[i] will \"prime[0..n]\". A // finally be false if i is Not a // prime, else true. $prime = array_fill(0, ($MAX + 1), true); for ($p = 2; $p * $p <= $MAX; $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $MAX; $i += $p) $prime[$i] = false; } } // Build prefix array // $prefix[0] = $prefix[1] = 0; for ($p = 2; $p <= $MAX; $p++) { $prefix[$p] = $prefix[$p - 1]; if ($prime[$p]) $prefix[$p]++; }} // Returns count of primes// in range from L to// R (both inclusive).function query($L, $R){ global $prefix; return $prefix[$R] - $prefix[$L - 1];} // Driver codebuildPrefix(); $L = 5;$R = 10;echo query($L, $R) . \"\\n\"; $L = 1;$R = 10;echo query($L, $R) . \"\\n\"; // This code is contributed by mits.?>", "e": 7112, "s": 5849, "text": null }, { "code": "<script> // Javascript program to answer queries for// count of primes in given range. let MAX = 10000; // prefix[i] is going to store count// of primes till i (including i).let prefix = []; function buildPrefix() { // Create a boolean array \"prime[0..n]\". A // value in prime[i] will finally be false // if i is Not a prime, else true. let prime = []; for (let p = 1; p <= MAX +1; p++) { prime[p] = true; } for (let p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= MAX; i += p) prime[i] = false; } } // Build prefix array prefix[0] = prefix[1] = 0; for (let p = 2; p <= MAX; p++) { prefix[p] = prefix[p - 1]; if (prime[p]) prefix[p]++; }} // Returns count of primes in range// from L to R (both inclusive).function query(L, R){ return prefix[R] - prefix[L - 1];} // driver program buildPrefix(); let L = 5, R = 10; document.write(query(L, R) + \"<br/>\"); L = 1; R = 10; document.write(query(L, R)); </script>", "e": 8267, "s": 7112, "text": null }, { "code": null, "e": 8277, "s": 8267, "text": "Output: " }, { "code": null, "e": 8281, "s": 8277, "text": "2\n4" }, { "code": null, "e": 8315, "s": 8281, "text": "Time Complexity: O(n*log(log(n)))" }, { "code": null, "e": 8337, "s": 8315, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 8395, "s": 8337, "text": "Here, n is the size of the prime array, Which is MAX here" }, { "code": null, "e": 8812, "s": 8395, "text": "This article is contributed by ShivamKD. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 8828, "s": 8812, "text": "ssharshavardhan" }, { "code": null, "e": 8841, "s": 8828, "text": "Mithun Kumar" }, { "code": null, "e": 8854, "s": 8841, "text": "Akanksha_Rai" }, { "code": null, "e": 8864, "s": 8854, "text": "sanjoy_62" }, { "code": null, "e": 8880, "s": 8864, "text": "sachinvinod1904" }, { "code": null, "e": 8900, "s": 8880, "text": "array-range-queries" }, { "code": null, "e": 8911, "s": 8900, "text": "prefix-sum" }, { "code": null, "e": 8924, "s": 8911, "text": "Prime Number" }, { "code": null, "e": 8930, "s": 8924, "text": "sieve" }, { "code": null, "e": 8943, "s": 8930, "text": "Mathematical" }, { "code": null, "e": 8954, "s": 8943, "text": "prefix-sum" }, { "code": null, "e": 8967, "s": 8954, "text": "Mathematical" }, { "code": null, "e": 8980, "s": 8967, "text": "Prime Number" }, { "code": null, "e": 8986, "s": 8980, "text": "sieve" }, { "code": null, "e": 9084, "s": 8986, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9108, "s": 9084, "text": "Merge two sorted arrays" }, { "code": null, "e": 9129, "s": 9108, "text": "Operators in C / C++" }, { "code": null, "e": 9143, "s": 9129, "text": "Prime Numbers" }, { "code": null, "e": 9196, "s": 9143, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 9233, "s": 9196, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 9265, "s": 9233, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 9308, "s": 9265, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 9349, "s": 9308, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 9392, "s": 9349, "text": "Modulo Operator (%) in C/C++ with Examples" } ]
Mapping messy addresses part 1: getting latitude and longitude | by Mark Ryan | Towards Data Science
My home city of Toronto is blessed with the only major streetcar network in North America that survived the postwar vendetta on street railways. Toronto’s streetcars are an essential part of the overall rapid transit system. However, they have one significant vulnerability — if a streetcar gets blocked it can be impossible for other streetcars to get around it, so streetcar delays have the potential to trigger gridlock. I have been working on a model that uses a publicly available dataset of information on streetcar delays to predict and help prevent such delays. The streetcar delay dataset includes details about every delay in the system since January, 2014, including the time, duration and location of the delay. The location field is completely unstructured — junctions are expressed in a variety of formats (“Queen and Sherbourne”, “queen/sherbourne”) and streets and landmarks are indicated inconsistently. For example, a single landmark can appear in the dataset with multiple, distinct location values: Roncesvalles Yard Roncy Yard Ronc. Carhouse. I need to visualize the locations of delays to understand which parts of the network are most prone to gridlock. To visualize the locations I need to convert them into latitude and longitude values. In this article I describe how I got latitude and longitude values from the messy locations in the input dataset. In the next article in this series I describe how I used these latitude and longitude values to generate maps to visualize the delay patterns. Before attempting to get latitude and longitude values I started with some old-fashioned cleanup of the location values, including: Set all location values to lowercase Replace common values that were represented with multiple strings, including inconsistent street names, and use a consistent conjunction for all junctions: Apply a function to give a consistent order to street names in junctions to avoid redundancy like “Queen and Broadview” / “Broadview and Queen”: These simple clean ups reduced the number of unique location by 35%, from 15.6 k to a little over 10 k. As we’ll see, reducing the number of unique locations means fewer calls to the API to convert locations to longitude and latitude values. The Google Geocoding API cost $5.00 / k calls, so I’ve saved $25 / batch run by reducing the number of unique locations. I decided to use the Google Geocoding API to get latitude and longitude values. This ended up being a less straightforward process than I anticipated — I hope that if you use the Geocoding API you can benefit from the lessons I learned, as described below. Here are the steps I had to take before invoking the Geocoding API from Python: Set up a project in Google Cloud. I followed the instructions here. Review the Geocoding API introduction material and follow instructions there to (1) activate the Geocoding API for your Google Cloud project and (2) get an API key for the Geocoding API Review the Python Client for Google Maps Services readme for instructions on how to invoke the Geocoding API from Python To prepare to invoke the Geocoding API from Python: Install the client Install the client ! pip install -U googlemaps 2. Associate your API key with the Geocoding API client and invoke the Geocoding API for a sample address from the cleaned up dataset: “lake shore blvd. and superior st.” Note that the address passed to the Geocoding API includes both the location from the dataset and the city (which is “Toronto” for all locations in the dataset). 3. check the latitude and longitude returned to confirm that it matches the input address: Now that we have validated the roundtrip from location value to latitude / longitude and back to address, there are a couple of snags to be overcome before we can convert the whole batch of location values. The Geocoding API choked on some location values, but not the ones I expected. I naively tried testing the API by sending a junk address “asdfasdfjjjj” and got non-empty JSON back: However, when I tried to convert a batch of locations, it failed on a location value that looked fine: “roncesvalles to neville park” To get a batch of locations converted reliably, I had to wrap the Geocoding API call in a function that checks if the returned list is empty, and if so, returns placeholder values: With the get_geocode_result function defined to call the Geocoding API reliably, I was ready to do a batch run to convert the location values. To minimize the calls to the API I defined a new dataframe df_unique containing only the unique location values: However, when I called the get_geocode_result function to add latitude and longitude values to the df_unique dataframe: I got the following error message: Checking the quota page for my project in the Google Cloud console, I could see that my daily limit for invocations of the Geocoding API was only 1,400. That’s why I was getting the OVER_QUERY_LIMIT error when I tried to invoke the API for the df_unique dataframe with over 10k values. To increase my daily limit for geocoding API calls for this project I had to open a ticket with Google Cloud support asking for my daily limit for the geocoding API to be raised: With my daily Geocoding API limit raised I was able to invoke the API on the df_unique dataframe without errors. After 1.5 hours (indicating about 110 API calls /minute) I had a dataframe including the latitude and longitude values for all the distinct locations: Next I created distinct longitude and latitude columns in the df_unique dataframe and then joined the original dataframe with df_unique: Finally, I have a dataframe containing all the original data plus latitude and longitude values corresponding to the location values: Here’s a summary of the steps required to get latitude and longitude values to correspond with all the messy locations in the original dataset: Clean up the original dataset to remove redundant locations and reduce the number of unique locationsSet up Python access to the Google Geocoding API by creating a project in Google Cloud, getting an API key, and setting up the Python Client for Google Maps ServicesCall the Geocoding API with the address (location and city) and parse the returned JSON to get the latitude and longitude. Check for the API returning an empty list, and open a ticket with Google Cloud support to get an increased daily API limit if the number of distinct locations that you want to convert is bigger than the default daily limit. Clean up the original dataset to remove redundant locations and reduce the number of unique locations Set up Python access to the Google Geocoding API by creating a project in Google Cloud, getting an API key, and setting up the Python Client for Google Maps Services Call the Geocoding API with the address (location and city) and parse the returned JSON to get the latitude and longitude. Check for the API returning an empty list, and open a ticket with Google Cloud support to get an increased daily API limit if the number of distinct locations that you want to convert is bigger than the default daily limit. In the next article in this series I describe how I used these latitude and longitude values to generate maps to visualize the delay patterns from the original dataset. If you want to try out the code described in this article yourself: The primary notebook for converting locations to latitude and longitude is here. You will need to get your own API key to run it. An example input dataframe that you can use for this notebook is here. Note that the location values in this dataframe have already been cleaned up (lowercased, street names in consistent order) as described in The solution part 1: clean up the location values to reduce redundancy section above.
[ { "code": null, "e": 742, "s": 172, "text": "My home city of Toronto is blessed with the only major streetcar network in North America that survived the postwar vendetta on street railways. Toronto’s streetcars are an essential part of the overall rapid transit system. However, they have one significant vulnerability — if a streetcar gets blocked it can be impossible for other streetcars to get around it, so streetcar delays have the potential to trigger gridlock. I have been working on a model that uses a publicly available dataset of information on streetcar delays to predict and help prevent such delays." }, { "code": null, "e": 896, "s": 742, "text": "The streetcar delay dataset includes details about every delay in the system since January, 2014, including the time, duration and location of the delay." }, { "code": null, "e": 1093, "s": 896, "text": "The location field is completely unstructured — junctions are expressed in a variety of formats (“Queen and Sherbourne”, “queen/sherbourne”) and streets and landmarks are indicated inconsistently." }, { "code": null, "e": 1191, "s": 1093, "text": "For example, a single landmark can appear in the dataset with multiple, distinct location values:" }, { "code": null, "e": 1209, "s": 1191, "text": "Roncesvalles Yard" }, { "code": null, "e": 1220, "s": 1209, "text": "Roncy Yard" }, { "code": null, "e": 1236, "s": 1220, "text": "Ronc. Carhouse." }, { "code": null, "e": 1692, "s": 1236, "text": "I need to visualize the locations of delays to understand which parts of the network are most prone to gridlock. To visualize the locations I need to convert them into latitude and longitude values. In this article I describe how I got latitude and longitude values from the messy locations in the input dataset. In the next article in this series I describe how I used these latitude and longitude values to generate maps to visualize the delay patterns." }, { "code": null, "e": 1824, "s": 1692, "text": "Before attempting to get latitude and longitude values I started with some old-fashioned cleanup of the location values, including:" }, { "code": null, "e": 1861, "s": 1824, "text": "Set all location values to lowercase" }, { "code": null, "e": 2017, "s": 1861, "text": "Replace common values that were represented with multiple strings, including inconsistent street names, and use a consistent conjunction for all junctions:" }, { "code": null, "e": 2162, "s": 2017, "text": "Apply a function to give a consistent order to street names in junctions to avoid redundancy like “Queen and Broadview” / “Broadview and Queen”:" }, { "code": null, "e": 2525, "s": 2162, "text": "These simple clean ups reduced the number of unique location by 35%, from 15.6 k to a little over 10 k. As we’ll see, reducing the number of unique locations means fewer calls to the API to convert locations to longitude and latitude values. The Google Geocoding API cost $5.00 / k calls, so I’ve saved $25 / batch run by reducing the number of unique locations." }, { "code": null, "e": 2782, "s": 2525, "text": "I decided to use the Google Geocoding API to get latitude and longitude values. This ended up being a less straightforward process than I anticipated — I hope that if you use the Geocoding API you can benefit from the lessons I learned, as described below." }, { "code": null, "e": 2862, "s": 2782, "text": "Here are the steps I had to take before invoking the Geocoding API from Python:" }, { "code": null, "e": 2930, "s": 2862, "text": "Set up a project in Google Cloud. I followed the instructions here." }, { "code": null, "e": 3116, "s": 2930, "text": "Review the Geocoding API introduction material and follow instructions there to (1) activate the Geocoding API for your Google Cloud project and (2) get an API key for the Geocoding API" }, { "code": null, "e": 3237, "s": 3116, "text": "Review the Python Client for Google Maps Services readme for instructions on how to invoke the Geocoding API from Python" }, { "code": null, "e": 3289, "s": 3237, "text": "To prepare to invoke the Geocoding API from Python:" }, { "code": null, "e": 3308, "s": 3289, "text": "Install the client" }, { "code": null, "e": 3327, "s": 3308, "text": "Install the client" }, { "code": null, "e": 3355, "s": 3327, "text": "! pip install -U googlemaps" }, { "code": null, "e": 3688, "s": 3355, "text": "2. Associate your API key with the Geocoding API client and invoke the Geocoding API for a sample address from the cleaned up dataset: “lake shore blvd. and superior st.” Note that the address passed to the Geocoding API includes both the location from the dataset and the city (which is “Toronto” for all locations in the dataset)." }, { "code": null, "e": 3779, "s": 3688, "text": "3. check the latitude and longitude returned to confirm that it matches the input address:" }, { "code": null, "e": 3986, "s": 3779, "text": "Now that we have validated the roundtrip from location value to latitude / longitude and back to address, there are a couple of snags to be overcome before we can convert the whole batch of location values." }, { "code": null, "e": 4167, "s": 3986, "text": "The Geocoding API choked on some location values, but not the ones I expected. I naively tried testing the API by sending a junk address “asdfasdfjjjj” and got non-empty JSON back:" }, { "code": null, "e": 4301, "s": 4167, "text": "However, when I tried to convert a batch of locations, it failed on a location value that looked fine: “roncesvalles to neville park”" }, { "code": null, "e": 4482, "s": 4301, "text": "To get a batch of locations converted reliably, I had to wrap the Geocoding API call in a function that checks if the returned list is empty, and if so, returns placeholder values:" }, { "code": null, "e": 4738, "s": 4482, "text": "With the get_geocode_result function defined to call the Geocoding API reliably, I was ready to do a batch run to convert the location values. To minimize the calls to the API I defined a new dataframe df_unique containing only the unique location values:" }, { "code": null, "e": 4858, "s": 4738, "text": "However, when I called the get_geocode_result function to add latitude and longitude values to the df_unique dataframe:" }, { "code": null, "e": 4893, "s": 4858, "text": "I got the following error message:" }, { "code": null, "e": 5179, "s": 4893, "text": "Checking the quota page for my project in the Google Cloud console, I could see that my daily limit for invocations of the Geocoding API was only 1,400. That’s why I was getting the OVER_QUERY_LIMIT error when I tried to invoke the API for the df_unique dataframe with over 10k values." }, { "code": null, "e": 5358, "s": 5179, "text": "To increase my daily limit for geocoding API calls for this project I had to open a ticket with Google Cloud support asking for my daily limit for the geocoding API to be raised:" }, { "code": null, "e": 5622, "s": 5358, "text": "With my daily Geocoding API limit raised I was able to invoke the API on the df_unique dataframe without errors. After 1.5 hours (indicating about 110 API calls /minute) I had a dataframe including the latitude and longitude values for all the distinct locations:" }, { "code": null, "e": 5759, "s": 5622, "text": "Next I created distinct longitude and latitude columns in the df_unique dataframe and then joined the original dataframe with df_unique:" }, { "code": null, "e": 5893, "s": 5759, "text": "Finally, I have a dataframe containing all the original data plus latitude and longitude values corresponding to the location values:" }, { "code": null, "e": 6037, "s": 5893, "text": "Here’s a summary of the steps required to get latitude and longitude values to correspond with all the messy locations in the original dataset:" }, { "code": null, "e": 6650, "s": 6037, "text": "Clean up the original dataset to remove redundant locations and reduce the number of unique locationsSet up Python access to the Google Geocoding API by creating a project in Google Cloud, getting an API key, and setting up the Python Client for Google Maps ServicesCall the Geocoding API with the address (location and city) and parse the returned JSON to get the latitude and longitude. Check for the API returning an empty list, and open a ticket with Google Cloud support to get an increased daily API limit if the number of distinct locations that you want to convert is bigger than the default daily limit." }, { "code": null, "e": 6752, "s": 6650, "text": "Clean up the original dataset to remove redundant locations and reduce the number of unique locations" }, { "code": null, "e": 6918, "s": 6752, "text": "Set up Python access to the Google Geocoding API by creating a project in Google Cloud, getting an API key, and setting up the Python Client for Google Maps Services" }, { "code": null, "e": 7265, "s": 6918, "text": "Call the Geocoding API with the address (location and city) and parse the returned JSON to get the latitude and longitude. Check for the API returning an empty list, and open a ticket with Google Cloud support to get an increased daily API limit if the number of distinct locations that you want to convert is bigger than the default daily limit." }, { "code": null, "e": 7434, "s": 7265, "text": "In the next article in this series I describe how I used these latitude and longitude values to generate maps to visualize the delay patterns from the original dataset." }, { "code": null, "e": 7502, "s": 7434, "text": "If you want to try out the code described in this article yourself:" }, { "code": null, "e": 7632, "s": 7502, "text": "The primary notebook for converting locations to latitude and longitude is here. You will need to get your own API key to run it." } ]
XML - Tags
Let us learn about one of the most important part of XML, the XML tags. XML tags form the foundation of XML. They define the scope of an element in XML. They can also be used to insert comments, declare settings required for parsing the environment, and to insert special instructions. We can broadly categorize XML tags as follows − The beginning of every non-empty XML element is marked by a start-tag. Following is an example of start-tag − <address> Every element that has a start tag should end with an end-tag. Following is an example of end-tag − </address> Note, that the end tags include a solidus ("/") before the name of an element. The text that appears between start-tag and end-tag is called content. An element which has no content is termed as empty. An empty element can be represented in two ways as follows − A start-tag immediately followed by an end-tag as shown below − <hr></hr> A complete empty-element tag is as shown below − <hr /> Empty-element tags may be used for any element which has no content. Following are the rules that need to be followed to use XML tags − XML tags are case-sensitive. Following line of code is an example of wrong syntax </Address>, because of the case difference in two tags, which is treated as erroneous syntax in XML. <address>This is wrong syntax</Address> Following code shows a correct way, where we use the same case to name the start and the end tag. <address>This is correct syntax</address> XML tags must be closed in an appropriate order, i.e., an XML tag opened inside another element must be closed before the outer element is closed. For example − <outer_element> <internal_element> This tag is closed before the outer_element </internal_element> </outer_element> 84 Lectures 6 hours Frahaan Hussain 29 Lectures 2 hours YouAccel 27 Lectures 1 hours Jordan Stanchev 16 Lectures 2 hours Simon Sez IT Print Add Notes Bookmark this page
[ { "code": null, "e": 2247, "s": 1961, "text": "Let us learn about one of the most important part of XML, the XML tags. XML tags form the foundation of XML. They define the scope of an element in XML. They can also be used to insert comments, declare settings required for parsing the environment, and to insert special instructions." }, { "code": null, "e": 2295, "s": 2247, "text": "We can broadly categorize XML tags as follows −" }, { "code": null, "e": 2405, "s": 2295, "text": "The beginning of every non-empty XML element is marked by a start-tag. Following is an\nexample of start-tag −" }, { "code": null, "e": 2416, "s": 2405, "text": "<address>\n" }, { "code": null, "e": 2516, "s": 2416, "text": "Every element that has a start tag should end with an end-tag. Following is an example of end-tag −" }, { "code": null, "e": 2528, "s": 2516, "text": "</address>\n" }, { "code": null, "e": 2607, "s": 2528, "text": "Note, that the end tags include a solidus (\"/\") before the name of an element." }, { "code": null, "e": 2791, "s": 2607, "text": "The text that appears between start-tag and end-tag is called content. An element which has no content is termed as empty. An empty element can be represented in two ways as follows −" }, { "code": null, "e": 2855, "s": 2791, "text": "A start-tag immediately followed by an end-tag as shown below −" }, { "code": null, "e": 2865, "s": 2855, "text": "<hr></hr>" }, { "code": null, "e": 2914, "s": 2865, "text": "A complete empty-element tag is as shown below −" }, { "code": null, "e": 2921, "s": 2914, "text": "<hr />" }, { "code": null, "e": 2990, "s": 2921, "text": "Empty-element tags may be used for any element which has no content." }, { "code": null, "e": 3057, "s": 2990, "text": "Following are the rules that need to be followed to use XML tags −" }, { "code": null, "e": 3240, "s": 3057, "text": "XML tags are case-sensitive. Following line of code is an example of wrong syntax </Address>, because of the case difference in two tags, which is treated as erroneous syntax in XML." }, { "code": null, "e": 3280, "s": 3240, "text": "<address>This is wrong syntax</Address>" }, { "code": null, "e": 3378, "s": 3280, "text": "Following code shows a correct way, where we use the same case to name the start and the end tag." }, { "code": null, "e": 3420, "s": 3378, "text": "<address>This is correct syntax</address>" }, { "code": null, "e": 3581, "s": 3420, "text": "XML tags must be closed in an appropriate order, i.e., an XML tag opened inside another element must be closed before the outer element is closed. For example −" }, { "code": null, "e": 3709, "s": 3581, "text": "<outer_element>\n <internal_element>\n This tag is closed before the outer_element\n </internal_element>\n</outer_element>" }, { "code": null, "e": 3742, "s": 3709, "text": "\n 84 Lectures \n 6 hours \n" }, { "code": null, "e": 3759, "s": 3742, "text": " Frahaan Hussain" }, { "code": null, "e": 3792, "s": 3759, "text": "\n 29 Lectures \n 2 hours \n" }, { "code": null, "e": 3802, "s": 3792, "text": " YouAccel" }, { "code": null, "e": 3835, "s": 3802, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 3852, "s": 3835, "text": " Jordan Stanchev" }, { "code": null, "e": 3885, "s": 3852, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3899, "s": 3885, "text": " Simon Sez IT" }, { "code": null, "e": 3906, "s": 3899, "text": " Print" }, { "code": null, "e": 3917, "s": 3906, "text": " Add Notes" } ]
Building a Fast Web Interface in Django for Data Entry | by Angelica Lo Duca | Towards Data Science
In this article I describe a simple strategy to build a fast Web Interface for data entry in Django. The article covers the following topics: Overview of Django Install Django Create a new Project Create a New App Create your Database Build the Data Entry Web Interface Django is a Python Web framework designed to build fast Web Applications. A single instance of Django is called Project. A Project may contain one or more Apps. Django follows the Model-Template-View (MTV) architecture. MTV differs from the Model-View-Controller (MVC) architecture in the sense that the Controller part is already implemented by the framework itself through templates. The Django MTV architecture is composed of the following components: Model: it defines the logical data structure. In practice, a model is a Python class, which represents a single table in the database. All the classes representing the logical structure of the database are stored in a script named models.py. View: it defines the business logic, in the sense that it communicates with the model and translates it into a format readable by the Template. A view is a Python function, which takes a request as input and returns a Web response as output. All the functions representing the business logic are stored in a script named views.py. Template: it defines the structure or the layout of a file, such as a HTML file. It is a text document or a Python string encoded through the Django template language. All the templates are stored in a subdirectory of the App named templates. The following figure illustrates the Django MTV architecture and how the Model, Template and View components interact each other: Firstly, the Django library must be installed, through the following command: pip3 install django You may decide to install it either directly in your main working environment or into a specific virtualenv. This article explains how to build a Python virtualenv. Before creating a new project, you must configure the associated database. Thus, you must have a running relational database on your machine (e.g. MySQL or Postgres). Personally, I have installed the MySQL server. Since I had an old installation of XAMPP, I have exploited the MySQL server provided by it. In PhPMyAdmin, I have created a database called mywebsite_db, initially empty. Django will populate it. In order to communicate with the SQL server, Django needs a Python driver for SQL. In the case of MySQL, you should install the mysqlclient Python library. Depending on you Operating System, you may encounter some installation issues, especially if your OS is quite old. Personally, I had some problems with the installation of the mysqlclient library, which I overcome by following the suggestions proposed at this link. In the next sections, I give an overview of how to build and run a Django app. For more details, you can refer to the Django official documentation. A single Django Web site instance is called Project. Within a Project, you can run many Web Apps. You can create a new Project using the django-admin tool: django-admin startproject mywebsite where mywebsite is the name of your Project. This command will create a new directory called mywebsite, in the folder from which you run the previous command. The folder mywebsites contains two elements: manage.py, which is the main script for configuration a folder with the same name of your project (inner mywebsite). The figure on the left shows the content of the inner mywebsite folder. Before running the new Project, you must configure the database parameters in the inner mywebsite/settings.py script, as shown: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mywebsite_db', 'USER': 'root', 'PASSWORD' : 'YOUR PASSWORD' }} You can run the development Web server from within this folder using manage.py and the runserver command: cd mywebsitepython3 manage.py runserver Within a Project you can run as apps as you want. In order to create an app you can enter the project folder and run the following command: python3 manage.py startapp myapp where myapp is the App name. Note that once a project is created, all the operations on it will be done through the manage.py script, such as startapp, migrate (as you will read later in this article, and so on). If you want to activate the new App, you must add it to the list of active Apps, contained in the inner mywebsite/setting.py script. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Add you new application, 'myapp.apps.MyappConfig'] Now you must say the Web server that a new app has been added. You can do this through the migrate command. You can launch it from the root directory of the project: python3 manage.py migrate Now the environment is ready. You can concentrate on content, in terms of data model and Web site presentation. The model can be modified in this file: myapp/models.py Each table in the database corresponds to a class in the model. For example, the table can be easily translated into the model below. from django.db import modelsclass Person(models.Model): Name = models.CharField(max_length=64) Surname = models.CharField(max_length=64) BirthDate = models.DateTimeField() Sex = models.CharField(max_length=1) The model is independent on the specific SQL database, thus can be translated by Django into a whatever SQL database (MySQL, Postgres...) Once created the model, you must tell Django that you have made some changes to your model. This can be done through the makemigrations command, followed by the migrate command, which applies all the migrations not yet applied: python3 manage.py makemigrations myapppython3 manage.py migrate In order to create the Web Interface, you can exploit a Django functionality, which is based on the admin interface. You can activate the admin interface through the following command: python3 manage.py createsuperuser Now, you must grant the admin access to all your model classes. This can be done by editing the myapp/admin.py script. You should add a register option for each table you want grant access to the admin: from django.contrib import adminfrom .models import Personadmin.site.register(Person) The admin interface will be available at the following address: http://127.0.0.1:8000/admin/. It will look like the following one: That’s all folks! In this article I have described how to build a fast Web Interface for data entry in Django. After an initial setup of the environment, deploying the Web interface is very simple, because it can exploit the admin interface provided by Django. And you, which framework do you exploit to build fast Web Interfaces? Drop me a comment! I will be glad to listen to your opinion! If you have come this far to read, for me it is already a lot for today. Thanks! You can read more about me in this article. If you want to read more about how Django works, you can read this interesting article by Rinu Gour, who explains the Django MTV Architecture. pub.towardsai.net towardsdatascience.com towardsdatascience.com One more word before leaving: you can download the full code of this tutorial from my Github repository :)
[ { "code": null, "e": 313, "s": 171, "text": "In this article I describe a simple strategy to build a fast Web Interface for data entry in Django. The article covers the following topics:" }, { "code": null, "e": 332, "s": 313, "text": "Overview of Django" }, { "code": null, "e": 347, "s": 332, "text": "Install Django" }, { "code": null, "e": 368, "s": 347, "text": "Create a new Project" }, { "code": null, "e": 385, "s": 368, "text": "Create a New App" }, { "code": null, "e": 406, "s": 385, "text": "Create your Database" }, { "code": null, "e": 441, "s": 406, "text": "Build the Data Entry Web Interface" }, { "code": null, "e": 602, "s": 441, "text": "Django is a Python Web framework designed to build fast Web Applications. A single instance of Django is called Project. A Project may contain one or more Apps." }, { "code": null, "e": 827, "s": 602, "text": "Django follows the Model-Template-View (MTV) architecture. MTV differs from the Model-View-Controller (MVC) architecture in the sense that the Controller part is already implemented by the framework itself through templates." }, { "code": null, "e": 896, "s": 827, "text": "The Django MTV architecture is composed of the following components:" }, { "code": null, "e": 1138, "s": 896, "text": "Model: it defines the logical data structure. In practice, a model is a Python class, which represents a single table in the database. All the classes representing the logical structure of the database are stored in a script named models.py." }, { "code": null, "e": 1469, "s": 1138, "text": "View: it defines the business logic, in the sense that it communicates with the model and translates it into a format readable by the Template. A view is a Python function, which takes a request as input and returns a Web response as output. All the functions representing the business logic are stored in a script named views.py." }, { "code": null, "e": 1712, "s": 1469, "text": "Template: it defines the structure or the layout of a file, such as a HTML file. It is a text document or a Python string encoded through the Django template language. All the templates are stored in a subdirectory of the App named templates." }, { "code": null, "e": 1842, "s": 1712, "text": "The following figure illustrates the Django MTV architecture and how the Model, Template and View components interact each other:" }, { "code": null, "e": 1920, "s": 1842, "text": "Firstly, the Django library must be installed, through the following command:" }, { "code": null, "e": 1940, "s": 1920, "text": "pip3 install django" }, { "code": null, "e": 2105, "s": 1940, "text": "You may decide to install it either directly in your main working environment or into a specific virtualenv. This article explains how to build a Python virtualenv." }, { "code": null, "e": 2515, "s": 2105, "text": "Before creating a new project, you must configure the associated database. Thus, you must have a running relational database on your machine (e.g. MySQL or Postgres). Personally, I have installed the MySQL server. Since I had an old installation of XAMPP, I have exploited the MySQL server provided by it. In PhPMyAdmin, I have created a database called mywebsite_db, initially empty. Django will populate it." }, { "code": null, "e": 2671, "s": 2515, "text": "In order to communicate with the SQL server, Django needs a Python driver for SQL. In the case of MySQL, you should install the mysqlclient Python library." }, { "code": null, "e": 2937, "s": 2671, "text": "Depending on you Operating System, you may encounter some installation issues, especially if your OS is quite old. Personally, I had some problems with the installation of the mysqlclient library, which I overcome by following the suggestions proposed at this link." }, { "code": null, "e": 3086, "s": 2937, "text": "In the next sections, I give an overview of how to build and run a Django app. For more details, you can refer to the Django official documentation." }, { "code": null, "e": 3242, "s": 3086, "text": "A single Django Web site instance is called Project. Within a Project, you can run many Web Apps. You can create a new Project using the django-admin tool:" }, { "code": null, "e": 3278, "s": 3242, "text": "django-admin startproject mywebsite" }, { "code": null, "e": 3437, "s": 3278, "text": "where mywebsite is the name of your Project. This command will create a new directory called mywebsite, in the folder from which you run the previous command." }, { "code": null, "e": 3482, "s": 3437, "text": "The folder mywebsites contains two elements:" }, { "code": null, "e": 3536, "s": 3482, "text": "manage.py, which is the main script for configuration" }, { "code": null, "e": 3599, "s": 3536, "text": "a folder with the same name of your project (inner mywebsite)." }, { "code": null, "e": 3671, "s": 3599, "text": "The figure on the left shows the content of the inner mywebsite folder." }, { "code": null, "e": 3799, "s": 3671, "text": "Before running the new Project, you must configure the database parameters in the inner mywebsite/settings.py script, as shown:" }, { "code": null, "e": 3970, "s": 3799, "text": "DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mywebsite_db', 'USER': 'root', 'PASSWORD' : 'YOUR PASSWORD' }}" }, { "code": null, "e": 4076, "s": 3970, "text": "You can run the development Web server from within this folder using manage.py and the runserver command:" }, { "code": null, "e": 4116, "s": 4076, "text": "cd mywebsitepython3 manage.py runserver" }, { "code": null, "e": 4256, "s": 4116, "text": "Within a Project you can run as apps as you want. In order to create an app you can enter the project folder and run the following command:" }, { "code": null, "e": 4289, "s": 4256, "text": "python3 manage.py startapp myapp" }, { "code": null, "e": 4318, "s": 4289, "text": "where myapp is the App name." }, { "code": null, "e": 4502, "s": 4318, "text": "Note that once a project is created, all the operations on it will be done through the manage.py script, such as startapp, migrate (as you will read later in this article, and so on)." }, { "code": null, "e": 4635, "s": 4502, "text": "If you want to activate the new App, you must add it to the list of active Apps, contained in the inner mywebsite/setting.py script." }, { "code": null, "e": 4893, "s": 4635, "text": "INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Add you new application, 'myapp.apps.MyappConfig']" }, { "code": null, "e": 5059, "s": 4893, "text": "Now you must say the Web server that a new app has been added. You can do this through the migrate command. You can launch it from the root directory of the project:" }, { "code": null, "e": 5085, "s": 5059, "text": "python3 manage.py migrate" }, { "code": null, "e": 5197, "s": 5085, "text": "Now the environment is ready. You can concentrate on content, in terms of data model and Web site presentation." }, { "code": null, "e": 5237, "s": 5197, "text": "The model can be modified in this file:" }, { "code": null, "e": 5253, "s": 5237, "text": "myapp/models.py" }, { "code": null, "e": 5387, "s": 5253, "text": "Each table in the database corresponds to a class in the model. For example, the table can be easily translated into the model below." }, { "code": null, "e": 5608, "s": 5387, "text": "from django.db import modelsclass Person(models.Model): Name = models.CharField(max_length=64) Surname = models.CharField(max_length=64) BirthDate = models.DateTimeField() Sex = models.CharField(max_length=1)" }, { "code": null, "e": 5746, "s": 5608, "text": "The model is independent on the specific SQL database, thus can be translated by Django into a whatever SQL database (MySQL, Postgres...)" }, { "code": null, "e": 5974, "s": 5746, "text": "Once created the model, you must tell Django that you have made some changes to your model. This can be done through the makemigrations command, followed by the migrate command, which applies all the migrations not yet applied:" }, { "code": null, "e": 6038, "s": 5974, "text": "python3 manage.py makemigrations myapppython3 manage.py migrate" }, { "code": null, "e": 6223, "s": 6038, "text": "In order to create the Web Interface, you can exploit a Django functionality, which is based on the admin interface. You can activate the admin interface through the following command:" }, { "code": null, "e": 6257, "s": 6223, "text": "python3 manage.py createsuperuser" }, { "code": null, "e": 6460, "s": 6257, "text": "Now, you must grant the admin access to all your model classes. This can be done by editing the myapp/admin.py script. You should add a register option for each table you want grant access to the admin:" }, { "code": null, "e": 6546, "s": 6460, "text": "from django.contrib import adminfrom .models import Personadmin.site.register(Person)" }, { "code": null, "e": 6677, "s": 6546, "text": "The admin interface will be available at the following address: http://127.0.0.1:8000/admin/. It will look like the following one:" }, { "code": null, "e": 6695, "s": 6677, "text": "That’s all folks!" }, { "code": null, "e": 6938, "s": 6695, "text": "In this article I have described how to build a fast Web Interface for data entry in Django. After an initial setup of the environment, deploying the Web interface is very simple, because it can exploit the admin interface provided by Django." }, { "code": null, "e": 7069, "s": 6938, "text": "And you, which framework do you exploit to build fast Web Interfaces? Drop me a comment! I will be glad to listen to your opinion!" }, { "code": null, "e": 7194, "s": 7069, "text": "If you have come this far to read, for me it is already a lot for today. Thanks! You can read more about me in this article." }, { "code": null, "e": 7337, "s": 7194, "text": "If you want to read more about how Django works, you can read this interesting article by Rinu Gour, who explains the Django MTV Architecture." }, { "code": null, "e": 7355, "s": 7337, "text": "pub.towardsai.net" }, { "code": null, "e": 7378, "s": 7355, "text": "towardsdatascience.com" }, { "code": null, "e": 7401, "s": 7378, "text": "towardsdatascience.com" } ]
Fine tuning a classifier in scikit-learn | by Kevin Arvai | Towards Data Science
It’s easy to understand that many machine learning problems benefit from either precision or recall as their optimal performance metric but implementing the concept requires knowledge of a detailed process. My first few attempts to fine-tune models for recall (sensitivity) were difficult, so I decided to share my experience. This post is from my first Kaggle kernel, where my aim was not to build a robust classifier, rather I wanted to show the practicality of optimizing a classifier for sensitivity. In figure A below, the goal is to move the decision threshold to the left. This minimizes false negatives, which are especially troublesome in the dataset chosen for this post. It contains features from images of 357 benign and 212 malignant breast biopsies. A false negative sample equates to missing a diagnosis of a malignant tumor. The data file can be downloaded here. With scikit-learn, tuning a classifier for recall can be achieved in (at least) two main steps. Using GridSearchCV to tune your model by searching for the best hyperparameters and keeping the classifier with the highest recall score.Adjust the decision threshold using the precision-recall curve and the roc curve, which is a more involved method that I will walk through. Using GridSearchCV to tune your model by searching for the best hyperparameters and keeping the classifier with the highest recall score. Adjust the decision threshold using the precision-recall curve and the roc curve, which is a more involved method that I will walk through. Start by loading the necessary libraries and the data. The class distribution can be found by counting the diagnosis column. B for benign and M for malignant. B 357M 212Name: diagnosis, dtype: int64 Convert the class labels and split the data into training and test sets. train_test_split with stratify=True results in consistent class distribution between training and test sets: # show the distributionprint('y_train class distribution')print(y_train.value_counts(normalize=True))print('y_test class distribution')print(y_test.value_counts(normalize=True))y_train class distribution0 0.6267611 0.373239Name: diagnosis, dtype: float64y_test class distribution0 0.6293711 0.370629Name: diagnosis, dtype: float64 Now that the data has been prepared, the classifier can be built. First build a generic classifier and setup a parameter grid; random forests have many tunable parameters, which make it suitable for GridSearchCV. The scorers dictionary can be used as the scoring argument in GridSearchCV. When multiple scores are passed, GridSearchCV.cv_results_ will return scoring metrics for each of the score types provided. The function below uses GridSearchCV to fit several classifiers according to the combinations of parameters in the param_grid. The scores from scorers are recorded and the best model (as scored by the refit argument) will be selected and "refit" to the full training data for downstream use. This also makes predictions on the held out X_test and prints the confusion matrix to show performance. The point of the wrapper function is to quickly reuse the code to fit the best classifier according to the type of scoring metric chosen. First, try precision_score, which should limit the number of false positives. This isn't well-suited for the goal of maxium sensitivity, but allows us to quickly show the difference between a classifier optimized for precision_score and one optimized for recall_score. grid_search_clf = grid_search_wrapper(refit_score='precision_score')Best params for precision_score{'max_depth': 15, 'max_features': 20, 'min_samples_split': 3, 'n_estimators': 300}Confusion matrix of Random Forest optimized for precision_score on the test data: pred_neg pred_posneg 85 5pos 3 50 The precision, recall, and accuracy scores for every combination of the parameters in param_grid are stored in cv_results_. Here, a pandas DataFrame helps visualize the scores and parameters for each classifier iteration. This is included to show that although accuracy may be relatively consistent across classifiers, it’s obvious that precision and recall have a trade-off. Sorting by precision, the best scoring model should be the first record. This can be checked by looking at the parameters of the first record and comparing them to grid_search.best_params_ above. results = pd.DataFrame(grid_search_clf.cv_results_)results = results.sort_values(by='mean_test_precision_score', ascending=False)results[['mean_test_precision_score', 'mean_test_recall_score', 'mean_test_accuracy_score', 'param_max_depth', 'param_max_features', 'param_min_samples_split', 'param_n_estimators']].round(3).head() That classifier was optimized for precision. For comparison, to show how GridSearchCV selects the best classifier, the function call below returns a classifier optimized for recall. The grid might be similar to the grid above, the only difference is that the classifer with the highest recall will be refit. This will be the most desirable metric in the cancer diagnosis classification problem, there should be less false negatives on the test set confusion matrix. grid_search_clf = grid_search_wrapper(refit_score='recall_score')Best params for recall_score{'max_depth': 5, 'max_features': 3, 'min_samples_split': 5, 'n_estimators': 100}Confusion matrix of Random Forest optimized for recall_score on the test data: pred_neg pred_posneg 84 6pos 3 50 Copy the same code for the generating the results table again, only this time it the best scores will be recall. results = pd.DataFrame(grid_search_clf.cv_results_)results = results.sort_values(by='mean_test_precision_score', ascending=False)results[['mean_test_precision_score', 'mean_test_recall_score', 'mean_test_accuracy_score', 'param_max_depth', 'param_max_features', 'param_min_samples_split', 'param_n_estimators']].round(3).head() The first strategy doesn’t yield impressive results for recall_score, it doesn’t significantly reduce (if at all) the number of false negatives compared to the classifier optimized for precision_score. Ideally, when designing a cancer diagnosis test, the classifier should strive as few false negatives as possible. The precision_recall_curve and roc_curve are useful tools to visualize the sensitivity-specificty tradeoff in the classifier. They help inform a data scientist where to set the decision threshold of the model to maximize either sensitivity or specificity. This is called the “operating point” of the model. The key to understanding how to fine tune classifiers in scikit-learn is to understand the methods.predict_proba() and .decision_function(). These return the raw probability that a sample is predicted to be in a class. This is an important distinction from the absolute class predictions returned by calling the .predict() method. To make this method generalizable to all classifiers in scikit-learn, know that some classifiers (like RandomForest) use .predict_proba() while others (like SVC) use .decision_function(). The default threshold for RandomForestClassifier is 0.5, so use that as a starting point. Create an array of the class probabilites called y_scores. y_scores = grid_search_clf.predict_proba(X_test)[:, 1]# for classifiers with decision_function, this achieves similar results# y_scores = classifier.decision_function(X_test) Generate the precision-recall curve for the classifier: p, r, thresholds = precision_recall_curve(y_test, y_scores) Here adjusted_classes is a simple function to return a modified version of y_scores that was calculated above, only now class labels will be assigned according to the probability threshold t. The other function below plots the precision and recall with respect to the given threshold value, t. Re-execute this function for several iterations, changing t each time, to tune the threshold until there are 0 False Negatives. On this particular run, I had to go all the way down to 0.29 before reducing the false negatives to 0. precision_recall_threshold(p, r, thresholds, 0.30)pred_neg pred_posneg 79 11pos 1 52 Another way to view the trade off between precision and recall is to plot them together as a function of the decision threshold. # use the same p, r, thresholds that were previously calculatedplot_precision_recall_vs_threshold(p, r, thresholds) Finally, the ROC curve shows that to achieve a 1.0 recall, the user of the model must select an operating point that allows for some false positive rate > 0.0. fpr, tpr, auc_thresholds = roc_curve(y_test, y_scores)print(auc(fpr, tpr)) # AUC of ROCplot_roc_curve(fpr, tpr, 'recall_optimized')0.9914046121593292 Thanks for following along. The concept of tuning a model for specificity and sensitivity should be more clear and you should be comfortable implementing the methods in your scikit-learn model. I’m interested to hear suggestions to improve the code and/or the classifiers.
[ { "code": null, "e": 374, "s": 47, "text": "It’s easy to understand that many machine learning problems benefit from either precision or recall as their optimal performance metric but implementing the concept requires knowledge of a detailed process. My first few attempts to fine-tune models for recall (sensitivity) were difficult, so I decided to share my experience." }, { "code": null, "e": 926, "s": 374, "text": "This post is from my first Kaggle kernel, where my aim was not to build a robust classifier, rather I wanted to show the practicality of optimizing a classifier for sensitivity. In figure A below, the goal is to move the decision threshold to the left. This minimizes false negatives, which are especially troublesome in the dataset chosen for this post. It contains features from images of 357 benign and 212 malignant breast biopsies. A false negative sample equates to missing a diagnosis of a malignant tumor. The data file can be downloaded here." }, { "code": null, "e": 1022, "s": 926, "text": "With scikit-learn, tuning a classifier for recall can be achieved in (at least) two main steps." }, { "code": null, "e": 1299, "s": 1022, "text": "Using GridSearchCV to tune your model by searching for the best hyperparameters and keeping the classifier with the highest recall score.Adjust the decision threshold using the precision-recall curve and the roc curve, which is a more involved method that I will walk through." }, { "code": null, "e": 1437, "s": 1299, "text": "Using GridSearchCV to tune your model by searching for the best hyperparameters and keeping the classifier with the highest recall score." }, { "code": null, "e": 1577, "s": 1437, "text": "Adjust the decision threshold using the precision-recall curve and the roc curve, which is a more involved method that I will walk through." }, { "code": null, "e": 1632, "s": 1577, "text": "Start by loading the necessary libraries and the data." }, { "code": null, "e": 1736, "s": 1632, "text": "The class distribution can be found by counting the diagnosis column. B for benign and M for malignant." }, { "code": null, "e": 1782, "s": 1736, "text": "B 357M 212Name: diagnosis, dtype: int64" }, { "code": null, "e": 1964, "s": 1782, "text": "Convert the class labels and split the data into training and test sets. train_test_split with stratify=True results in consistent class distribution between training and test sets:" }, { "code": null, "e": 2307, "s": 1964, "text": "# show the distributionprint('y_train class distribution')print(y_train.value_counts(normalize=True))print('y_test class distribution')print(y_test.value_counts(normalize=True))y_train class distribution0 0.6267611 0.373239Name: diagnosis, dtype: float64y_test class distribution0 0.6293711 0.370629Name: diagnosis, dtype: float64" }, { "code": null, "e": 2373, "s": 2307, "text": "Now that the data has been prepared, the classifier can be built." }, { "code": null, "e": 2720, "s": 2373, "text": "First build a generic classifier and setup a parameter grid; random forests have many tunable parameters, which make it suitable for GridSearchCV. The scorers dictionary can be used as the scoring argument in GridSearchCV. When multiple scores are passed, GridSearchCV.cv_results_ will return scoring metrics for each of the score types provided." }, { "code": null, "e": 3116, "s": 2720, "text": "The function below uses GridSearchCV to fit several classifiers according to the combinations of parameters in the param_grid. The scores from scorers are recorded and the best model (as scored by the refit argument) will be selected and \"refit\" to the full training data for downstream use. This also makes predictions on the held out X_test and prints the confusion matrix to show performance." }, { "code": null, "e": 3523, "s": 3116, "text": "The point of the wrapper function is to quickly reuse the code to fit the best classifier according to the type of scoring metric chosen. First, try precision_score, which should limit the number of false positives. This isn't well-suited for the goal of maxium sensitivity, but allows us to quickly show the difference between a classifier optimized for precision_score and one optimized for recall_score." }, { "code": null, "e": 3855, "s": 3523, "text": "grid_search_clf = grid_search_wrapper(refit_score='precision_score')Best params for precision_score{'max_depth': 15, 'max_features': 20, 'min_samples_split': 3, 'n_estimators': 300}Confusion matrix of Random Forest optimized for precision_score on the test data: pred_neg pred_posneg 85 5pos 3 50" }, { "code": null, "e": 4427, "s": 3855, "text": "The precision, recall, and accuracy scores for every combination of the parameters in param_grid are stored in cv_results_. Here, a pandas DataFrame helps visualize the scores and parameters for each classifier iteration. This is included to show that although accuracy may be relatively consistent across classifiers, it’s obvious that precision and recall have a trade-off. Sorting by precision, the best scoring model should be the first record. This can be checked by looking at the parameters of the first record and comparing them to grid_search.best_params_ above." }, { "code": null, "e": 4755, "s": 4427, "text": "results = pd.DataFrame(grid_search_clf.cv_results_)results = results.sort_values(by='mean_test_precision_score', ascending=False)results[['mean_test_precision_score', 'mean_test_recall_score', 'mean_test_accuracy_score', 'param_max_depth', 'param_max_features', 'param_min_samples_split', 'param_n_estimators']].round(3).head()" }, { "code": null, "e": 5221, "s": 4755, "text": "That classifier was optimized for precision. For comparison, to show how GridSearchCV selects the best classifier, the function call below returns a classifier optimized for recall. The grid might be similar to the grid above, the only difference is that the classifer with the highest recall will be refit. This will be the most desirable metric in the cancer diagnosis classification problem, there should be less false negatives on the test set confusion matrix." }, { "code": null, "e": 5542, "s": 5221, "text": "grid_search_clf = grid_search_wrapper(refit_score='recall_score')Best params for recall_score{'max_depth': 5, 'max_features': 3, 'min_samples_split': 5, 'n_estimators': 100}Confusion matrix of Random Forest optimized for recall_score on the test data: pred_neg pred_posneg 84 6pos 3 50" }, { "code": null, "e": 5655, "s": 5542, "text": "Copy the same code for the generating the results table again, only this time it the best scores will be recall." }, { "code": null, "e": 5983, "s": 5655, "text": "results = pd.DataFrame(grid_search_clf.cv_results_)results = results.sort_values(by='mean_test_precision_score', ascending=False)results[['mean_test_precision_score', 'mean_test_recall_score', 'mean_test_accuracy_score', 'param_max_depth', 'param_max_features', 'param_min_samples_split', 'param_n_estimators']].round(3).head()" }, { "code": null, "e": 6299, "s": 5983, "text": "The first strategy doesn’t yield impressive results for recall_score, it doesn’t significantly reduce (if at all) the number of false negatives compared to the classifier optimized for precision_score. Ideally, when designing a cancer diagnosis test, the classifier should strive as few false negatives as possible." }, { "code": null, "e": 6606, "s": 6299, "text": "The precision_recall_curve and roc_curve are useful tools to visualize the sensitivity-specificty tradeoff in the classifier. They help inform a data scientist where to set the decision threshold of the model to maximize either sensitivity or specificity. This is called the “operating point” of the model." }, { "code": null, "e": 6937, "s": 6606, "text": "The key to understanding how to fine tune classifiers in scikit-learn is to understand the methods.predict_proba() and .decision_function(). These return the raw probability that a sample is predicted to be in a class. This is an important distinction from the absolute class predictions returned by calling the .predict() method." }, { "code": null, "e": 7274, "s": 6937, "text": "To make this method generalizable to all classifiers in scikit-learn, know that some classifiers (like RandomForest) use .predict_proba() while others (like SVC) use .decision_function(). The default threshold for RandomForestClassifier is 0.5, so use that as a starting point. Create an array of the class probabilites called y_scores." }, { "code": null, "e": 7449, "s": 7274, "text": "y_scores = grid_search_clf.predict_proba(X_test)[:, 1]# for classifiers with decision_function, this achieves similar results# y_scores = classifier.decision_function(X_test)" }, { "code": null, "e": 7505, "s": 7449, "text": "Generate the precision-recall curve for the classifier:" }, { "code": null, "e": 7565, "s": 7505, "text": "p, r, thresholds = precision_recall_curve(y_test, y_scores)" }, { "code": null, "e": 7859, "s": 7565, "text": "Here adjusted_classes is a simple function to return a modified version of y_scores that was calculated above, only now class labels will be assigned according to the probability threshold t. The other function below plots the precision and recall with respect to the given threshold value, t." }, { "code": null, "e": 8090, "s": 7859, "text": "Re-execute this function for several iterations, changing t each time, to tune the threshold until there are 0 False Negatives. On this particular run, I had to go all the way down to 0.29 before reducing the false negatives to 0." }, { "code": null, "e": 8205, "s": 8090, "text": "precision_recall_threshold(p, r, thresholds, 0.30)pred_neg pred_posneg 79 11pos 1 52" }, { "code": null, "e": 8334, "s": 8205, "text": "Another way to view the trade off between precision and recall is to plot them together as a function of the decision threshold." }, { "code": null, "e": 8450, "s": 8334, "text": "# use the same p, r, thresholds that were previously calculatedplot_precision_recall_vs_threshold(p, r, thresholds)" }, { "code": null, "e": 8610, "s": 8450, "text": "Finally, the ROC curve shows that to achieve a 1.0 recall, the user of the model must select an operating point that allows for some false positive rate > 0.0." }, { "code": null, "e": 8760, "s": 8610, "text": "fpr, tpr, auc_thresholds = roc_curve(y_test, y_scores)print(auc(fpr, tpr)) # AUC of ROCplot_roc_curve(fpr, tpr, 'recall_optimized')0.9914046121593292" } ]
How to Build a Simple Notes App in Android? - GeeksforGeeks
13 Oct, 2020 Notes app is used for making short text notes, update when you need them, and trash when you are done. It can be used for various functions as you can add your to-do list in this app, some important notes for future reference, etc. The app is very useful in some cases like when you want quick access to the notes. Likewise, here let’s create an Android App to learn how to create a simple NotesApp. So in this article let’s build a Notes App in which the user can add any data, remove any data as well as edit any data. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the activity_main.xml file In the activity_main.xml file add a ListView and a TextView. ListView is added to display the list of auto-saved notes and TextView is used to simply display the GFG text. Below is the complete code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Adding a ListView --> <ListView android:id="@+id/listView" android:layout_width="409dp" android:layout_height="601dp" android:layout_marginTop="80dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <!--Adding a TextView --> <TextView android:id="@+id/textView2" android:layout_width="0dp" android:layout_height="0dp" android:gravity="center_horizontal" android:text="GFG" android:textColor="@android:color/holo_green_dark" android:textSize="30sp" app:layout_constraintBottom_toTopOf="@+id/listView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Output UI: Step 3: Create a new layout to show the menu Go to app > res > right-click > New > Directory and named it as menu. Then click on app > res > menu > New > Menu resource file and name the file as add_note_menu. Below is the code for the add_note_menu.xml file. XML <?xml version="1.0" encoding="utf-8"?><!--Adding Menu to show the function to User to delete and edit the data--><menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/add_note" android:title="Add note"></item> </menu> Step 4: Create a new empty activity Go to app > java > right-click > New > Activity > Empty Activity and name it as NoteEditorActivity. In this activity, we are going to type our notes. So in the activity_note_editor.xml file add an EditText to add data to ListView. Below is the code for the activity_note_editor.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".NoteEditorActivity"> <!--Adding Edit Text To add data to List View--> <EditText android:id="@+id/editText" android:layout_width="0dp" android:layout_height="0dp" android:ems="10" android:gravity="top|left" android:inputType="textMultiLine" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Now in the NoteEditorActivity.java file write code to store data. Add SharedPreference into the App to store the data in the Phone Memory. Setting Values in SharedPreference: SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit(); editor.putString(“name”, “Elena”); editor.putInt(“idName”, 12); editor.apply(); Retrieve data from SharedPreference: SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); // No name defined is the default value. String name = prefs.getString(“name”, “No name defined”); // 0 is the default value. int idName = prefs.getInt(“idName”, 0); Below is the complete code for the NoteEditorActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.widget.EditText;import androidx.appcompat.app.AppCompatActivity;import java.util.HashSet; public class NoteEditorActivity extends AppCompatActivity { int noteId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_note_editor); EditText editText = findViewById(R.id.editText); // Fetch data that is passed from MainActivity Intent intent = getIntent(); // Accessing the data using key and value noteId = intent.getIntExtra("noteId", -1); if (noteId != -1) { editText.setText(MainActivity.notes.get(noteId)); } else { MainActivity.notes.add(""); noteId = MainActivity.notes.size() - 1; MainActivity.arrayAdapter.notifyDataSetChanged(); } editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { // add your code here } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { MainActivity.notes.set(noteId, String.valueOf(charSequence)); MainActivity.arrayAdapter.notifyDataSetChanged(); // Creating Object of SharedPreferences to store data in the phone SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.notes", Context.MODE_PRIVATE); HashSet<String> set = new HashSet(MainActivity.notes); sharedPreferences.edit().putStringSet("notes", set).apply(); } @Override public void afterTextChanged(Editable editable) { // add your code here } }); }} Step 5: Working with the MainAtivity.java file Now set up all the things in the MainActivity.java file. Calling the NoteEditorActivity.java code, join all the XML code to java and run the app. Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.view.Menu;import android.view.MenuInflater;import android.view.MenuItem;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.ListView;import androidx.annotation.NonNull;import androidx.appcompat.app.AlertDialog;import androidx.appcompat.app.AppCompatActivity;import java.util.ArrayList;import java.util.HashSet; public class MainActivity extends AppCompatActivity { static ArrayList<String> notes = new ArrayList<>(); static ArrayAdapter arrayAdapter; @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.add_note_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { super.onOptionsItemSelected(item); if (item.getItemId() == R.id.add_note) { // Going from MainActivity to NotesEditorActivity Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class); startActivity(intent); return true; } return false; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView listView = findViewById(R.id.listView); SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.notes", Context.MODE_PRIVATE); HashSet<String> set = (HashSet<String>) sharedPreferences.getStringSet("notes", null); if (set == null) { notes.add("Example note"); } else { notes = new ArrayList(set); } // Using custom listView Provided by Android Studio arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, notes); listView.setAdapter(arrayAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { // Going from MainActivity to NotesEditorActivity Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class); intent.putExtra("noteId", i); startActivity(intent); } }); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) { final int itemToDelete = i; // To delete the data from the App new AlertDialog.Builder(MainActivity.this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Are you sure?") .setMessage("Do you want to delete this note?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { notes.remove(itemToDelete); arrayAdapter.notifyDataSetChanged(); SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.notes", Context.MODE_PRIVATE); HashSet<String> set = new HashSet(MainActivity.notes); sharedPreferences.edit().putStringSet("notes", set).apply(); } }).setNegativeButton("No", null).show(); return true; } }); }} android Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Android RecyclerView in Kotlin Services in Android with Example CardView in Android With Example Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 24429, "s": 24401, "text": "\n13 Oct, 2020" }, { "code": null, "e": 25115, "s": 24429, "text": "Notes app is used for making short text notes, update when you need them, and trash when you are done. It can be used for various functions as you can add your to-do list in this app, some important notes for future reference, etc. The app is very useful in some cases like when you want quick access to the notes. Likewise, here let’s create an Android App to learn how to create a simple NotesApp. So in this article let’s build a Notes App in which the user can add any data, remove any data as well as edit any data. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 25144, "s": 25115, "text": "Step 1: Create a New Project" }, { "code": null, "e": 25306, "s": 25144, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 25354, "s": 25306, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 25586, "s": 25354, "text": "In the activity_main.xml file add a ListView and a TextView. ListView is added to display the list of auto-saved notes and TextView is used to simply display the GFG text. Below is the complete code for the activity_main.xml file. " }, { "code": null, "e": 25590, "s": 25586, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Adding a ListView --> <ListView android:id=\"@+id/listView\" android:layout_width=\"409dp\" android:layout_height=\"601dp\" android:layout_marginTop=\"80dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <!--Adding a TextView --> <TextView android:id=\"@+id/textView2\" android:layout_width=\"0dp\" android:layout_height=\"0dp\" android:gravity=\"center_horizontal\" android:text=\"GFG\" android:textColor=\"@android:color/holo_green_dark\" android:textSize=\"30sp\" app:layout_constraintBottom_toTopOf=\"@+id/listView\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 26932, "s": 25590, "text": null }, { "code": null, "e": 26943, "s": 26932, "text": "Output UI:" }, { "code": null, "e": 26988, "s": 26943, "text": "Step 3: Create a new layout to show the menu" }, { "code": null, "e": 27204, "s": 26988, "text": "Go to app > res > right-click > New > Directory and named it as menu. Then click on app > res > menu > New > Menu resource file and name the file as add_note_menu. Below is the code for the add_note_menu.xml file. " }, { "code": null, "e": 27208, "s": 27204, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--Adding Menu to show the function to User to delete and edit the data--><menu xmlns:android=\"http://schemas.android.com/apk/res/android\"> <item android:id=\"@+id/add_note\" android:title=\"Add note\"></item> </menu>", "e": 27475, "s": 27208, "text": null }, { "code": null, "e": 27511, "s": 27475, "text": "Step 4: Create a new empty activity" }, { "code": null, "e": 27800, "s": 27511, "text": "Go to app > java > right-click > New > Activity > Empty Activity and name it as NoteEditorActivity. In this activity, we are going to type our notes. So in the activity_note_editor.xml file add an EditText to add data to ListView. Below is the code for the activity_note_editor.xml file. " }, { "code": null, "e": 27804, "s": 27800, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".NoteEditorActivity\"> <!--Adding Edit Text To add data to List View--> <EditText android:id=\"@+id/editText\" android:layout_width=\"0dp\" android:layout_height=\"0dp\" android:ems=\"10\" android:gravity=\"top|left\" android:inputType=\"textMultiLine\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 28714, "s": 27804, "text": null }, { "code": null, "e": 28889, "s": 28714, "text": "Now in the NoteEditorActivity.java file write code to store data. Add SharedPreference into the App to store the data in the Phone Memory. Setting Values in SharedPreference:" }, { "code": null, "e": 28981, "s": 28889, "text": "SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();" }, { "code": null, "e": 29016, "s": 28981, "text": "editor.putString(“name”, “Elena”);" }, { "code": null, "e": 29045, "s": 29016, "text": "editor.putInt(“idName”, 12);" }, { "code": null, "e": 29061, "s": 29045, "text": "editor.apply();" }, { "code": null, "e": 29098, "s": 29061, "text": "Retrieve data from SharedPreference:" }, { "code": null, "e": 29177, "s": 29098, "text": "SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); " }, { "code": null, "e": 29218, "s": 29177, "text": "// No name defined is the default value." }, { "code": null, "e": 29276, "s": 29218, "text": "String name = prefs.getString(“name”, “No name defined”);" }, { "code": null, "e": 29303, "s": 29276, "text": "// 0 is the default value." }, { "code": null, "e": 29343, "s": 29303, "text": "int idName = prefs.getInt(“idName”, 0);" }, { "code": null, "e": 29482, "s": 29343, "text": "Below is the complete code for the NoteEditorActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 29487, "s": 29482, "text": "Java" }, { "code": "import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.widget.EditText;import androidx.appcompat.app.AppCompatActivity;import java.util.HashSet; public class NoteEditorActivity extends AppCompatActivity { int noteId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_note_editor); EditText editText = findViewById(R.id.editText); // Fetch data that is passed from MainActivity Intent intent = getIntent(); // Accessing the data using key and value noteId = intent.getIntExtra(\"noteId\", -1); if (noteId != -1) { editText.setText(MainActivity.notes.get(noteId)); } else { MainActivity.notes.add(\"\"); noteId = MainActivity.notes.size() - 1; MainActivity.arrayAdapter.notifyDataSetChanged(); } editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { // add your code here } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { MainActivity.notes.set(noteId, String.valueOf(charSequence)); MainActivity.arrayAdapter.notifyDataSetChanged(); // Creating Object of SharedPreferences to store data in the phone SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(\"com.example.notes\", Context.MODE_PRIVATE); HashSet<String> set = new HashSet(MainActivity.notes); sharedPreferences.edit().putStringSet(\"notes\", set).apply(); } @Override public void afterTextChanged(Editable editable) { // add your code here } }); }}", "e": 31556, "s": 29487, "text": null }, { "code": null, "e": 31603, "s": 31556, "text": "Step 5: Working with the MainAtivity.java file" }, { "code": null, "e": 31882, "s": 31603, "text": "Now set up all the things in the MainActivity.java file. Calling the NoteEditorActivity.java code, join all the XML code to java and run the app. Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 31887, "s": 31882, "text": "Java" }, { "code": "import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.view.Menu;import android.view.MenuInflater;import android.view.MenuItem;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.ListView;import androidx.annotation.NonNull;import androidx.appcompat.app.AlertDialog;import androidx.appcompat.app.AppCompatActivity;import java.util.ArrayList;import java.util.HashSet; public class MainActivity extends AppCompatActivity { static ArrayList<String> notes = new ArrayList<>(); static ArrayAdapter arrayAdapter; @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.add_note_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { super.onOptionsItemSelected(item); if (item.getItemId() == R.id.add_note) { // Going from MainActivity to NotesEditorActivity Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class); startActivity(intent); return true; } return false; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView listView = findViewById(R.id.listView); SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(\"com.example.notes\", Context.MODE_PRIVATE); HashSet<String> set = (HashSet<String>) sharedPreferences.getStringSet(\"notes\", null); if (set == null) { notes.add(\"Example note\"); } else { notes = new ArrayList(set); } // Using custom listView Provided by Android Studio arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, notes); listView.setAdapter(arrayAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { // Going from MainActivity to NotesEditorActivity Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class); intent.putExtra(\"noteId\", i); startActivity(intent); } }); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) { final int itemToDelete = i; // To delete the data from the App new AlertDialog.Builder(MainActivity.this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(\"Are you sure?\") .setMessage(\"Do you want to delete this note?\") .setPositiveButton(\"Yes\", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { notes.remove(itemToDelete); arrayAdapter.notifyDataSetChanged(); SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(\"com.example.notes\", Context.MODE_PRIVATE); HashSet<String> set = new HashSet(MainActivity.notes); sharedPreferences.edit().putStringSet(\"notes\", set).apply(); } }).setNegativeButton(\"No\", null).show(); return true; } }); }}", "e": 35873, "s": 31887, "text": null }, { "code": null, "e": 35881, "s": 35873, "text": "android" }, { "code": null, "e": 35889, "s": 35881, "text": "Android" }, { "code": null, "e": 35894, "s": 35889, "text": "Java" }, { "code": null, "e": 35899, "s": 35894, "text": "Java" }, { "code": null, "e": 35907, "s": 35899, "text": "Android" }, { "code": null, "e": 36005, "s": 35907, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36014, "s": 36005, "text": "Comments" }, { "code": null, "e": 36027, "s": 36014, "text": "Old Comments" }, { "code": null, "e": 36085, "s": 36027, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 36128, "s": 36085, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 36159, "s": 36128, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 36192, "s": 36159, "text": "Services in Android with Example" }, { "code": null, "e": 36225, "s": 36192, "text": "CardView in Android With Example" }, { "code": null, "e": 36240, "s": 36225, "text": "Arrays in Java" }, { "code": null, "e": 36284, "s": 36240, "text": "Split() String method in Java with examples" }, { "code": null, "e": 36306, "s": 36284, "text": "For-each loop in Java" }, { "code": null, "e": 36331, "s": 36306, "text": "Reverse a string in Java" } ]
fseek() in C/C++ with example - GeeksforGeeks
02 Jun, 2017 fseek() is used to move file pointer associated with a given file to a specific position.Syntax: int fseek(FILE *pointer, long int offset, int position) pointer: pointer to a FILE object that identifies the stream. offset: number of bytes to offset from position position: position from where offset is added. returns: zero if successful, or else it returns a non-zero value position defines the point with respect to which the file pointer needs to be moved. It has three values:SEEK_END : It denotes end of the file.SEEK_SET : It denotes starting of the file.SEEK_CUR : It denotes file pointer’s current position. // C Program to demonstrate the use of fseek()#include <stdio.h> int main(){ FILE *fp; fp = fopen("test.txt", "r"); // Moving pointer to end fseek(fp, 0, SEEK_END); // Printing position of pointer printf("%ld", ftell(fp)); return 0;} Output: 81 Explanation The file test.txt contains the following text: "Someone over there is calling you. we are going for work. take care of yourself." When we implement fseek() we move the pointer by 0 distance with respect to end of file i.e pointer now points to end of the file. Therefore the output is 81. Related article: fseek vs rewind in C This article is contributed by Hardik Gaur. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C-File Handling C-Library CPP-Library C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in C / C++ rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ Command line arguments in C/C++ Function Pointer in C Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 24470, "s": 24442, "text": "\n02 Jun, 2017" }, { "code": null, "e": 24567, "s": 24470, "text": "fseek() is used to move file pointer associated with a given file to a specific position.Syntax:" }, { "code": null, "e": 24848, "s": 24567, "text": "int fseek(FILE *pointer, long int offset, int position)\npointer: pointer to a FILE object that identifies the stream.\noffset: number of bytes to offset from position\nposition: position from where offset is added.\n\nreturns:\nzero if successful, or else it returns a non-zero value \n" }, { "code": null, "e": 25089, "s": 24848, "text": "position defines the point with respect to which the file pointer needs to be moved. It has three values:SEEK_END : It denotes end of the file.SEEK_SET : It denotes starting of the file.SEEK_CUR : It denotes file pointer’s current position." }, { "code": "// C Program to demonstrate the use of fseek()#include <stdio.h> int main(){ FILE *fp; fp = fopen(\"test.txt\", \"r\"); // Moving pointer to end fseek(fp, 0, SEEK_END); // Printing position of pointer printf(\"%ld\", ftell(fp)); return 0;}", "e": 25359, "s": 25089, "text": null }, { "code": null, "e": 25367, "s": 25359, "text": "Output:" }, { "code": null, "e": 25371, "s": 25367, "text": "81\n" }, { "code": null, "e": 25383, "s": 25371, "text": "Explanation" }, { "code": null, "e": 25430, "s": 25383, "text": "The file test.txt contains the following text:" }, { "code": null, "e": 25513, "s": 25430, "text": "\"Someone over there is calling you.\nwe are going for work.\ntake care of yourself.\"" }, { "code": null, "e": 25672, "s": 25513, "text": "When we implement fseek() we move the pointer by 0 distance with respect to end of file i.e pointer now points to end of the file. Therefore the output is 81." }, { "code": null, "e": 25710, "s": 25672, "text": "Related article: fseek vs rewind in C" }, { "code": null, "e": 26009, "s": 25710, "text": "This article is contributed by Hardik Gaur. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 26134, "s": 26009, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 26150, "s": 26134, "text": "C-File Handling" }, { "code": null, "e": 26160, "s": 26150, "text": "C-Library" }, { "code": null, "e": 26172, "s": 26160, "text": "CPP-Library" }, { "code": null, "e": 26183, "s": 26172, "text": "C Language" }, { "code": null, "e": 26187, "s": 26183, "text": "C++" }, { "code": null, "e": 26191, "s": 26187, "text": "CPP" }, { "code": null, "e": 26289, "s": 26191, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26324, "s": 26289, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 26352, "s": 26324, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 26398, "s": 26352, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 26430, "s": 26398, "text": "Command line arguments in C/C++" }, { "code": null, "e": 26452, "s": 26430, "text": "Function Pointer in C" }, { "code": null, "e": 26470, "s": 26452, "text": "Vector in C++ STL" }, { "code": null, "e": 26516, "s": 26470, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 26535, "s": 26516, "text": "Inheritance in C++" }, { "code": null, "e": 26578, "s": 26535, "text": "Map in C++ Standard Template Library (STL)" } ]
Java throw Keyword
❮ Java Keywords Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print "Access granted": public class Main { static void checkAge(int age) { if (age < 18) { throw new ArithmeticException("Access denied - You must be at least 18 years old."); } else { System.out.println("Access granted - You are old enough!"); } } public static void main(String[] args) { checkAge(15); // Set age to 15 (which is below 18...) } } Try it Yourself » The throw keyword is used to create a custom error. The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc. The exception type is often used together with a custom method, like in the example above. Differences between throw and throws: throw is followed by an object (new type) used inside the method throws is followed by a class and used with the method signature Read more about exceptions in our Java Try..Catch Tutorial. ❮ Java Keywords We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 18, "s": 0, "text": "\n❮ Java Keywords\n" }, { "code": null, "e": 129, "s": 18, "text": "Throw an exception if age is below 18 (print \"Access \ndenied\"). If age is 18 or older, print \"Access granted\":" }, { "code": null, "e": 496, "s": 129, "text": "public class Main {\n static void checkAge(int age) {\n if (age < 18) {\n throw new ArithmeticException(\"Access denied - You must be at least 18 years old.\");\n }\n else {\n System.out.println(\"Access granted - You are old enough!\");\n }\n }\n\n public static void main(String[] args) {\n checkAge(15); // Set age to 15 (which is below 18...)\n }\n}\n" }, { "code": null, "e": 516, "s": 496, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 568, "s": 516, "text": "The throw keyword is used to create a custom error." }, { "code": null, "e": 780, "s": 568, "text": "The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc." }, { "code": null, "e": 871, "s": 780, "text": "The exception type is often used together with a custom method, like in the example above." }, { "code": null, "e": 909, "s": 871, "text": "Differences between throw and throws:" }, { "code": null, "e": 951, "s": 909, "text": "throw is followed by an object (new type)" }, { "code": null, "e": 974, "s": 951, "text": "used inside the method" }, { "code": null, "e": 1004, "s": 974, "text": "throws is followed by a class" }, { "code": null, "e": 1039, "s": 1004, "text": "and used with the method signature" }, { "code": null, "e": 1099, "s": 1039, "text": "Read more about exceptions in our Java Try..Catch Tutorial." }, { "code": null, "e": 1117, "s": 1099, "text": "\n❮ Java Keywords\n" }, { "code": null, "e": 1150, "s": 1117, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1192, "s": 1150, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1299, "s": 1192, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1318, "s": 1299, "text": "help@w3schools.com" } ]
C++ function call by pointer
The call by pointer method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument. To pass the value by pointer, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to by its arguments. // function definition to swap the values. void swap(int *x, int *y) { int temp; temp = *x; /* save the value at address x */ *x = *y; /* put y into x */ *y = temp; /* put x into y */ return; } To check the more detail about C++ pointers, kindly check C++ Pointers chapter. For now, let us call the function swap() by passing values by pointer as in the following example − #include <iostream> using namespace std; // function declaration void swap(int *x, int *y); int main () { // local variable declaration: int a = 100; int b = 200; cout << "Before swap, value of a :" << a << endl; cout << "Before swap, value of b :" << b << endl; /* calling a function to swap the values. * &a indicates pointer to a ie. address of variable a and * &b indicates pointer to b ie. address of variable b. */ swap(&a, &b); cout << "After swap, value of a :" << a << endl; cout << "After swap, value of b :" << b << endl; return 0; } When the above code is put together in a file, compiled and executed, it produces the following result − Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :200 After swap, value of b :100 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2604, "s": 2318, "text": "The call by pointer method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument." }, { "code": null, "e": 2906, "s": 2604, "text": "To pass the value by pointer, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to by its arguments." }, { "code": null, "e": 3118, "s": 2906, "text": "// function definition to swap the values.\nvoid swap(int *x, int *y) {\n int temp;\n temp = *x; /* save the value at address x */\n *x = *y; /* put y into x */\n *y = temp; /* put x into y */\n \n return;\n}" }, { "code": null, "e": 3198, "s": 3118, "text": "To check the more detail about C++ pointers, kindly check C++ Pointers chapter." }, { "code": null, "e": 3298, "s": 3198, "text": "For now, let us call the function swap() by passing values by pointer as in the following example −" }, { "code": null, "e": 3897, "s": 3298, "text": "#include <iostream>\nusing namespace std;\n\n// function declaration\nvoid swap(int *x, int *y);\n\nint main () {\n // local variable declaration:\n int a = 100;\n int b = 200;\n \n cout << \"Before swap, value of a :\" << a << endl;\n cout << \"Before swap, value of b :\" << b << endl;\n\n /* calling a function to swap the values.\n * &a indicates pointer to a ie. address of variable a and \n * &b indicates pointer to b ie. address of variable b.\n */\n swap(&a, &b);\n\n cout << \"After swap, value of a :\" << a << endl;\n cout << \"After swap, value of b :\" << b << endl;\n \n return 0;\n}" }, { "code": null, "e": 4002, "s": 3897, "text": "When the above code is put together in a file, compiled and executed, it produces the following result −" }, { "code": null, "e": 4117, "s": 4002, "text": "Before swap, value of a :100\nBefore swap, value of b :200\nAfter swap, value of a :200\nAfter swap, value of b :100\n" }, { "code": null, "e": 4154, "s": 4117, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 4173, "s": 4154, "text": " Arnab Chakraborty" }, { "code": null, "e": 4205, "s": 4173, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 4228, "s": 4205, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 4264, "s": 4228, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 4281, "s": 4264, "text": " Frahaan Hussain" }, { "code": null, "e": 4316, "s": 4281, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4333, "s": 4316, "text": " Frahaan Hussain" }, { "code": null, "e": 4368, "s": 4333, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4385, "s": 4368, "text": " Frahaan Hussain" }, { "code": null, "e": 4420, "s": 4385, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4437, "s": 4420, "text": " Frahaan Hussain" }, { "code": null, "e": 4444, "s": 4437, "text": " Print" }, { "code": null, "e": 4455, "s": 4444, "text": " Add Notes" } ]
Word2Vec Explained. Explaining the Intuition of Word2Vec &... | by Vatsal | Towards Data Science
Table of Contents Introduction What is a Word Embedding? Word2Vec Architecture- CBOW (Continuous Bag of Words) Model- Continuous Skip-Gram Model Implementation- Data- Requirements- Import Data- Preprocess Data- Embed- PCA on Embeddings Concluding Remarks Resources Word2Vec is a recent breakthrough in the world of NLP. Tomas Mikolov a Czech computer scientist and currently a researcher at CIIRC ( Czech Institute of Informatics, Robotics and Cybernetics) was one of the leading contributors towards the research and implementation of word2vec. Word embeddings are an integral part of solving many problems in NLP. They depict how humans understand language to a machine. You can imagine them as a vectorized representation of text. Word2Vec, a common method of generating word embeddings, has a variety of applications such as text similarity, recommendation systems, sentiment analysis, etc. Before we get into word2vec, let’s establish an understanding of what word embeddings are. This is important to know because the overall result and output of word2vec will be embeddings associated to each unique word passed through the algorithm. Word embeddings is a technique where individual words are transformed into a numerical representation of the word (a vector). Where each word is mapped to one vector, this vector is then learned in a way which resembles a neural network. The vectors try to capture various characteristics of that word with regard to the overall text. These characteristics can include the semantic relationship of the word, definitions, context, etc. With these numerical representations, you can do many things like identify similarity or dissimilarity between words. Clearly, these are integral as inputs to various aspects of machine learning. A machine cannot process text in their raw form, thus converting the text into an embedding will allow users to feed the embedding to classic machine learning models. The simplest embedding would be a one hot encoding of text data where each vector would be mapped to a category. For example: have = [1, 0, 0, 0, 0, 0, ... 0]a = [0, 1, 0, 0, 0, 0, ... 0]good = [0, 0, 1, 0, 0, 0, ... 0]day = [0, 0, 0, 1, 0, 0, ... 0] ... However, there are multiple limitations of simple embeddings such as this, as they do not capture characteristics of the word, and they can be quite large depending on the size of the corpus. The effectiveness of Word2Vec comes from its ability to group together vectors of similar words. Given a large enough dataset, Word2Vec can make strong estimates about a words meaning based on their occurrences in the text. These estimates yield word associations with other words in the corpus. For example, words like “King” and “Queen” would be very similar with one another. When conducting algebraic operations on word embeddings you can find a close approximation of word similarities. For example, the 2 dimensional embedding vector of "king" - the 2 dimensional embedding vector of "man" + the 2 dimensional embedding vector of "woman" yielded a vector which is very close to the embedding vector of "queen". Note, that the values below were chosen arbitrarily. King - Man + Woman = Queen[5,3] - [2,1] + [3, 2] = [6,4] There are two main architectures which yield the success of word2vec. The skip-gram and CBOW architectures. This architecture is very similar to a feed forward neural network. This model architecture essentially tries to predict a target word from a list of context words. The intuition behind this model is quite simple, given a phrase "Have a great day" , we will chose our target word to be “a” and our context words to be [“have”, “great”, “day”]. What this model will do is take the distributed representations of the context words to try and predict the target word. The skip-gram model is a simple neural network with one hidden layer trained in order to predict the probability of a given word being present when an input word is present. Intuitively, you can imagine the skip-gram model being the opposite of the CBOW model. In this architecture, it takes the current word as an input and tries to accurately predict the words before and after this current word. This model essentially tries to learn and predict the context words around the specified input word. Based on experiments assessing the accuracy of this model it was found that the prediction quality improves given a large range of word vectors, however it also increases the computational complexity. The process can be described visually as seen below. As seen above, given some corpus of text, a target word is selected over some rolling window. The training data consists of pair wise combinations of that target word and all other words in the window. This is the resulting training data for the neural network. Once the model is trained, we can essentially yield a probability of a word being a context word for a given target. The following image below represents the architecture of the neural network for the skip-gram model. A corpus can be represented as a vector of size N, where each element in N corresponds to a word in the corpus. During the training process, we have a pair of target and context words, the input array will have 0 in all element except for the target word. The target word will be equal to 1. The hidden layer will learn the embedding representation of each word, yielding a d-dimensional embedding space. The output layer is a dense layer with a softmax activation function. The output layer will essentially yield a vector of the same size as the input, each element in the vector will consist of a probability. This probability indicates the similarity between the target word and the associated word in the corpus. For a more detailed overview of both these models, I highly recommend reading the original paper which outlined these results here. I’ll be showing how to use word2vec to generate word embeddings and use those embeddings for finding similar words and visualization of embeddings through PCA. For the purposes of this tutorial we’ll be working with the Shakespeare dataset. You can find the file I used for this tutorial here, it includes all the lines Shakespeare has written for his plays. nltk==3.6.1node2vec==0.4.3pandas==1.2.4matplotlib==3.3.4gensim==4.0.1scikit-learn=0.24.1 Note: Since we’re working with NLTK you might need to download the following corpus for the rest of the tutorial to work. This can easily be done by the following commands : import nltknltk.download('stopwords')nltk.download('punkt') Note: Change the PATH variable to the path of the data you’re working with. Stopword Filtering Note Be aware that the stopwords removed from these lines are of modern vocabulary. The application & data has a high importance to the type of preprocessing tactics necessary for cleaning of words. In our scenario, words like “you” or “yourself” would be present in the stopwords and eliminated from the lines, however since this is Shakespeare text data, these types of words would not be used. Instead “thou” or “thyself” might be useful to remove. Stay keen to these types of miniature changes because they make a drastic difference in the performance of a good model versus a poor one. For the purposes of this example, I won’t be going into extreme details in identifying stopwords from a different century, but be aware that you should. Tensorflow has made a very beautiful, intuitive and user friendly representation of the word2vec model. I highly recommend you to explore it as it allows you to interact with the results of word2vec. The link is below. projector.tensorflow.org Word embeddings are an essential part of solving many problems in NLP, it depicts how humans understand language to a machine. Given a large corpus of text, word2vec produces an embedding vector associated to each word in the corpus. These embeddings are structured such that words with similar characteristics are in close proximity of one another. CBOW (continuous bag of words) and the skip-gram model are the two main architectures associated to word2vec. Given an input word, skip-gram will try to predict the words in context to the input whereas the CBOW model will take a variety of words and try to predict the missing one. I’ve also written about node2vec which uses word2vec to generate node embeddings given a network. You can read about it here. towardsdatascience.com https://arxiv.org/pdf/1301.3781.pdf https://www.kdnuggets.com/2019/02/word-embeddings-nlp-applications.html https://wiki.pathmind.com/word2vec https://projector.tensorflow.org/ If you enjoyed reading this article, please consider following me for upcoming articles explaining other data science materials and those materials (like word2vec) to solve relevant problems in different areas of data science. Here are some other articles I’ve written which I think you might enjoy.
[ { "code": null, "e": 190, "s": 172, "text": "Table of Contents" }, { "code": null, "e": 203, "s": 190, "text": "Introduction" }, { "code": null, "e": 229, "s": 203, "text": "What is a Word Embedding?" }, { "code": null, "e": 317, "s": 229, "text": "Word2Vec Architecture- CBOW (Continuous Bag of Words) Model- Continuous Skip-Gram Model" }, { "code": null, "e": 408, "s": 317, "text": "Implementation- Data- Requirements- Import Data- Preprocess Data- Embed- PCA on Embeddings" }, { "code": null, "e": 427, "s": 408, "text": "Concluding Remarks" }, { "code": null, "e": 437, "s": 427, "text": "Resources" }, { "code": null, "e": 1067, "s": 437, "text": "Word2Vec is a recent breakthrough in the world of NLP. Tomas Mikolov a Czech computer scientist and currently a researcher at CIIRC ( Czech Institute of Informatics, Robotics and Cybernetics) was one of the leading contributors towards the research and implementation of word2vec. Word embeddings are an integral part of solving many problems in NLP. They depict how humans understand language to a machine. You can imagine them as a vectorized representation of text. Word2Vec, a common method of generating word embeddings, has a variety of applications such as text similarity, recommendation systems, sentiment analysis, etc." }, { "code": null, "e": 1314, "s": 1067, "text": "Before we get into word2vec, let’s establish an understanding of what word embeddings are. This is important to know because the overall result and output of word2vec will be embeddings associated to each unique word passed through the algorithm." }, { "code": null, "e": 1867, "s": 1314, "text": "Word embeddings is a technique where individual words are transformed into a numerical representation of the word (a vector). Where each word is mapped to one vector, this vector is then learned in a way which resembles a neural network. The vectors try to capture various characteristics of that word with regard to the overall text. These characteristics can include the semantic relationship of the word, definitions, context, etc. With these numerical representations, you can do many things like identify similarity or dissimilarity between words." }, { "code": null, "e": 2225, "s": 1867, "text": "Clearly, these are integral as inputs to various aspects of machine learning. A machine cannot process text in their raw form, thus converting the text into an embedding will allow users to feed the embedding to classic machine learning models. The simplest embedding would be a one hot encoding of text data where each vector would be mapped to a category." }, { "code": null, "e": 2371, "s": 2225, "text": "For example: have = [1, 0, 0, 0, 0, 0, ... 0]a = [0, 1, 0, 0, 0, 0, ... 0]good = [0, 0, 1, 0, 0, 0, ... 0]day = [0, 0, 0, 1, 0, 0, ... 0] ..." }, { "code": null, "e": 2563, "s": 2371, "text": "However, there are multiple limitations of simple embeddings such as this, as they do not capture characteristics of the word, and they can be quite large depending on the size of the corpus." }, { "code": null, "e": 3333, "s": 2563, "text": "The effectiveness of Word2Vec comes from its ability to group together vectors of similar words. Given a large enough dataset, Word2Vec can make strong estimates about a words meaning based on their occurrences in the text. These estimates yield word associations with other words in the corpus. For example, words like “King” and “Queen” would be very similar with one another. When conducting algebraic operations on word embeddings you can find a close approximation of word similarities. For example, the 2 dimensional embedding vector of \"king\" - the 2 dimensional embedding vector of \"man\" + the 2 dimensional embedding vector of \"woman\" yielded a vector which is very close to the embedding vector of \"queen\". Note, that the values below were chosen arbitrarily." }, { "code": null, "e": 3424, "s": 3333, "text": "King - Man + Woman = Queen[5,3] - [2,1] + [3, 2] = [6,4] " }, { "code": null, "e": 3532, "s": 3424, "text": "There are two main architectures which yield the success of word2vec. The skip-gram and CBOW architectures." }, { "code": null, "e": 3997, "s": 3532, "text": "This architecture is very similar to a feed forward neural network. This model architecture essentially tries to predict a target word from a list of context words. The intuition behind this model is quite simple, given a phrase \"Have a great day\" , we will chose our target word to be “a” and our context words to be [“have”, “great”, “day”]. What this model will do is take the distributed representations of the context words to try and predict the target word." }, { "code": null, "e": 4751, "s": 3997, "text": "The skip-gram model is a simple neural network with one hidden layer trained in order to predict the probability of a given word being present when an input word is present. Intuitively, you can imagine the skip-gram model being the opposite of the CBOW model. In this architecture, it takes the current word as an input and tries to accurately predict the words before and after this current word. This model essentially tries to learn and predict the context words around the specified input word. Based on experiments assessing the accuracy of this model it was found that the prediction quality improves given a large range of word vectors, however it also increases the computational complexity. The process can be described visually as seen below." }, { "code": null, "e": 5231, "s": 4751, "text": "As seen above, given some corpus of text, a target word is selected over some rolling window. The training data consists of pair wise combinations of that target word and all other words in the window. This is the resulting training data for the neural network. Once the model is trained, we can essentially yield a probability of a word being a context word for a given target. The following image below represents the architecture of the neural network for the skip-gram model." }, { "code": null, "e": 5949, "s": 5231, "text": "A corpus can be represented as a vector of size N, where each element in N corresponds to a word in the corpus. During the training process, we have a pair of target and context words, the input array will have 0 in all element except for the target word. The target word will be equal to 1. The hidden layer will learn the embedding representation of each word, yielding a d-dimensional embedding space. The output layer is a dense layer with a softmax activation function. The output layer will essentially yield a vector of the same size as the input, each element in the vector will consist of a probability. This probability indicates the similarity between the target word and the associated word in the corpus." }, { "code": null, "e": 6081, "s": 5949, "text": "For a more detailed overview of both these models, I highly recommend reading the original paper which outlined these results here." }, { "code": null, "e": 6241, "s": 6081, "text": "I’ll be showing how to use word2vec to generate word embeddings and use those embeddings for finding similar words and visualization of embeddings through PCA." }, { "code": null, "e": 6440, "s": 6241, "text": "For the purposes of this tutorial we’ll be working with the Shakespeare dataset. You can find the file I used for this tutorial here, it includes all the lines Shakespeare has written for his plays." }, { "code": null, "e": 6529, "s": 6440, "text": "nltk==3.6.1node2vec==0.4.3pandas==1.2.4matplotlib==3.3.4gensim==4.0.1scikit-learn=0.24.1" }, { "code": null, "e": 6703, "s": 6529, "text": "Note: Since we’re working with NLTK you might need to download the following corpus for the rest of the tutorial to work. This can easily be done by the following commands :" }, { "code": null, "e": 6763, "s": 6703, "text": "import nltknltk.download('stopwords')nltk.download('punkt')" }, { "code": null, "e": 6839, "s": 6763, "text": "Note: Change the PATH variable to the path of the data you’re working with." }, { "code": null, "e": 6863, "s": 6839, "text": "Stopword Filtering Note" }, { "code": null, "e": 7057, "s": 6863, "text": "Be aware that the stopwords removed from these lines are of modern vocabulary. The application & data has a high importance to the type of preprocessing tactics necessary for cleaning of words." }, { "code": null, "e": 7449, "s": 7057, "text": "In our scenario, words like “you” or “yourself” would be present in the stopwords and eliminated from the lines, however since this is Shakespeare text data, these types of words would not be used. Instead “thou” or “thyself” might be useful to remove. Stay keen to these types of miniature changes because they make a drastic difference in the performance of a good model versus a poor one." }, { "code": null, "e": 7602, "s": 7449, "text": "For the purposes of this example, I won’t be going into extreme details in identifying stopwords from a different century, but be aware that you should." }, { "code": null, "e": 7821, "s": 7602, "text": "Tensorflow has made a very beautiful, intuitive and user friendly representation of the word2vec model. I highly recommend you to explore it as it allows you to interact with the results of word2vec. The link is below." }, { "code": null, "e": 7846, "s": 7821, "text": "projector.tensorflow.org" }, { "code": null, "e": 8479, "s": 7846, "text": "Word embeddings are an essential part of solving many problems in NLP, it depicts how humans understand language to a machine. Given a large corpus of text, word2vec produces an embedding vector associated to each word in the corpus. These embeddings are structured such that words with similar characteristics are in close proximity of one another. CBOW (continuous bag of words) and the skip-gram model are the two main architectures associated to word2vec. Given an input word, skip-gram will try to predict the words in context to the input whereas the CBOW model will take a variety of words and try to predict the missing one." }, { "code": null, "e": 8605, "s": 8479, "text": "I’ve also written about node2vec which uses word2vec to generate node embeddings given a network. You can read about it here." }, { "code": null, "e": 8628, "s": 8605, "text": "towardsdatascience.com" }, { "code": null, "e": 8664, "s": 8628, "text": "https://arxiv.org/pdf/1301.3781.pdf" }, { "code": null, "e": 8736, "s": 8664, "text": "https://www.kdnuggets.com/2019/02/word-embeddings-nlp-applications.html" }, { "code": null, "e": 8771, "s": 8736, "text": "https://wiki.pathmind.com/word2vec" }, { "code": null, "e": 8805, "s": 8771, "text": "https://projector.tensorflow.org/" } ]
Python | Equidistant element list - GeeksforGeeks
03 Oct, 2019 Sometimes, while working with Python list we can have a problem in which we need to construct the list in which the range is auto computed using the start, end and length parameters. The solution of this problem can have many applications. Let’s discuss a way in which this task can be performed. Method : Using list comprehensionThis task can be performed using list comprehension, shorthand for the loop version of logic. In this, we just compute the range using division manipulation and extend it to increasing list forming equidistant list. # Python3 code to demonstrate working of# Equidistant element list# using list comprehension # initializing start value strt = 5 # initializing end value end = 10 # initializing lengthlength = 8 # Equidistant element list# using list comprehensiontest_list = [strt + x * (end - strt)/length for x in range(length)] # Printing resultprint("The Equidistant list is : " + str(test_list)) The Equidistant list is : [5.0, 5.625, 6.25, 6.875, 7.5, 8.125, 8.75, 9.375] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Bar Plot in Matplotlib Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Split string into list of characters Python Program for Binary Search (Recursive and Iterative)
[ { "code": null, "e": 23901, "s": 23873, "text": "\n03 Oct, 2019" }, { "code": null, "e": 24198, "s": 23901, "text": "Sometimes, while working with Python list we can have a problem in which we need to construct the list in which the range is auto computed using the start, end and length parameters. The solution of this problem can have many applications. Let’s discuss a way in which this task can be performed." }, { "code": null, "e": 24447, "s": 24198, "text": "Method : Using list comprehensionThis task can be performed using list comprehension, shorthand for the loop version of logic. In this, we just compute the range using division manipulation and extend it to increasing list forming equidistant list." }, { "code": "# Python3 code to demonstrate working of# Equidistant element list# using list comprehension # initializing start value strt = 5 # initializing end value end = 10 # initializing lengthlength = 8 # Equidistant element list# using list comprehensiontest_list = [strt + x * (end - strt)/length for x in range(length)] # Printing resultprint(\"The Equidistant list is : \" + str(test_list))", "e": 24837, "s": 24447, "text": null }, { "code": null, "e": 24917, "s": 24837, "text": " \nThe Equidistant list is : [5.0, 5.625, 6.25, 6.875, 7.5, 8.125, 8.75, 9.375]\n" }, { "code": null, "e": 24938, "s": 24917, "text": "Python list-programs" }, { "code": null, "e": 24945, "s": 24938, "text": "Python" }, { "code": null, "e": 24961, "s": 24945, "text": "Python Programs" }, { "code": null, "e": 25059, "s": 24961, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25068, "s": 25059, "text": "Comments" }, { "code": null, "e": 25081, "s": 25068, "text": "Old Comments" }, { "code": null, "e": 25117, "s": 25081, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 25140, "s": 25117, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 25179, "s": 25140, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25212, "s": 25179, "text": "Python | Convert set into a list" }, { "code": null, "e": 25261, "s": 25212, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 25283, "s": 25261, "text": "Defaultdict in Python" }, { "code": null, "e": 25322, "s": 25283, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25360, "s": 25322, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 25406, "s": 25360, "text": "Python | Split string into list of characters" } ]
Jupyter Magics with SQL. Jupyter/IPython notebooks can be used... | by Sayat Satybaldiyev | Towards Data Science
Jupyter/IPython notebooks can be used for an interactive data analysis with SQL on a relational database. This fuses together the advantages of using Jupyter, a well-established platform for data analysis, with the ease of use of SQL and the performance of SQL engines. Jupyter magic functions allow you to replace a boilerplate code snippets with more concise one. Let’s explore Jupyter SQL magic that allows us to interact with Presto or any other relational databases. Magic functions are pre-defined functions(“magics”) in Jupyter kernel that executes supplied commands. There are two kinds of magics line-oriented and cell-oriented prefaced with % and %% respectively. To see the difference we start comparing code examples using magics functions and without. Ultimately, two statements achieves the same result. Let’s start creating connection with SQLAchemy to fetch last executed query and put it to data-frame. import pandas as pd from sqlalchemy.engine import create_engine # Presto engine = create_engine('presto://localhost:8080/system/runtime') #Read Presto Data query into a DataFrame df = pd.read_sql('select * from queries limit 1', engine) df.head() This is how would we do it in case we have enabled SQL magic functions. pd = %sql select * from runtime.queries limit 1 pd.DataFrame().head() * presto://user@localhost:8080/system Done. The examples use Prestodb as a SQL engine. However, the approach can be extended to any engine that compatible with Python SQLAlchemy and has driver implementing Python DB 2.0 Specification. To enable the magic we need an ipython-sql library. The examples further are mostly adopted from the ipython-sql official repository. pip install pandaspip install sqlalchemy # ORM for databasespip install ipython-sql # SQL magic function To work with Prestodb we will need to have PyHive library. SQLAlchemy under the hood will use the library to make a connection and submit SQL queries. For other engines, you need to install a proper driver i.e. PostgresSQL, MySQL. pip install pyhive[presto] # DB driver library The ipython-sql library is loaded using the %load_ext iPython extension syntax and is pointed to the connection object as follows: %load_ext sql%config SqlMagic.autocommit=False # for engines that do not support autommit Please note that for Presto, Impala and some other engines you need to disable autocommit feature. This is done via SqlMagic config property. To list all options of config you can run in the cell: %config SqlMagic To connect to the database you need to pass connection string in SQLAlchemy format to the %sql function. %sql presto://user@localhost:8080/system If connection string is not provided and connection has not been made yet, ipython-sql tries to get connection information from DATABASE_URLenvironment variable. You can export environment variable DATABASE_URL in ~/.bashrc in case your connection information is static. %env is another magic function that sets environment variables. %env DATABASE_URL=presto://user@localhost:8080/system%sql SELECT 1 as "Test" In case of multiple SQL engines, and you want to combine data from them you can pass connection string with each query of the magic function in cell-mode. %%sql user@jmxSHOW SCHEMAS Parameter substitution is a handy feature that allows defining SQL query parameters at query run-time. It makes code less fragile and expressive. The parameter needs to be defined in the local scope and prefixed with colon i.e. :parameter state='FINISHED' %sql SELECT :state as "bind_variable" Done. Ordinary IPython assignment works for single-line %sql queries: result = %sql select query_id, state from runtime.queries limit 1 For multi-line query you need to use << syntax. %%sql result_set << SELECT query_id, state, query FROM runtime.queriesLIMIT 2 SQL magic has a nice integration with pandas library. Result from SQL query can be converted to regular pandas data frame via DataFrame call. You should also consider reading about build-in magic functions that allows you to achieve more and type less! You can also take a look at the full notebook with the examples from the post.
[ { "code": null, "e": 317, "s": 47, "text": "Jupyter/IPython notebooks can be used for an interactive data analysis with SQL on a relational database. This fuses together the advantages of using Jupyter, a well-established platform for data analysis, with the ease of use of SQL and the performance of SQL engines." }, { "code": null, "e": 519, "s": 317, "text": "Jupyter magic functions allow you to replace a boilerplate code snippets with more concise one. Let’s explore Jupyter SQL magic that allows us to interact with Presto or any other relational databases." }, { "code": null, "e": 721, "s": 519, "text": "Magic functions are pre-defined functions(“magics”) in Jupyter kernel that executes supplied commands. There are two kinds of magics line-oriented and cell-oriented prefaced with % and %% respectively." }, { "code": null, "e": 865, "s": 721, "text": "To see the difference we start comparing code examples using magics functions and without. Ultimately, two statements achieves the same result." }, { "code": null, "e": 967, "s": 865, "text": "Let’s start creating connection with SQLAchemy to fetch last executed query and put it to data-frame." }, { "code": null, "e": 1218, "s": 967, "text": "import pandas as pd\nfrom sqlalchemy.engine import create_engine\n\n# Presto\nengine = create_engine('presto://localhost:8080/system/runtime') \n\n#Read Presto Data query into a DataFrame\ndf = pd.read_sql('select * from queries limit 1', engine)\ndf.head()\n" }, { "code": null, "e": 1290, "s": 1218, "text": "This is how would we do it in case we have enabled SQL magic functions." }, { "code": null, "e": 1361, "s": 1290, "text": "pd = %sql select * from runtime.queries limit 1\npd.DataFrame().head()\n" }, { "code": null, "e": 1407, "s": 1361, "text": " * presto://user@localhost:8080/system\nDone.\n" }, { "code": null, "e": 1732, "s": 1407, "text": "The examples use Prestodb as a SQL engine. However, the approach can be extended to any engine that compatible with Python SQLAlchemy and has driver implementing Python DB 2.0 Specification. To enable the magic we need an ipython-sql library. The examples further are mostly adopted from the ipython-sql official repository." }, { "code": null, "e": 1837, "s": 1732, "text": "pip install pandaspip install sqlalchemy # ORM for databasespip install ipython-sql # SQL magic function" }, { "code": null, "e": 2068, "s": 1837, "text": "To work with Prestodb we will need to have PyHive library. SQLAlchemy under the hood will use the library to make a connection and submit SQL queries. For other engines, you need to install a proper driver i.e. PostgresSQL, MySQL." }, { "code": null, "e": 2115, "s": 2068, "text": "pip install pyhive[presto] # DB driver library" }, { "code": null, "e": 2246, "s": 2115, "text": "The ipython-sql library is loaded using the %load_ext iPython extension syntax and is pointed to the connection object as follows:" }, { "code": null, "e": 2336, "s": 2246, "text": "%load_ext sql%config SqlMagic.autocommit=False # for engines that do not support autommit" }, { "code": null, "e": 2550, "s": 2336, "text": "Please note that for Presto, Impala and some other engines you need to disable autocommit feature. This is done via SqlMagic config property. To list all options of config you can run in the cell: %config SqlMagic" }, { "code": null, "e": 2655, "s": 2550, "text": "To connect to the database you need to pass connection string in SQLAlchemy format to the %sql function." }, { "code": null, "e": 2696, "s": 2655, "text": "%sql presto://user@localhost:8080/system" }, { "code": null, "e": 3031, "s": 2696, "text": "If connection string is not provided and connection has not been made yet, ipython-sql tries to get connection information from DATABASE_URLenvironment variable. You can export environment variable DATABASE_URL in ~/.bashrc in case your connection information is static. %env is another magic function that sets environment variables." }, { "code": null, "e": 3108, "s": 3031, "text": "%env DATABASE_URL=presto://user@localhost:8080/system%sql SELECT 1 as \"Test\"" }, { "code": null, "e": 3263, "s": 3108, "text": "In case of multiple SQL engines, and you want to combine data from them you can pass connection string with each query of the magic function in cell-mode." }, { "code": null, "e": 3290, "s": 3263, "text": "%%sql user@jmxSHOW SCHEMAS" }, { "code": null, "e": 3529, "s": 3290, "text": "Parameter substitution is a handy feature that allows defining SQL query parameters at query run-time. It makes code less fragile and expressive. The parameter needs to be defined in the local scope and prefixed with colon i.e. :parameter" }, { "code": null, "e": 3585, "s": 3529, "text": "state='FINISHED'\n%sql SELECT :state as \"bind_variable\"\n" }, { "code": null, "e": 3592, "s": 3585, "text": "Done.\n" }, { "code": null, "e": 3656, "s": 3592, "text": "Ordinary IPython assignment works for single-line %sql queries:" }, { "code": null, "e": 3722, "s": 3656, "text": "result = %sql select query_id, state from runtime.queries limit 1" }, { "code": null, "e": 3770, "s": 3722, "text": "For multi-line query you need to use << syntax." }, { "code": null, "e": 3848, "s": 3770, "text": "%%sql result_set << SELECT query_id, state, query FROM runtime.queriesLIMIT 2" }, { "code": null, "e": 3990, "s": 3848, "text": "SQL magic has a nice integration with pandas library. Result from SQL query can be converted to regular pandas data frame via DataFrame call." } ]
How to dynamically update a plot in a loop in Ipython notebook?
We can iterate a plot using display.clear_output(wait=True), display.display(pl.gcf()) and time.sleep() methods in a loop to get the exact output. Plot a sample (or samples) from the "standard normal" distribution using pylab.randn(). Plot a sample (or samples) from the "standard normal" distribution using pylab.randn(). Clear the output of the current cell receiving output, wait=False(default value), wait to clear the output until new output is available to replace it. Clear the output of the current cell receiving output, wait=False(default value), wait to clear the output until new output is available to replace it. Display a Python object in all frontends. By default, all representations will be computed and sent to the frontends. Frontends can decide which representation is used and how, using the display() method. pl.gcf helps to get the current figure. Display a Python object in all frontends. By default, all representations will be computed and sent to the frontends. Frontends can decide which representation is used and how, using the display() method. pl.gcf helps to get the current figure. To sleep for a while, use time.sleep() method. To sleep for a while, use time.sleep() method. import time import pylab as pl from IPython import display for i in range(2): pl.plot(pl.randn(100)) display.clear_output(wait=True) display.display(pl.gcf()) time.sleep(1.0) Figure(640x480) Figure(640x480)
[ { "code": null, "e": 1209, "s": 1062, "text": "We can iterate a plot using display.clear_output(wait=True), display.display(pl.gcf()) and time.sleep() methods in a loop to get the exact output." }, { "code": null, "e": 1297, "s": 1209, "text": "Plot a sample (or samples) from the \"standard normal\" distribution using pylab.randn()." }, { "code": null, "e": 1385, "s": 1297, "text": "Plot a sample (or samples) from the \"standard normal\" distribution using pylab.randn()." }, { "code": null, "e": 1537, "s": 1385, "text": "Clear the output of the current cell receiving output, wait=False(default value), wait to clear the output until new output is available to replace it." }, { "code": null, "e": 1689, "s": 1537, "text": "Clear the output of the current cell receiving output, wait=False(default value), wait to clear the output until new output is available to replace it." }, { "code": null, "e": 1934, "s": 1689, "text": "Display a Python object in all frontends. By default, all representations will be computed and sent to the frontends. Frontends can decide which representation is used and how, using the display() method. pl.gcf helps to get the current figure." }, { "code": null, "e": 2179, "s": 1934, "text": "Display a Python object in all frontends. By default, all representations will be computed and sent to the frontends. Frontends can decide which representation is used and how, using the display() method. pl.gcf helps to get the current figure." }, { "code": null, "e": 2226, "s": 2179, "text": "To sleep for a while, use time.sleep() method." }, { "code": null, "e": 2273, "s": 2226, "text": "To sleep for a while, use time.sleep() method." }, { "code": null, "e": 2460, "s": 2273, "text": "import time\nimport pylab as pl\nfrom IPython import display\nfor i in range(2):\n pl.plot(pl.randn(100))\n display.clear_output(wait=True)\n display.display(pl.gcf())\n time.sleep(1.0)" }, { "code": null, "e": 2492, "s": 2460, "text": "Figure(640x480)\nFigure(640x480)" } ]
How to Get the Current Working Directory in Golang? - GeeksforGeeks
10 May, 2020 Getwd functionis used to get the current working directory in Golang, the function returns the rooted path name and if the current directory can be reached via multiple paths, the function can return any one of them. Syntax: func Getwd()(dir string, err error) The func returns two things the directory and also error, if there is no error it returns nil. // Golang code for printing// current working directory package main import ( "fmt" "os") func main() { // using the function mydir, err := os.Getwd() if err != nil { fmt.Println(err) } fmt.Println(mydir)} Output: users/home/desktop You may get different outputs on online compilers. For better understanding, use the offline compiler. Golang-Program Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Parse JSON in Golang? Defer Keyword in Golang Loops in Go Language time.Parse() Function in Golang With Examples Anonymous function in Go Language Time Durations in Golang Structures in Golang Strings in Golang How to iterate over an Array using for loop in Golang? Rune in Golang
[ { "code": null, "e": 24460, "s": 24432, "text": "\n10 May, 2020" }, { "code": null, "e": 24677, "s": 24460, "text": "Getwd functionis used to get the current working directory in Golang, the function returns the rooted path name and if the current directory can be reached via multiple paths, the function can return any one of them." }, { "code": null, "e": 24685, "s": 24677, "text": "Syntax:" }, { "code": null, "e": 24721, "s": 24685, "text": "func Getwd()(dir string, err error)" }, { "code": null, "e": 24816, "s": 24721, "text": "The func returns two things the directory and also error, if there is no error it returns nil." }, { "code": "// Golang code for printing// current working directory package main import ( \"fmt\" \"os\") func main() { // using the function mydir, err := os.Getwd() if err != nil { fmt.Println(err) } fmt.Println(mydir)}", "e": 25055, "s": 24816, "text": null }, { "code": null, "e": 25063, "s": 25055, "text": "Output:" }, { "code": null, "e": 25082, "s": 25063, "text": "users/home/desktop" }, { "code": null, "e": 25185, "s": 25082, "text": "You may get different outputs on online compilers. For better understanding, use the offline compiler." }, { "code": null, "e": 25200, "s": 25185, "text": "Golang-Program" }, { "code": null, "e": 25207, "s": 25200, "text": "Picked" }, { "code": null, "e": 25219, "s": 25207, "text": "Go Language" }, { "code": null, "e": 25317, "s": 25219, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25326, "s": 25317, "text": "Comments" }, { "code": null, "e": 25339, "s": 25326, "text": "Old Comments" }, { "code": null, "e": 25368, "s": 25339, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 25392, "s": 25368, "text": "Defer Keyword in Golang" }, { "code": null, "e": 25413, "s": 25392, "text": "Loops in Go Language" }, { "code": null, "e": 25459, "s": 25413, "text": "time.Parse() Function in Golang With Examples" }, { "code": null, "e": 25493, "s": 25459, "text": "Anonymous function in Go Language" }, { "code": null, "e": 25518, "s": 25493, "text": "Time Durations in Golang" }, { "code": null, "e": 25539, "s": 25518, "text": "Structures in Golang" }, { "code": null, "e": 25557, "s": 25539, "text": "Strings in Golang" }, { "code": null, "e": 25612, "s": 25557, "text": "How to iterate over an Array using for loop in Golang?" } ]
Cosine Similarity Matrix using broadcasting in Python | by Andrea Grianti | Towards Data Science
Learn how to code a (almost) one liner python function to calculate (manually) cosine similarity or correlation matrices used in many data science algorithms using the broadcasting feature of numpy library in Python. Do you think we can say that a professional MotoGP rider and the kid in the picture have the same passion for motorsports even if they will never meet and are different in all the other aspects of their life ? If you think yes then you grasped the idea of cosine similarity and correlation. Now suppose you work for a pay tv channel and you have the results of a survey from two groups of subscribers. One of the anaysis could be about the similarities of tastes between the two groups. For this type of analysis we are interested to select people sharing similar behaviours regardless of “how much time” they watch TV. This is well represented by the concept of cosine similarity which allow to consider as “close” those ‘observations’ aligned to some interesting for us directions regardless of how different the magnitude of the measures are from each other . So as an example if “person A” watches 10 hours of sport and 4 hours movies and “person B” watches 5 hours of sport, 2 hours movies, we can see the twos are (perfectly in this case) aligned given the fact that regardless of how many hours in total they watch TV, in proportion they share the same behaviours. By contrast if the objective is to analyse those watching similar number of hours in an interval, the euclidean distance would have been more appropriate as that evaluates the distance as we are used normally to think. It’s rather intuitive from the chart below to see this comparing the two points A and B with the length of segment f=10 (euclidean distance) with cosine of angle alpha = 0.9487 which oscillates between 1 and -1 where 1 means same direction same orientation, -1 same direction but opposite orientation. If the orientation is not important in our analysis the module of cosine would null this effect and consider +1 the same as -1. In terms of formulas cosine similarity is related to Pearson’s correlation coefficient by almost the same formula as cosine similarity is Pearson’s correlation when vectors are centered on their mean: The generalization of the cosine similarity concept when we have many points in a data matrix A to be compared with themselves (cosine similarity matrix using A vs. A) or to be compared with points in a second data matrix B (cosine similarity matrix of A vs. B with the same number of dimensions) is the same problem. So to make things different from usual we want to calculate the Cosine Similarity Matrix of a group of points A vs. a second group of points B, both with same number of variables (columns) like this: Assuming the vectors to be compared are in the rows of A and B the Cosine Similarity Matrix would appear as follows where each cell is cosine of the angle between all the vectors of A (rows) with all the vectors of B (columns): If you look at the color pattern you see that first vectors “a” replicate itself by row, while vectors “b” replicates itself by columns. To calculate this matrix in (almost) one line of code we need to look for a way to use what we know of algebra for numerator and denominator and then put it all together. Cell Numerator: If we keep A matrix fixed (3,3) we have to operate a ‘dot’ product with the transpose of B [=> (5,3)] and we get a (3,3) result. In python this is easy with: num=np.dot(A,B.T) Cell Denominator: It ’s a simple multiplication between 2 numbers but first we have to calculate the length of the two vectors. Let’s find a way to do that in a few Python lines using the numpy broadcasting operation which is a smart way to solve this problem. To calculate the lengths of vectors in A (and B) we should do this: square the elements of matrix Asum the values by rowroot square the values out of point 2 square the elements of matrix A sum the values by row root square the values out of point 2 In the above case where A=(3,3) and B=(5,3) the two lines below (remember that axis=1 means ‘by row’) return two arrays (not matrices !): p1=np.sqrt(np.sum(A**2,axis=1)) # array with 3 elements (it’s not a matrix)p2=np.sqrt(np.sum(B**2,axis=1)) # array with 5 elements (it’s not a matrix) If we just multiply them together it doesn’t work because the ‘*’ works element by element and the shapes as you see are different. Because ‘*’ operation is element by element we want two matrices where the first has the vector p1 vertical and copied in width p2 times, while p2 is horizontal and copied in height p1 times. To do this with ‘broadcasting’ we have to modify p1 so that it becomes fixed in vertical (a1,a2,a3) but “elastic” in a second dimension. The same with p2 so that becomes fixed in horizontal and “elastic” in a second dimension. To achieve this we leverage the np.newaxis function with this: p1=np.sqrt(np.sum(A**2,axis=1))[:,np.newaxis]p2=np.sqrt(np.sum(B**2,axis=1))[np.newaxis,:] p1 can be read like: make the vector vertical (:) and add a column dimension and p2 can be read like: add a row dimension, make the vector horizontal. This operation for p2 in theory is not necessary because p2 was already horizontal and even if it was an array, multiplying a matrix (p1) by an array (p2) results in a matrix (if they are compatible of course) but I like the above because more clean and flexible to changes. Now if you look p1 and p2 before and after you will notice that p1 is now a matrix and so p2 but still one dimensional. If you now multiply them with p1*p2 then the magic happens and the result is a 3x5 matrix like the p1*p2 in grey in the above picture. So we can now finalize the (almost) one liner for our cosine similarity matrix with this example complete of some data for A and B: import numpy as npA=np.array([[2,2,3],[1,0,4],[6,9,7]])B=np.array([[1,5,2],[6,6,4],[1,10,7],[5,8,2],[3,0,6]])def csm(A,B): num=np.dot(A,B.T) p1=np.sqrt(np.sum(A**2,axis=1))[:,np.newaxis] p2=np.sqrt(np.sum(B**2,axis=1))[np.newaxis,:]return num/(p1*p2)print(csm(A,B)) In case you want to modify the function to use it to calculate the correlation matrix the only difference is that you should subtract from the original matrices A and B their mean by row and also in this case you can leverage the np.newaxis function. In this case you first calculate the vector of the means by row as you’d usually do but remember that the result is again a horizontal vector and you cannot proceed with the code below B-B.mean(axis=1)A-A.mean(axis=1) We must make the means vector of A compatible with the matrix A by verticalizing and copying the now column vector the width of A times and the same for B. For this we can use again the broadcasting feature in Python “verticalizing” the vector (using ‘:’) and creating a new (elastic) dimension for columns. B=B-B.mean(axis=1)[:,np.newaxis]A=A-A.mean(axis=1)[:,np.newaxis] Now we can modify our function including a boolean where if it’s True it calculates the correlation matrix between A and B while if it’s False calculate the cosine similarity matrix: import numpy as npA=np.array([[1,2,3],[5,0,4],[6,9,7]])B=np.array([[4,0,9],[1,5,4],[2,8,6],[3,2,7],[5,9,4]])def csm(A,B,corr): if corr: B=B-B.mean(axis=1)[:,np.newaxis] A=A-A.mean(axis=1)[:,np.newaxis] num=np.dot(A,B.T) p1=np.sqrt(np.sum(A**2,axis=1))[:,np.newaxis] p2=np.sqrt(np.sum(B**2,axis=1))[np.newaxis,:]return num/(p1*p2)print(csm(A,B,True)) Note that if you use this function to calculate the correlation matrix the result is similar to the numpy function np.corrcoef(A,B) with the difference that the numpy function calculates also the correlation of A with A and B with B which could be redundant and force you to cut out the parts you don’t need. For example the correlation of A with B is in the submatrix top right which can be cut out knowing the shapes of A and B and working with indices. Of course there are many methods to do the same thing described here including other libraries and functions but the np.newaxis is quite smart and in this example I hope I helped you in that ... direction
[ { "code": null, "e": 388, "s": 171, "text": "Learn how to code a (almost) one liner python function to calculate (manually) cosine similarity or correlation matrices used in many data science algorithms using the broadcasting feature of numpy library in Python." }, { "code": null, "e": 679, "s": 388, "text": "Do you think we can say that a professional MotoGP rider and the kid in the picture have the same passion for motorsports even if they will never meet and are different in all the other aspects of their life ? If you think yes then you grasped the idea of cosine similarity and correlation." }, { "code": null, "e": 1251, "s": 679, "text": "Now suppose you work for a pay tv channel and you have the results of a survey from two groups of subscribers. One of the anaysis could be about the similarities of tastes between the two groups. For this type of analysis we are interested to select people sharing similar behaviours regardless of “how much time” they watch TV. This is well represented by the concept of cosine similarity which allow to consider as “close” those ‘observations’ aligned to some interesting for us directions regardless of how different the magnitude of the measures are from each other ." }, { "code": null, "e": 1560, "s": 1251, "text": "So as an example if “person A” watches 10 hours of sport and 4 hours movies and “person B” watches 5 hours of sport, 2 hours movies, we can see the twos are (perfectly in this case) aligned given the fact that regardless of how many hours in total they watch TV, in proportion they share the same behaviours." }, { "code": null, "e": 1779, "s": 1560, "text": "By contrast if the objective is to analyse those watching similar number of hours in an interval, the euclidean distance would have been more appropriate as that evaluates the distance as we are used normally to think." }, { "code": null, "e": 2081, "s": 1779, "text": "It’s rather intuitive from the chart below to see this comparing the two points A and B with the length of segment f=10 (euclidean distance) with cosine of angle alpha = 0.9487 which oscillates between 1 and -1 where 1 means same direction same orientation, -1 same direction but opposite orientation." }, { "code": null, "e": 2209, "s": 2081, "text": "If the orientation is not important in our analysis the module of cosine would null this effect and consider +1 the same as -1." }, { "code": null, "e": 2410, "s": 2209, "text": "In terms of formulas cosine similarity is related to Pearson’s correlation coefficient by almost the same formula as cosine similarity is Pearson’s correlation when vectors are centered on their mean:" }, { "code": null, "e": 2728, "s": 2410, "text": "The generalization of the cosine similarity concept when we have many points in a data matrix A to be compared with themselves (cosine similarity matrix using A vs. A) or to be compared with points in a second data matrix B (cosine similarity matrix of A vs. B with the same number of dimensions) is the same problem." }, { "code": null, "e": 2928, "s": 2728, "text": "So to make things different from usual we want to calculate the Cosine Similarity Matrix of a group of points A vs. a second group of points B, both with same number of variables (columns) like this:" }, { "code": null, "e": 3156, "s": 2928, "text": "Assuming the vectors to be compared are in the rows of A and B the Cosine Similarity Matrix would appear as follows where each cell is cosine of the angle between all the vectors of A (rows) with all the vectors of B (columns):" }, { "code": null, "e": 3293, "s": 3156, "text": "If you look at the color pattern you see that first vectors “a” replicate itself by row, while vectors “b” replicates itself by columns." }, { "code": null, "e": 3464, "s": 3293, "text": "To calculate this matrix in (almost) one line of code we need to look for a way to use what we know of algebra for numerator and denominator and then put it all together." }, { "code": null, "e": 3480, "s": 3464, "text": "Cell Numerator:" }, { "code": null, "e": 3638, "s": 3480, "text": "If we keep A matrix fixed (3,3) we have to operate a ‘dot’ product with the transpose of B [=> (5,3)] and we get a (3,3) result. In python this is easy with:" }, { "code": null, "e": 3656, "s": 3638, "text": "num=np.dot(A,B.T)" }, { "code": null, "e": 3674, "s": 3656, "text": "Cell Denominator:" }, { "code": null, "e": 3917, "s": 3674, "text": "It ’s a simple multiplication between 2 numbers but first we have to calculate the length of the two vectors. Let’s find a way to do that in a few Python lines using the numpy broadcasting operation which is a smart way to solve this problem." }, { "code": null, "e": 3985, "s": 3917, "text": "To calculate the lengths of vectors in A (and B) we should do this:" }, { "code": null, "e": 4075, "s": 3985, "text": "square the elements of matrix Asum the values by rowroot square the values out of point 2" }, { "code": null, "e": 4107, "s": 4075, "text": "square the elements of matrix A" }, { "code": null, "e": 4129, "s": 4107, "text": "sum the values by row" }, { "code": null, "e": 4167, "s": 4129, "text": "root square the values out of point 2" }, { "code": null, "e": 4305, "s": 4167, "text": "In the above case where A=(3,3) and B=(5,3) the two lines below (remember that axis=1 means ‘by row’) return two arrays (not matrices !):" }, { "code": null, "e": 4456, "s": 4305, "text": "p1=np.sqrt(np.sum(A**2,axis=1)) # array with 3 elements (it’s not a matrix)p2=np.sqrt(np.sum(B**2,axis=1)) # array with 5 elements (it’s not a matrix)" }, { "code": null, "e": 4588, "s": 4456, "text": "If we just multiply them together it doesn’t work because the ‘*’ works element by element and the shapes as you see are different." }, { "code": null, "e": 4780, "s": 4588, "text": "Because ‘*’ operation is element by element we want two matrices where the first has the vector p1 vertical and copied in width p2 times, while p2 is horizontal and copied in height p1 times." }, { "code": null, "e": 5007, "s": 4780, "text": "To do this with ‘broadcasting’ we have to modify p1 so that it becomes fixed in vertical (a1,a2,a3) but “elastic” in a second dimension. The same with p2 so that becomes fixed in horizontal and “elastic” in a second dimension." }, { "code": null, "e": 5070, "s": 5007, "text": "To achieve this we leverage the np.newaxis function with this:" }, { "code": null, "e": 5161, "s": 5070, "text": "p1=np.sqrt(np.sum(A**2,axis=1))[:,np.newaxis]p2=np.sqrt(np.sum(B**2,axis=1))[np.newaxis,:]" }, { "code": null, "e": 5587, "s": 5161, "text": "p1 can be read like: make the vector vertical (:) and add a column dimension and p2 can be read like: add a row dimension, make the vector horizontal. This operation for p2 in theory is not necessary because p2 was already horizontal and even if it was an array, multiplying a matrix (p1) by an array (p2) results in a matrix (if they are compatible of course) but I like the above because more clean and flexible to changes." }, { "code": null, "e": 5707, "s": 5587, "text": "Now if you look p1 and p2 before and after you will notice that p1 is now a matrix and so p2 but still one dimensional." }, { "code": null, "e": 5842, "s": 5707, "text": "If you now multiply them with p1*p2 then the magic happens and the result is a 3x5 matrix like the p1*p2 in grey in the above picture." }, { "code": null, "e": 5974, "s": 5842, "text": "So we can now finalize the (almost) one liner for our cosine similarity matrix with this example complete of some data for A and B:" }, { "code": null, "e": 6249, "s": 5974, "text": "import numpy as npA=np.array([[2,2,3],[1,0,4],[6,9,7]])B=np.array([[1,5,2],[6,6,4],[1,10,7],[5,8,2],[3,0,6]])def csm(A,B): num=np.dot(A,B.T) p1=np.sqrt(np.sum(A**2,axis=1))[:,np.newaxis] p2=np.sqrt(np.sum(B**2,axis=1))[np.newaxis,:]return num/(p1*p2)print(csm(A,B))" }, { "code": null, "e": 6500, "s": 6249, "text": "In case you want to modify the function to use it to calculate the correlation matrix the only difference is that you should subtract from the original matrices A and B their mean by row and also in this case you can leverage the np.newaxis function." }, { "code": null, "e": 6685, "s": 6500, "text": "In this case you first calculate the vector of the means by row as you’d usually do but remember that the result is again a horizontal vector and you cannot proceed with the code below" }, { "code": null, "e": 6718, "s": 6685, "text": "B-B.mean(axis=1)A-A.mean(axis=1)" }, { "code": null, "e": 7026, "s": 6718, "text": "We must make the means vector of A compatible with the matrix A by verticalizing and copying the now column vector the width of A times and the same for B. For this we can use again the broadcasting feature in Python “verticalizing” the vector (using ‘:’) and creating a new (elastic) dimension for columns." }, { "code": null, "e": 7091, "s": 7026, "text": "B=B-B.mean(axis=1)[:,np.newaxis]A=A-A.mean(axis=1)[:,np.newaxis]" }, { "code": null, "e": 7274, "s": 7091, "text": "Now we can modify our function including a boolean where if it’s True it calculates the correlation matrix between A and B while if it’s False calculate the cosine similarity matrix:" }, { "code": null, "e": 7650, "s": 7274, "text": "import numpy as npA=np.array([[1,2,3],[5,0,4],[6,9,7]])B=np.array([[4,0,9],[1,5,4],[2,8,6],[3,2,7],[5,9,4]])def csm(A,B,corr): if corr: B=B-B.mean(axis=1)[:,np.newaxis] A=A-A.mean(axis=1)[:,np.newaxis] num=np.dot(A,B.T) p1=np.sqrt(np.sum(A**2,axis=1))[:,np.newaxis] p2=np.sqrt(np.sum(B**2,axis=1))[np.newaxis,:]return num/(p1*p2)print(csm(A,B,True))" }, { "code": null, "e": 8106, "s": 7650, "text": "Note that if you use this function to calculate the correlation matrix the result is similar to the numpy function np.corrcoef(A,B) with the difference that the numpy function calculates also the correlation of A with A and B with B which could be redundant and force you to cut out the parts you don’t need. For example the correlation of A with B is in the submatrix top right which can be cut out knowing the shapes of A and B and working with indices." } ]
C | Structure & Union | Question 5 - GeeksforGeeks
28 Jun, 2021 #include<stdio.h> struct st { int x; struct st next; }; int main() { struct st temp; temp.x = 10; temp.next = temp; printf("%d", temp.next.x); return 0; } (A) Compiler Error(B) 10(C) Runtime Error(D) Garbage ValueAnswer: (A)Explanation: A structure cannot contain a member of its own type because if this is allowed then it becomes impossible for compiler to know size of such struct. Although a pointer of same type can be a member because pointers of all types are of same size and compiler can calculate size of structQuiz of this Question C-Structure & Union Structure & Union C Language C Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments rand() and srand() in C/C++ fork() in C Command line arguments in C/C++ Different methods to reverse a string in C/C++ Function Pointer in C Compiling a C program:- Behind the Scenes Operator Precedence and Associativity in C C | File Handling | Question 5 C | File Handling | Question 1 C | Dynamic Memory Allocation | Question 5
[ { "code": null, "e": 24414, "s": 24386, "text": "\n28 Jun, 2021" }, { "code": "#include<stdio.h> struct st { int x; struct st next; }; int main() { struct st temp; temp.x = 10; temp.next = temp; printf(\"%d\", temp.next.x); return 0; }", "e": 24601, "s": 24414, "text": null }, { "code": null, "e": 24989, "s": 24601, "text": "(A) Compiler Error(B) 10(C) Runtime Error(D) Garbage ValueAnswer: (A)Explanation: A structure cannot contain a member of its own type because if this is allowed then it becomes impossible for compiler to know size of such struct. Although a pointer of same type can be a member because pointers of all types are of same size and compiler can calculate size of structQuiz of this Question" }, { "code": null, "e": 25009, "s": 24989, "text": "C-Structure & Union" }, { "code": null, "e": 25027, "s": 25009, "text": "Structure & Union" }, { "code": null, "e": 25038, "s": 25027, "text": "C Language" }, { "code": null, "e": 25045, "s": 25038, "text": "C Quiz" }, { "code": null, "e": 25143, "s": 25045, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25152, "s": 25143, "text": "Comments" }, { "code": null, "e": 25165, "s": 25152, "text": "Old Comments" }, { "code": null, "e": 25193, "s": 25165, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 25205, "s": 25193, "text": "fork() in C" }, { "code": null, "e": 25237, "s": 25205, "text": "Command line arguments in C/C++" }, { "code": null, "e": 25284, "s": 25237, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 25306, "s": 25284, "text": "Function Pointer in C" }, { "code": null, "e": 25348, "s": 25306, "text": "Compiling a C program:- Behind the Scenes" }, { "code": null, "e": 25391, "s": 25348, "text": "Operator Precedence and Associativity in C" }, { "code": null, "e": 25422, "s": 25391, "text": "C | File Handling | Question 5" }, { "code": null, "e": 25453, "s": 25422, "text": "C | File Handling | Question 1" } ]
Find longest sequence of 1's in binary representation with one flip - GeeksforGeeks
21 May, 2021 Give an integer n. We can flip exactly one bit. Write code to find the length of the longest sequence of 1 s you could create. Examples: Input : 1775 Output : 8 Binary representation of 1775 is 11011101111. After flipping the highlighted bit, we get consecutive 8 bits. 11011111111. Input : 12 Output : 3 Input : 15 Output : 5 Input : 71 Output: 4 Binary representation of 71 is 1000111. After flipping the highlighted bit, we get consecutive 4 bits. 1001111. A simple solution is to store the binary representation of a given number in a binary array. Once we have elements in a binary array, we can apply the methods discussed here. An efficient solution is to walk through the bits in the binary representation of the given number. We keep track of the current 1’s sequence length and the previous 1’s sequence length. When we see a zero, update the previous Length: If the next bit is a 1, the previous Length should be set to the current Length.If the next bit is a 0, then we can’t merge these sequences together. So, set the previous Length to 0. If the next bit is a 1, the previous Length should be set to the current Length. If the next bit is a 0, then we can’t merge these sequences together. So, set the previous Length to 0. We update max length by comparing the following two: The current value of max-lengthCurrent-Length + Previous-Length . The current value of max-length Current-Length + Previous-Length . Result = return max-length+1 (// add 1 for flip bit count ) Below is the implementation of the above idea : C++ Java Python3 C# PHP Javascript // C++ program to find maximum consecutive// 1's in binary representation of a number// after flipping one bit.#include<bits/stdc++.h>using namespace std; int flipBit(unsigned a){ /* If all bits are l, binary representation of 'a' has all 1s */ if (~a == 0) return 8*sizeof(int); int currLen = 0, prevLen = 0, maxLen = 0; while (a!= 0) { // If Current bit is a 1 then increment currLen++ if ((a & 1) == 1) currLen++; // If Current bit is a 0 then check next bit of a else if ((a & 1) == 0) { /* Update prevLen to 0 (if next bit is 0) or currLen (if next bit is 1). */ prevLen = (a & 2) == 0? 0 : currLen; // If two consecutively bits are 0 // then currLen also will be 0. currLen = 0; } // Update maxLen if required maxLen = max(prevLen + currLen, maxLen); // Remove last bit (Right shift) a >>= 1; } // We can always have a sequence of // at least one 1, this is flipped bit return maxLen+1;} // Driver codeint main(){ // input 1 cout << flipBit(13); cout << endl; // input 2 cout << flipBit(1775); cout << endl; // input 3 cout << flipBit(15); return 0;} // Java program to find maximum consecutive// 1's in binary representation of a number// after flipping one bit. class GFG{ static int flipBit(int a) { /* If all bits are l, binary representation of 'a' has all 1s */ if (~a == 0) { return 8 * sizeof(); } int currLen = 0, prevLen = 0, maxLen = 0; while (a != 0) { // If Current bit is a 1 // then increment currLen++ if ((a & 1) == 1) { currLen++; } // If Current bit is a 0 then // check next bit of a else if ((a & 1) == 0) { /* Update prevLen to 0 (if next bit is 0) or currLen (if next bit is 1). */ prevLen = (a & 2) == 0 ? 0 : currLen; // If two consecutively bits are 0 // then currLen also will be 0. currLen = 0; } // Update maxLen if required maxLen = Math.max(prevLen + currLen, maxLen); // Remove last bit (Right shift) a >>= 1; } // We can always have a sequence of // at least one 1, this is flipped bit return maxLen + 1; } static byte sizeof() { byte sizeOfInteger = 8; return sizeOfInteger; } // Driver code public static void main(String[] args) { // input 1 System.out.println(flipBit(13)); // input 2 System.out.println(flipBit(1775)); // input 3 System.out.println(flipBit(15)); }} // This code is contributed by PrinciRaj1992 # Python3 program to find maximum# consecutive 1's in binary# representation of a number# after flipping one bit.def flipBit(a): # If all bits are l, # binary representation # of 'a' has all 1s if (~a == 0): return 8 * sizeof(); currLen = 0; prevLen = 0; maxLen = 0; while (a > 0): # If Current bit is a 1 # then increment currLen++ if ((a & 1) == 1): currLen += 1; # If Current bit is a 0 # then check next bit of a elif ((a & 1) == 0): # Update prevLen to 0 # (if next bit is 0) # or currLen (if next # bit is 1). */ prevLen = 0 if((a & 2) == 0) else currLen; # If two consecutively bits # are 0 then currLen also # will be 0. currLen = 0; # Update maxLen if required maxLen = max(prevLen + currLen, maxLen); # Remove last bit (Right shift) a >>= 1; # We can always have a sequence # of at least one 1, this is # flipped bit return maxLen + 1; # Driver code# input 1print(flipBit(13)); # input 2print(flipBit(1775)); # input 3print(flipBit(15)); # This code is contributed by mits // C# program to find maximum consecutive// 1's in binary representation of a number// after flipping one bit.using System; class GFG{ static int flipBit(int a) { /* If all bits are l, binary representation of 'a' has all 1s */ if (~a == 0) { return 8 * sizeof(int); } int currLen = 0, prevLen = 0, maxLen = 0; while (a != 0) { // If Current bit is a 1 // then increment currLen++ if ((a & 1) == 1) { currLen++; } // If Current bit is a 0 then // check next bit of a else if ((a & 1) == 0) { /* Update prevLen to 0 (if next bit is 0) or currLen (if next bit is 1). */ prevLen = (a & 2) == 0 ? 0 : currLen; // If two consecutively bits are 0 // then currLen also will be 0. currLen = 0; } // Update maxLen if required maxLen = Math.Max(prevLen + currLen, maxLen); // Remove last bit (Right shift) a >>= 1; } // We can always have a sequence of // at least one 1, this is flipped bit return maxLen + 1; } // Driver code public static void Main(String[] args) { // input 1 Console.WriteLine(flipBit(13)); // input 2 Console.WriteLine(flipBit(1775)); // input 3 Console.WriteLine(flipBit(15)); }} // This code contributed by Rajput-Ji <?php// PHP program to find maximum consecutive// 1's in binary representation of a number// after flipping one bit. function flipBit($a){ /* If all bits are l, binary representation of 'a' has all 1s */ if (~$a == 0) return 8 * sizeof(); $currLen = 0; $prevLen = 0; $maxLen = 0; while ($a!= 0) { // If Current bit is a 1 // then increment currLen++ if (($a & 1) == 1) $currLen++; // If Current bit is a 0 // then check next bit of a else if (($a & 1) == 0) { /* Update prevLen to 0 (if next bit is 0) or currLen (if next bit is 1). */ $prevLen = ($a & 2) == 0? 0 : $currLen; // If two consecutively bits are 0 // then currLen also will be 0. $currLen = 0; } // Update maxLen if required $maxLen = max($prevLen + $currLen, $maxLen); // Remove last bit (Right shift) $a >>= 1; } // We can always have a sequence of // at least one 1, this is flipped bit return $maxLen+1;} // Driver code // input 1 echo flipBit(13); echo "\n"; // input 2 echo flipBit(1775); echo "\n"; // input 3 echo flipBit(15); // This code is contributed by aj_36?> <script> // Javascript program to // find maximum consecutive // 1's in binary representation // of a number // after flipping one bit. function flipBit(a) { /* If all bits are l, binary representation of 'a' has all 1s */ if (~a == 0) { return 8 * sizeof(int); } let currLen = 0, prevLen = 0, maxLen = 0; while (a != 0) { // If Current bit is a 1 // then increment currLen++ if ((a & 1) == 1) { currLen++; } // If Current bit is a 0 then // check next bit of a else if ((a & 1) == 0) { /* Update prevLen to 0 (if next bit is 0) or currLen (if next bit is 1). */ prevLen = (a & 2) == 0 ? 0 : currLen; // If two consecutively bits are 0 // then currLen also will be 0. currLen = 0; } // Update maxLen if required maxLen = Math.max(prevLen + currLen, maxLen); // Remove last bit (Right shift) a >>= 1; } // We can always have a sequence of // at least one 1, this is flipped bit return maxLen + 1; } // input 1 document.write(flipBit(13) + "</br>"); // input 2 document.write(flipBit(1775) + "</br>"); // input 3 document.write(flipBit(15)); </script> Output : 4 8 5 This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t Mithun Kumar princiraj1992 Rajput-Ji shubham_singh divyeshrabadiya07 surinderdawra388 binary-representation Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bits manipulation (Important tactics) Add two numbers without using arithmetic operators Bit Fields in C Find the element that appears once Set, Clear and Toggle a given bit of a number in C C++ bitset and its application 1's and 2's complement of a Binary Number Divide two integers without using multiplication, division and mod operator Find the Number Occurring Odd Number of Times Check whether K-th bit is set or not
[ { "code": null, "e": 25074, "s": 25046, "text": "\n21 May, 2021" }, { "code": null, "e": 25202, "s": 25074, "text": "Give an integer n. We can flip exactly one bit. Write code to find the length of the longest sequence of 1 s you could create. " }, { "code": null, "e": 25213, "s": 25202, "text": "Examples: " }, { "code": null, "e": 25563, "s": 25213, "text": "Input : 1775 \nOutput : 8 \nBinary representation of 1775 is 11011101111.\nAfter flipping the highlighted bit, we get \nconsecutive 8 bits. 11011111111.\n\nInput : 12 \nOutput : 3 \n\nInput : 15\nOutput : 5\n\nInput : 71\nOutput: 4\n\nBinary representation of 71 is 1000111.\nAfter flipping the highlighted bit, we get \nconsecutive 4 bits. 1001111. " }, { "code": null, "e": 25738, "s": 25563, "text": "A simple solution is to store the binary representation of a given number in a binary array. Once we have elements in a binary array, we can apply the methods discussed here." }, { "code": null, "e": 25975, "s": 25738, "text": "An efficient solution is to walk through the bits in the binary representation of the given number. We keep track of the current 1’s sequence length and the previous 1’s sequence length. When we see a zero, update the previous Length: " }, { "code": null, "e": 26159, "s": 25975, "text": "If the next bit is a 1, the previous Length should be set to the current Length.If the next bit is a 0, then we can’t merge these sequences together. So, set the previous Length to 0." }, { "code": null, "e": 26240, "s": 26159, "text": "If the next bit is a 1, the previous Length should be set to the current Length." }, { "code": null, "e": 26344, "s": 26240, "text": "If the next bit is a 0, then we can’t merge these sequences together. So, set the previous Length to 0." }, { "code": null, "e": 26399, "s": 26344, "text": "We update max length by comparing the following two: " }, { "code": null, "e": 26465, "s": 26399, "text": "The current value of max-lengthCurrent-Length + Previous-Length ." }, { "code": null, "e": 26497, "s": 26465, "text": "The current value of max-length" }, { "code": null, "e": 26532, "s": 26497, "text": "Current-Length + Previous-Length ." }, { "code": null, "e": 26592, "s": 26532, "text": "Result = return max-length+1 (// add 1 for flip bit count )" }, { "code": null, "e": 26641, "s": 26592, "text": "Below is the implementation of the above idea : " }, { "code": null, "e": 26645, "s": 26641, "text": "C++" }, { "code": null, "e": 26650, "s": 26645, "text": "Java" }, { "code": null, "e": 26658, "s": 26650, "text": "Python3" }, { "code": null, "e": 26661, "s": 26658, "text": "C#" }, { "code": null, "e": 26665, "s": 26661, "text": "PHP" }, { "code": null, "e": 26676, "s": 26665, "text": "Javascript" }, { "code": "// C++ program to find maximum consecutive// 1's in binary representation of a number// after flipping one bit.#include<bits/stdc++.h>using namespace std; int flipBit(unsigned a){ /* If all bits are l, binary representation of 'a' has all 1s */ if (~a == 0) return 8*sizeof(int); int currLen = 0, prevLen = 0, maxLen = 0; while (a!= 0) { // If Current bit is a 1 then increment currLen++ if ((a & 1) == 1) currLen++; // If Current bit is a 0 then check next bit of a else if ((a & 1) == 0) { /* Update prevLen to 0 (if next bit is 0) or currLen (if next bit is 1). */ prevLen = (a & 2) == 0? 0 : currLen; // If two consecutively bits are 0 // then currLen also will be 0. currLen = 0; } // Update maxLen if required maxLen = max(prevLen + currLen, maxLen); // Remove last bit (Right shift) a >>= 1; } // We can always have a sequence of // at least one 1, this is flipped bit return maxLen+1;} // Driver codeint main(){ // input 1 cout << flipBit(13); cout << endl; // input 2 cout << flipBit(1775); cout << endl; // input 3 cout << flipBit(15); return 0;}", "e": 27955, "s": 26676, "text": null }, { "code": "// Java program to find maximum consecutive// 1's in binary representation of a number// after flipping one bit. class GFG{ static int flipBit(int a) { /* If all bits are l, binary representation of 'a' has all 1s */ if (~a == 0) { return 8 * sizeof(); } int currLen = 0, prevLen = 0, maxLen = 0; while (a != 0) { // If Current bit is a 1 // then increment currLen++ if ((a & 1) == 1) { currLen++; } // If Current bit is a 0 then // check next bit of a else if ((a & 1) == 0) { /* Update prevLen to 0 (if next bit is 0) or currLen (if next bit is 1). */ prevLen = (a & 2) == 0 ? 0 : currLen; // If two consecutively bits are 0 // then currLen also will be 0. currLen = 0; } // Update maxLen if required maxLen = Math.max(prevLen + currLen, maxLen); // Remove last bit (Right shift) a >>= 1; } // We can always have a sequence of // at least one 1, this is flipped bit return maxLen + 1; } static byte sizeof() { byte sizeOfInteger = 8; return sizeOfInteger; } // Driver code public static void main(String[] args) { // input 1 System.out.println(flipBit(13)); // input 2 System.out.println(flipBit(1775)); // input 3 System.out.println(flipBit(15)); }} // This code is contributed by PrinciRaj1992", "e": 29620, "s": 27955, "text": null }, { "code": "# Python3 program to find maximum# consecutive 1's in binary# representation of a number# after flipping one bit.def flipBit(a): # If all bits are l, # binary representation # of 'a' has all 1s if (~a == 0): return 8 * sizeof(); currLen = 0; prevLen = 0; maxLen = 0; while (a > 0): # If Current bit is a 1 # then increment currLen++ if ((a & 1) == 1): currLen += 1; # If Current bit is a 0 # then check next bit of a elif ((a & 1) == 0): # Update prevLen to 0 # (if next bit is 0) # or currLen (if next # bit is 1). */ prevLen = 0 if((a & 2) == 0) else currLen; # If two consecutively bits # are 0 then currLen also # will be 0. currLen = 0; # Update maxLen if required maxLen = max(prevLen + currLen, maxLen); # Remove last bit (Right shift) a >>= 1; # We can always have a sequence # of at least one 1, this is # flipped bit return maxLen + 1; # Driver code# input 1print(flipBit(13)); # input 2print(flipBit(1775)); # input 3print(flipBit(15)); # This code is contributed by mits", "e": 30863, "s": 29620, "text": null }, { "code": "// C# program to find maximum consecutive// 1's in binary representation of a number// after flipping one bit.using System; class GFG{ static int flipBit(int a) { /* If all bits are l, binary representation of 'a' has all 1s */ if (~a == 0) { return 8 * sizeof(int); } int currLen = 0, prevLen = 0, maxLen = 0; while (a != 0) { // If Current bit is a 1 // then increment currLen++ if ((a & 1) == 1) { currLen++; } // If Current bit is a 0 then // check next bit of a else if ((a & 1) == 0) { /* Update prevLen to 0 (if next bit is 0) or currLen (if next bit is 1). */ prevLen = (a & 2) == 0 ? 0 : currLen; // If two consecutively bits are 0 // then currLen also will be 0. currLen = 0; } // Update maxLen if required maxLen = Math.Max(prevLen + currLen, maxLen); // Remove last bit (Right shift) a >>= 1; } // We can always have a sequence of // at least one 1, this is flipped bit return maxLen + 1; } // Driver code public static void Main(String[] args) { // input 1 Console.WriteLine(flipBit(13)); // input 2 Console.WriteLine(flipBit(1775)); // input 3 Console.WriteLine(flipBit(15)); }} // This code contributed by Rajput-Ji", "e": 32444, "s": 30863, "text": null }, { "code": "<?php// PHP program to find maximum consecutive// 1's in binary representation of a number// after flipping one bit. function flipBit($a){ /* If all bits are l, binary representation of 'a' has all 1s */ if (~$a == 0) return 8 * sizeof(); $currLen = 0; $prevLen = 0; $maxLen = 0; while ($a!= 0) { // If Current bit is a 1 // then increment currLen++ if (($a & 1) == 1) $currLen++; // If Current bit is a 0 // then check next bit of a else if (($a & 1) == 0) { /* Update prevLen to 0 (if next bit is 0) or currLen (if next bit is 1). */ $prevLen = ($a & 2) == 0? 0 : $currLen; // If two consecutively bits are 0 // then currLen also will be 0. $currLen = 0; } // Update maxLen if required $maxLen = max($prevLen + $currLen, $maxLen); // Remove last bit (Right shift) $a >>= 1; } // We can always have a sequence of // at least one 1, this is flipped bit return $maxLen+1;} // Driver code // input 1 echo flipBit(13); echo \"\\n\"; // input 2 echo flipBit(1775); echo \"\\n\"; // input 3 echo flipBit(15); // This code is contributed by aj_36?>", "e": 33787, "s": 32444, "text": null }, { "code": "<script> // Javascript program to // find maximum consecutive // 1's in binary representation // of a number // after flipping one bit. function flipBit(a) { /* If all bits are l, binary representation of 'a' has all 1s */ if (~a == 0) { return 8 * sizeof(int); } let currLen = 0, prevLen = 0, maxLen = 0; while (a != 0) { // If Current bit is a 1 // then increment currLen++ if ((a & 1) == 1) { currLen++; } // If Current bit is a 0 then // check next bit of a else if ((a & 1) == 0) { /* Update prevLen to 0 (if next bit is 0) or currLen (if next bit is 1). */ prevLen = (a & 2) == 0 ? 0 : currLen; // If two consecutively bits are 0 // then currLen also will be 0. currLen = 0; } // Update maxLen if required maxLen = Math.max(prevLen + currLen, maxLen); // Remove last bit (Right shift) a >>= 1; } // We can always have a sequence of // at least one 1, this is flipped bit return maxLen + 1; } // input 1 document.write(flipBit(13) + \"</br>\"); // input 2 document.write(flipBit(1775) + \"</br>\"); // input 3 document.write(flipBit(15)); </script>", "e": 35336, "s": 33787, "text": null }, { "code": null, "e": 35346, "s": 35336, "text": "Output : " }, { "code": null, "e": 35352, "s": 35346, "text": "4\n8\n5" }, { "code": null, "e": 35778, "s": 35352, "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 write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 35784, "s": 35778, "text": "jit_t" }, { "code": null, "e": 35797, "s": 35784, "text": "Mithun Kumar" }, { "code": null, "e": 35811, "s": 35797, "text": "princiraj1992" }, { "code": null, "e": 35821, "s": 35811, "text": "Rajput-Ji" }, { "code": null, "e": 35835, "s": 35821, "text": "shubham_singh" }, { "code": null, "e": 35853, "s": 35835, "text": "divyeshrabadiya07" }, { "code": null, "e": 35870, "s": 35853, "text": "surinderdawra388" }, { "code": null, "e": 35892, "s": 35870, "text": "binary-representation" }, { "code": null, "e": 35902, "s": 35892, "text": "Bit Magic" }, { "code": null, "e": 35912, "s": 35902, "text": "Bit Magic" }, { "code": null, "e": 36010, "s": 35912, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36048, "s": 36010, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 36099, "s": 36048, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 36115, "s": 36099, "text": "Bit Fields in C" }, { "code": null, "e": 36150, "s": 36115, "text": "Find the element that appears once" }, { "code": null, "e": 36201, "s": 36150, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 36232, "s": 36201, "text": "C++ bitset and its application" }, { "code": null, "e": 36274, "s": 36232, "text": "1's and 2's complement of a Binary Number" }, { "code": null, "e": 36350, "s": 36274, "text": "Divide two integers without using multiplication, division and mod operator" }, { "code": null, "e": 36396, "s": 36350, "text": "Find the Number Occurring Odd Number of Times" } ]
How to Copy files or Folder without overwriting existing files?
To copy files/folders on the remote path without overwriting the existing files/folders, you can use multiple cmdlets like Copy-Item, Robocoy, and Xcopy, etc. As Copy-Item is a standard cmdlet, we will check if it's supported parameters can prevent overwriting. If Copy-Item doesn’t work then we will check its alternate command. Copy-Item simply overwrites the files and folders on the destination path and the copies newer files. For example, To copy files from the source folder C:\Test1 to the destination folder C:\Test2 below command is used and it simply overwrites the file without asking. Copy-Item C:\Test1\* C:\Test2 -Recurse -Verbose PS C:\Temp> Copy-Item C:\Test1\* C:\Test2 -Recurse -Verbose VERBOSE: Performing the operation "Copy File" on target "Item: C:\Test1\File1.txt Destination: C:\Test2\File1.txt". VERBOSE: Performing the operation "Copy File" on target "Item: C:\Test1\File2.txt Destination: C:\Test2\File2.txt". We have another -Confirm parameter, but it just confirms from the user that if files need to copy on the destination folder or not. If we choose $True for -Confirm parameter then it will ask for each file if it needs to copy or not but if you have hundreds of files on the system then this method won’t work Copy-Item C:\Test1\* -Destination C:\Test2\ -Confirm:$true -Verbose PS C:\Temp> Copy-Item C:\Test1\* -Destination C:\Test2\ -Confirm:$true -Verbose Confirm Are you sure you want to perform this action? Performing the operation "Copy File" on target "Item: C:\Test1\File1.txt Destination: C:\Test2\File1.txt". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): With -Force parameter is for overwriting Read-only file content. So that is also not going to help so we can use another method like filtering existing files through Get-ChildItem and skipping them but that requires writing several codes and loop instead we have a robocopy command which supports preventing overwriting of files/ folder. Robocopy C:\Test1\ C:\Test2\ /E /XC /XN /XO PS C:\> Robocopy C:\Test1\ C:\Test2\ /E /XC /XN /XO ------------------------------------------------------------------------------- ROBOCOPY :: Robust File Copy for Windows ------------------------------------------------------------------------------- Started : Saturday, August 29, 2020 2:15:33 PM Source : C:\Test1\ Dest : C:\Test2\ Files : *.* Options : *.* /S /E /DCOPY:DA /COPY:DAT /XO /XN /XC /R:1000000 /W:30 ------------------------------------------------------------------------------ 2 C:\Test1\ *EXTRA File 8 File3.txt 100% New File 11 File2.txt ------------------------------------------------------------------------------ Total Copied Skipped Mismatch FAILED Extras Dirs : 1 0 1 0 0 0 Files : 2 1 1 0 0 1 Bytes : 22 11 11 0 0 8 Times : 0:00:00 0:00:00 0:00:00 0:00:00 Speed : 1833 Bytes/sec. Speed : 0.104 MegaBytes/min. Ended : Saturday, August 29, 2020 2:15:33 PM Switches are explained below. /E − Copies child items (like -recursive in Copy-Command) /XC − Prevents overwriting the files which have the same timestamp. /XN − Prevents overwriting of files with the newer timestamp than the source files. /XO − Prevents overwriting of files with the older timestamp than the source files.
[ { "code": null, "e": 1324, "s": 1062, "text": "To copy files/folders on the remote path without overwriting the existing files/folders, you can use multiple cmdlets like Copy-Item, Robocoy, and Xcopy, etc. As Copy-Item is a standard cmdlet, we will check if it's supported parameters can prevent overwriting." }, { "code": null, "e": 1494, "s": 1324, "text": "If Copy-Item doesn’t work then we will check its alternate command. Copy-Item simply overwrites the files and folders on the destination path and the copies newer files." }, { "code": null, "e": 1660, "s": 1494, "text": "For example, To copy files from the source folder C:\\Test1 to the destination folder C:\\Test2 below command is used and it simply overwrites the file without asking." }, { "code": null, "e": 1708, "s": 1660, "text": "Copy-Item C:\\Test1\\* C:\\Test2 -Recurse -Verbose" }, { "code": null, "e": 2000, "s": 1708, "text": "PS C:\\Temp> Copy-Item C:\\Test1\\* C:\\Test2 -Recurse -Verbose\nVERBOSE: Performing the operation \"Copy File\" on target \"Item: C:\\Test1\\File1.txt\nDestination: C:\\Test2\\File1.txt\".\nVERBOSE: Performing the operation \"Copy File\" on target \"Item: C:\\Test1\\File2.txt\nDestination: C:\\Test2\\File2.txt\"." }, { "code": null, "e": 2308, "s": 2000, "text": "We have another -Confirm parameter, but it just confirms from the user that if files need to copy on the destination folder or not. If we choose $True for -Confirm parameter then it will ask for each file if it needs to copy or not but if you have hundreds of files on the system then this method won’t work" }, { "code": null, "e": 2376, "s": 2308, "text": "Copy-Item C:\\Test1\\* -Destination C:\\Test2\\ -Confirm:$true -Verbose" }, { "code": null, "e": 2701, "s": 2376, "text": "PS C:\\Temp> Copy-Item C:\\Test1\\* -Destination C:\\Test2\\ -Confirm:$true -Verbose\n\nConfirm\nAre you sure you want to perform this action?\nPerforming the operation \"Copy File\" on target \"Item: C:\\Test1\\File1.txt Destination:\nC:\\Test2\\File1.txt\".\n[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is \"Y\"):" }, { "code": null, "e": 3039, "s": 2701, "text": "With -Force parameter is for overwriting Read-only file content. So that is also not going to help so we can use another method like filtering existing files through Get-ChildItem and skipping them but that requires writing several codes and loop instead we have a robocopy command which supports preventing overwriting of files/ folder." }, { "code": null, "e": 3083, "s": 3039, "text": "Robocopy C:\\Test1\\ C:\\Test2\\ /E /XC /XN /XO" }, { "code": null, "e": 4124, "s": 3083, "text": "PS C:\\> Robocopy C:\\Test1\\ C:\\Test2\\ /E /XC /XN /XO\n-------------------------------------------------------------------------------\nROBOCOPY :: Robust File Copy for Windows\n-------------------------------------------------------------------------------\nStarted : Saturday, August 29, 2020 2:15:33 PM\nSource : C:\\Test1\\\nDest : C:\\Test2\\\nFiles : *.*\nOptions : *.* /S /E /DCOPY:DA /COPY:DAT /XO /XN /XC /R:1000000 /W:30\n------------------------------------------------------------------------------\n 2 C:\\Test1\\\n *EXTRA File 8 File3.txt\n100% New File 11 File2.txt\n------------------------------------------------------------------------------\n Total Copied Skipped Mismatch FAILED Extras\nDirs : 1 0 1 0 0 0\nFiles : 2 1 1 0 0 1\nBytes : 22 11 11 0 0 8\nTimes : 0:00:00 0:00:00 0:00:00 0:00:00\nSpeed : 1833 Bytes/sec.\nSpeed : 0.104 MegaBytes/min.\nEnded : Saturday, August 29, 2020 2:15:33 PM" }, { "code": null, "e": 4154, "s": 4124, "text": "Switches are explained below." }, { "code": null, "e": 4212, "s": 4154, "text": "/E − Copies child items (like -recursive in Copy-Command)" }, { "code": null, "e": 4280, "s": 4212, "text": "/XC − Prevents overwriting the files which have the same timestamp." }, { "code": null, "e": 4364, "s": 4280, "text": "/XN − Prevents overwriting of files with the newer timestamp than the source files." }, { "code": null, "e": 4448, "s": 4364, "text": "/XO − Prevents overwriting of files with the older timestamp than the source files." } ]
Removing duplicate elements from an array in PHP
The ‘array_flip’ function can be used, that will reverse the values as indices and keys as values. Live Demo <?php $my_arr = array(45, 65, 67, 99, 81, 90, 99, 45, 68); echo "The original array contains \n"; print_r($my_arr); $my_arr = array_flip($my_arr); $my_arr = array_flip($my_arr); $my_arr= array_values($my_arr); echo "\n The array after removing duplicate elements is \n "; print_r($my_arr); ?> The original array contains Array ( [0] => 45 [1] => 65 [2] => 67 [3] => 99 [4] => 81 [5] => 90 [6] => 99 [7] => 45 [8] => 68 ) The array after removing duplicate elements is Array ( [0] => 45 [1] => 65 [2] => 67 [3] => 99 [4] => 81 [5] => 90 [6] => 68 ) An array is defined and duplicate elements from the array can be found and removed using the ‘array_flip’ function, that basically reverses the keys/index as values and values as keys. This way, the value that is repeated comes twice in the index and one of them is removed since indices have to be unique. Again, the ‘array_flip’ function is used to get the array back to the original form.
[ { "code": null, "e": 1161, "s": 1062, "text": "The ‘array_flip’ function can be used, that will reverse the values as indices and keys as values." }, { "code": null, "e": 1172, "s": 1161, "text": " Live Demo" }, { "code": null, "e": 1489, "s": 1172, "text": "<?php\n $my_arr = array(45, 65, 67, 99, 81, 90, 99, 45, 68);\n echo \"The original array contains \\n\";\n print_r($my_arr);\n $my_arr = array_flip($my_arr);\n $my_arr = array_flip($my_arr);\n $my_arr= array_values($my_arr);\n echo \"\\n The array after removing duplicate elements is \\n \";\n print_r($my_arr);\n?>" }, { "code": null, "e": 1793, "s": 1489, "text": "The original array contains\nArray\n(\n [0] => 45\n [1] => 65\n [2] => 67\n [3] => 99\n [4] => 81\n [5] => 90\n [6] => 99\n [7] => 45\n [8] => 68\n)\n\nThe array after removing duplicate elements is\nArray\n(\n [0] => 45\n [1] => 65\n [2] => 67\n [3] => 99\n [4] => 81\n [5] => 90\n [6] => 68\n)" }, { "code": null, "e": 2185, "s": 1793, "text": "An array is defined and duplicate elements from the array can be found and removed using the ‘array_flip’ function, that basically reverses the keys/index as values and values as keys. This way, the value that is repeated comes twice in the index and one of them is removed since indices have to be unique. Again, the ‘array_flip’ function is used to get the array back to the original form." } ]
JavaScript String - link() Method
This method creates an HTML hypertext link that requests another URL. The syntax for link() method is as follows − string.link( hrefname ) hrefname − Any string that specifies the HREF of the A tag; it should be a valid URL. Returns the string with <a> tag. Try the following example. <html> <head> <title>JavaScript String link() Method</title> </head> <body> <script type = "text/javascript"> var str = new String("Hello world"); var URL = "http://www.tutorialspoint.com"; alert(str.link( URL )); </script> </body> </html> <a href = "http://www.tutorialspoint.com">Hello world</a> 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2536, "s": 2466, "text": "This method creates an HTML hypertext link that requests another URL." }, { "code": null, "e": 2581, "s": 2536, "text": "The syntax for link() method is as follows −" }, { "code": null, "e": 2606, "s": 2581, "text": "string.link( hrefname )\n" }, { "code": null, "e": 2692, "s": 2606, "text": "hrefname − Any string that specifies the HREF of the A tag; it should be a valid URL." }, { "code": null, "e": 2725, "s": 2692, "text": "Returns the string with <a> tag." }, { "code": null, "e": 2752, "s": 2725, "text": "Try the following example." }, { "code": null, "e": 3071, "s": 2752, "text": "<html>\n <head>\n <title>JavaScript String link() Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var str = new String(\"Hello world\");\n var URL = \"http://www.tutorialspoint.com\"; \n alert(str.link( URL ));\n </script> \n </body>\n</html>" }, { "code": null, "e": 3130, "s": 3071, "text": "<a href = \"http://www.tutorialspoint.com\">Hello world</a>\n" }, { "code": null, "e": 3165, "s": 3130, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3179, "s": 3165, "text": " Anadi Sharma" }, { "code": null, "e": 3213, "s": 3179, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 3227, "s": 3213, "text": " Lets Kode It" }, { "code": null, "e": 3262, "s": 3227, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3279, "s": 3262, "text": " Frahaan Hussain" }, { "code": null, "e": 3314, "s": 3279, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3331, "s": 3314, "text": " Frahaan Hussain" }, { "code": null, "e": 3364, "s": 3331, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 3392, "s": 3364, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3426, "s": 3392, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 3454, "s": 3426, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3461, "s": 3454, "text": " Print" }, { "code": null, "e": 3472, "s": 3461, "text": " Add Notes" } ]
How to increase the font size of the legend in my Seaborn plot using Matplotlib?
To increase the font size of the legend in a Seaborn plot, we can use the fontsize variable and can use it in legend() method argument. Create a data frame using Pandas. The keys are number, count, and select. Create a data frame using Pandas. The keys are number, count, and select. Plot a bar in Seaborn using barplot() method. Plot a bar in Seaborn using barplot() method. Initialize a variable fontsize to increase the fontsize of the legend. Initialize a variable fontsize to increase the fontsize of the legend. Use legend() method to place legend on the figure with fontsize in the argument. Use legend() method to place legend on the figure with fontsize in the argument. To display the figure, use show() method. To display the figure, use show() method. import pandas import matplotlib.pylab as plt import seaborn as sns plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True df = pandas.DataFrame(dict( number=[2, 5, 1, 6, 3], count=[56, 21, 34, 36, 12], select=[29, 13, 17, 21, 8] )) bar_plot1 = sns.barplot(x='number', y='count', data=df, label="count", color="red") bar_plot2 = sns.barplot(x='number', y='select', data=df, label="select", color="green") fontsize = 20 plt.legend(loc="upper right", frameon=True, fontsize=fontsize) plt.show()
[ { "code": null, "e": 1198, "s": 1062, "text": "To increase the font size of the legend in a Seaborn plot, we can use the fontsize variable and can use it in legend() method argument." }, { "code": null, "e": 1272, "s": 1198, "text": "Create a data frame using Pandas. The keys are number, count, and select." }, { "code": null, "e": 1346, "s": 1272, "text": "Create a data frame using Pandas. The keys are number, count, and select." }, { "code": null, "e": 1392, "s": 1346, "text": "Plot a bar in Seaborn using barplot() method." }, { "code": null, "e": 1438, "s": 1392, "text": "Plot a bar in Seaborn using barplot() method." }, { "code": null, "e": 1509, "s": 1438, "text": "Initialize a variable fontsize to increase the fontsize of the legend." }, { "code": null, "e": 1580, "s": 1509, "text": "Initialize a variable fontsize to increase the fontsize of the legend." }, { "code": null, "e": 1661, "s": 1580, "text": "Use legend() method to place legend on the figure with fontsize in the argument." }, { "code": null, "e": 1742, "s": 1661, "text": "Use legend() method to place legend on the figure with fontsize in the argument." }, { "code": null, "e": 1784, "s": 1742, "text": "To display the figure, use show() method." }, { "code": null, "e": 1826, "s": 1784, "text": "To display the figure, use show() method." }, { "code": null, "e": 2359, "s": 1826, "text": "import pandas\nimport matplotlib.pylab as plt\nimport seaborn as sns\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ndf = pandas.DataFrame(dict(\n number=[2, 5, 1, 6, 3],\n count=[56, 21, 34, 36, 12],\n select=[29, 13, 17, 21, 8]\n))\nbar_plot1 = sns.barplot(x='number', y='count', data=df, label=\"count\", color=\"red\")\nbar_plot2 = sns.barplot(x='number', y='select', data=df, label=\"select\", color=\"green\")\nfontsize = 20\nplt.legend(loc=\"upper right\", frameon=True, fontsize=fontsize)\nplt.show()" } ]
Uber datasets in BigQuery: Driving times around SF (and your city too) | by Felipe Hoffa | Towards Data Science
First let’s play with the interactive dashboard, and we’ll look into the loading steps and troubleshooting below. Note that you can use these steps to load any other city into BigQuery! Interactive Data Studio dashboard: We can find data for several cities in Uber Movements’s public data site. Here I’ll download some of the San Francisco travel times datasets: Once we have the files on our side, loading the data CSVs is straightforward: bq load --autodetect \ fh-bigquery:deleting.uber_sf_censustracts_201803_all_hourly \ san_francisco-censustracts-2018-3-All-HourlyAggregate.csvbq load --autodetect \ fh-bigquery:deleting.uber_sf_censustracts_201803_weekdays_hourly \ san_francisco-censustracts-2018-3-OnlyWeekdays-HourlyAggregate.csvbq load --autodetect \ fh-bigquery:deleting.uber_sf_censustracts_201803_weekends_hourly \ san_francisco-censustracts-2018-3-OnlyWeekends-HourlyAggregate.csv However the geo boundaries files will pose some challenges. They are standard GeoJSON files, but we’ll have to massage them before loading into BigQuery: Transform the GeoJSON file to a new line delimited JSON file with jq.Load the new .json files as CSV into BigQuery.Parse the JSON rows in BigQuery to generate native GIS geometries. Transform the GeoJSON file to a new line delimited JSON file with jq. Load the new .json files as CSV into BigQuery. Parse the JSON rows in BigQuery to generate native GIS geometries. jq -c .features[] \ san_francisco_censustracts.json > sf_censustracts_201905.jsonbq load --source_format=CSV \ --quote='' --field_delimiter='|' \ fh-bigquery:deleting.sf_censustracts_201905 \ sf_censustracts_201905.json row For step 3, we can parse the loaded rows inside BigQuery: CREATE OR REPLACE TABLE `fh-bigquery.uber_201905.sf_censustracts`ASSELECT FORMAT('%f,%f', ST_Y(centroid), ST_X(centroid)) lat_lon, *FROM ( SELECT *, ST_CENTROID(geometry) centroid FROM ( SELECT CAST(JSON_EXTRACT_SCALAR(row, '$.properties.MOVEMENT_ID') AS INT64) movement_id , JSON_EXTRACT_SCALAR(row, '$.properties.DISPLAY_NAME') display_name , ST_GeogFromGeoJson(JSON_EXTRACT(row, '$.geometry')) geometry FROM `fh-bigquery.deleting.sf_censustracts_201905` )) Find some alternatives (JavaScript, ogr2ogr) from Lak Lakshmanan and Michael Entin to load GeoJSON data in this Stack Overflow reply. Now that we have both tables inside BigQuery, let’s massage the data to partition the main table, create native BQ GIS geometry columns, and join everything together: Let’s create our main table. This table will contain both weekdays, weekends, and overall stats — and we’ll add some census tract data to make it easier to visualize and understand. For efficiency we’ll partition it by quarter and cluster by the type of stat and travel starting place. I’ll also calculate some additional stats: Average distance between areas and speed given this distance. Note that having these stats will make the query run way slower than if we skipped them: CREATE OR REPLACE TABLE `fh-bigquery.uber_201905.sf_hourly`PARTITION BY quarter CLUSTER BY table_source, source, destination-- don't partition/cluster if using BQ w/o credit cardASSELECT *, distance * 0.000621371192 / geometric_mean_travel_time * 3600 speed_mphFROM ( SELECT * EXCEPT(geo_b, geo_c), (ST_DISTANCE(geo_b, geo_c)+ST_MAXDISTANCE(geo_b, geo_c))/2 distance FROM ( SELECT a.*, SPLIT(_TABLE_SUFFIX, '_')[OFFSET(0)] table_source , b.display_name source , c.display_name destination , b.lat_lon sourceid_lat_lon , CAST(SPLIT(b.lat_lon, ',')[OFFSET(0)] AS FLOAT64) sourceid_lat , CAST(SPLIT(b.lat_lon, ',')[OFFSET(1)] AS FLOAT64) sourceid_lon , c.lat_lon dstid_lat_lon , CAST(SPLIT(c.lat_lon, ',')[OFFSET(0)] AS FLOAT64) dstid_lat , CAST(SPLIT(c.lat_lon, ',')[OFFSET(1)] AS FLOAT64) dstid_lon , DATE('2018-07-01') quarter , COUNT(*) OVER(PARTITION BY sourceid, dstid) source_dst_popularity , COUNT(*) OVER(PARTITION BY dstid) dst_popularity , b.geometry geo_b, c.geometry geo_c FROM `fh-bigquery.deleting.uber_sf_censustracts_201803_*` a JOIN `fh-bigquery.uber_201905.sf_censustracts` b ON a.sourceid=b.movement_id JOIN `fh-bigquery.uber_201905.sf_censustracts` c ON a.dstid=c.movement_id )) I created an interactive dashboard with Data Studio. Note that it runs super fast thanks to our new BigQuery BI Engine. But you can also run your own queries! For example, the worst destinations in San Francisco and time of the day when arriving to the SFO airport: SELECT ROUND(geometric_mean_travel_time/60) minutes , hod hour, ROUND(distance*0.000621371192,2) miles , destination FROM `fh-bigquery.uber_201905.sf_hourly`WHERE table_source='weekdays'AND quarter='2018-07-01'AND source LIKE '100 Domestic Terminals Departures Level%' AND destination LIKE '%San Francisco%'AND (distance*0.000621371192)>10ORDER BY 1 DESCLIMIT 20 And the best places and times to travel from SFO to SF: SELECT ROUND(geometric_mean_travel_time/60) minutes , hod hour, ROUND(distance*0.000621371192,2) miles , destination FROM `fh-bigquery.uber_201905.sf_hourly`WHERE table_source='weekdays'AND quarter='2018-07-01'AND source LIKE '100 Domestic Terminals Departures Level%' AND destination LIKE '%San Francisco%'AND (distance*0.000621371192)>10ORDER BY 1 LIMIT 20 The worst variations in average time (by stddev), when going from SFO to Oakland: SELECT destination , STDDEV(geometric_mean_travel_time) stddev , COUNT(*) cFROM `fh-bigquery.uber_201905.sf_hourly`WHERE table_source='weekdays'AND quarter='2018-07-01'AND source LIKE '100 Domestic Terminals Departures Level%' AND destination LIKE '%Oakland%'AND (distance*0.000621371192)>10GROUP BY destinationHAVING c=24ORDER BY stddev DESCLIMIT 20 Find the shared dataset in BigQuery. Load more cities — Uber keeps adding more data to their shared collection! Want more stories? Check my Medium, follow me on twitter, and subscribe to reddit.com/r/bigquery. And try BigQuery — every month you get a full terabyte of analysis for free. Uber’s data license: Data is made available under the Creative Commons, Attribution Non Commercial license. Data Attributions Background map: http://extras.sfgate.com/img/pages/travel/maps/sfbay_std.gif
[ { "code": null, "e": 393, "s": 172, "text": "First let’s play with the interactive dashboard, and we’ll look into the loading steps and troubleshooting below. Note that you can use these steps to load any other city into BigQuery! Interactive Data Studio dashboard:" }, { "code": null, "e": 535, "s": 393, "text": "We can find data for several cities in Uber Movements’s public data site. Here I’ll download some of the San Francisco travel times datasets:" }, { "code": null, "e": 613, "s": 535, "text": "Once we have the files on our side, loading the data CSVs is straightforward:" }, { "code": null, "e": 1074, "s": 613, "text": "bq load --autodetect \\ fh-bigquery:deleting.uber_sf_censustracts_201803_all_hourly \\ san_francisco-censustracts-2018-3-All-HourlyAggregate.csvbq load --autodetect \\ fh-bigquery:deleting.uber_sf_censustracts_201803_weekdays_hourly \\ san_francisco-censustracts-2018-3-OnlyWeekdays-HourlyAggregate.csvbq load --autodetect \\ fh-bigquery:deleting.uber_sf_censustracts_201803_weekends_hourly \\ san_francisco-censustracts-2018-3-OnlyWeekends-HourlyAggregate.csv" }, { "code": null, "e": 1228, "s": 1074, "text": "However the geo boundaries files will pose some challenges. They are standard GeoJSON files, but we’ll have to massage them before loading into BigQuery:" }, { "code": null, "e": 1410, "s": 1228, "text": "Transform the GeoJSON file to a new line delimited JSON file with jq.Load the new .json files as CSV into BigQuery.Parse the JSON rows in BigQuery to generate native GIS geometries." }, { "code": null, "e": 1480, "s": 1410, "text": "Transform the GeoJSON file to a new line delimited JSON file with jq." }, { "code": null, "e": 1527, "s": 1480, "text": "Load the new .json files as CSV into BigQuery." }, { "code": null, "e": 1594, "s": 1527, "text": "Parse the JSON rows in BigQuery to generate native GIS geometries." }, { "code": null, "e": 1822, "s": 1594, "text": "jq -c .features[] \\ san_francisco_censustracts.json > sf_censustracts_201905.jsonbq load --source_format=CSV \\ --quote='' --field_delimiter='|' \\ fh-bigquery:deleting.sf_censustracts_201905 \\ sf_censustracts_201905.json row" }, { "code": null, "e": 1880, "s": 1822, "text": "For step 3, we can parse the loaded rows inside BigQuery:" }, { "code": null, "e": 2366, "s": 1880, "text": "CREATE OR REPLACE TABLE `fh-bigquery.uber_201905.sf_censustracts`ASSELECT FORMAT('%f,%f', ST_Y(centroid), ST_X(centroid)) lat_lon, *FROM ( SELECT *, ST_CENTROID(geometry) centroid FROM ( SELECT CAST(JSON_EXTRACT_SCALAR(row, '$.properties.MOVEMENT_ID') AS INT64) movement_id , JSON_EXTRACT_SCALAR(row, '$.properties.DISPLAY_NAME') display_name , ST_GeogFromGeoJson(JSON_EXTRACT(row, '$.geometry')) geometry FROM `fh-bigquery.deleting.sf_censustracts_201905` ))" }, { "code": null, "e": 2500, "s": 2366, "text": "Find some alternatives (JavaScript, ogr2ogr) from Lak Lakshmanan and Michael Entin to load GeoJSON data in this Stack Overflow reply." }, { "code": null, "e": 2667, "s": 2500, "text": "Now that we have both tables inside BigQuery, let’s massage the data to partition the main table, create native BQ GIS geometry columns, and join everything together:" }, { "code": null, "e": 2953, "s": 2667, "text": "Let’s create our main table. This table will contain both weekdays, weekends, and overall stats — and we’ll add some census tract data to make it easier to visualize and understand. For efficiency we’ll partition it by quarter and cluster by the type of stat and travel starting place." }, { "code": null, "e": 3147, "s": 2953, "text": "I’ll also calculate some additional stats: Average distance between areas and speed given this distance. Note that having these stats will make the query run way slower than if we skipped them:" }, { "code": null, "e": 4437, "s": 3147, "text": "CREATE OR REPLACE TABLE `fh-bigquery.uber_201905.sf_hourly`PARTITION BY quarter CLUSTER BY table_source, source, destination-- don't partition/cluster if using BQ w/o credit cardASSELECT *, distance * 0.000621371192 / geometric_mean_travel_time * 3600 speed_mphFROM ( SELECT * EXCEPT(geo_b, geo_c), (ST_DISTANCE(geo_b, geo_c)+ST_MAXDISTANCE(geo_b, geo_c))/2 distance FROM ( SELECT a.*, SPLIT(_TABLE_SUFFIX, '_')[OFFSET(0)] table_source , b.display_name source , c.display_name destination , b.lat_lon sourceid_lat_lon , CAST(SPLIT(b.lat_lon, ',')[OFFSET(0)] AS FLOAT64) sourceid_lat , CAST(SPLIT(b.lat_lon, ',')[OFFSET(1)] AS FLOAT64) sourceid_lon , c.lat_lon dstid_lat_lon , CAST(SPLIT(c.lat_lon, ',')[OFFSET(0)] AS FLOAT64) dstid_lat , CAST(SPLIT(c.lat_lon, ',')[OFFSET(1)] AS FLOAT64) dstid_lon , DATE('2018-07-01') quarter , COUNT(*) OVER(PARTITION BY sourceid, dstid) source_dst_popularity , COUNT(*) OVER(PARTITION BY dstid) dst_popularity , b.geometry geo_b, c.geometry geo_c FROM `fh-bigquery.deleting.uber_sf_censustracts_201803_*` a JOIN `fh-bigquery.uber_201905.sf_censustracts` b ON a.sourceid=b.movement_id JOIN `fh-bigquery.uber_201905.sf_censustracts` c ON a.dstid=c.movement_id ))" }, { "code": null, "e": 4596, "s": 4437, "text": "I created an interactive dashboard with Data Studio. Note that it runs super fast thanks to our new BigQuery BI Engine. But you can also run your own queries!" }, { "code": null, "e": 4703, "s": 4596, "text": "For example, the worst destinations in San Francisco and time of the day when arriving to the SFO airport:" }, { "code": null, "e": 5068, "s": 4703, "text": "SELECT ROUND(geometric_mean_travel_time/60) minutes , hod hour, ROUND(distance*0.000621371192,2) miles , destination FROM `fh-bigquery.uber_201905.sf_hourly`WHERE table_source='weekdays'AND quarter='2018-07-01'AND source LIKE '100 Domestic Terminals Departures Level%' AND destination LIKE '%San Francisco%'AND (distance*0.000621371192)>10ORDER BY 1 DESCLIMIT 20" }, { "code": null, "e": 5124, "s": 5068, "text": "And the best places and times to travel from SFO to SF:" }, { "code": null, "e": 5485, "s": 5124, "text": "SELECT ROUND(geometric_mean_travel_time/60) minutes , hod hour, ROUND(distance*0.000621371192,2) miles , destination FROM `fh-bigquery.uber_201905.sf_hourly`WHERE table_source='weekdays'AND quarter='2018-07-01'AND source LIKE '100 Domestic Terminals Departures Level%' AND destination LIKE '%San Francisco%'AND (distance*0.000621371192)>10ORDER BY 1 LIMIT 20" }, { "code": null, "e": 5567, "s": 5485, "text": "The worst variations in average time (by stddev), when going from SFO to Oakland:" }, { "code": null, "e": 5921, "s": 5567, "text": "SELECT destination , STDDEV(geometric_mean_travel_time) stddev , COUNT(*) cFROM `fh-bigquery.uber_201905.sf_hourly`WHERE table_source='weekdays'AND quarter='2018-07-01'AND source LIKE '100 Domestic Terminals Departures Level%' AND destination LIKE '%Oakland%'AND (distance*0.000621371192)>10GROUP BY destinationHAVING c=24ORDER BY stddev DESCLIMIT 20" }, { "code": null, "e": 5958, "s": 5921, "text": "Find the shared dataset in BigQuery." }, { "code": null, "e": 6033, "s": 5958, "text": "Load more cities — Uber keeps adding more data to their shared collection!" }, { "code": null, "e": 6208, "s": 6033, "text": "Want more stories? Check my Medium, follow me on twitter, and subscribe to reddit.com/r/bigquery. And try BigQuery — every month you get a full terabyte of analysis for free." }, { "code": null, "e": 6334, "s": 6208, "text": "Uber’s data license: Data is made available under the Creative Commons, Attribution Non Commercial license. Data Attributions" } ]
ftp_connect() function in PHP
The ftp_connect() function opens an FTB connection. ftp_connect(host,port,timeout); host − The FTP server to connect to host − The FTP server to connect to port − The port of the FTP server. The default is 21. The host can be a domain or IP address. port − The port of the FTP server. The default is 21. The host can be a domain or IP address. timeout − The timeout for network operation timeout − The timeout for network operation The ftp_connect() function returns an FTP stream on success or FALSE on error The following is an example: to open an FTP connection, to work in it and closing it. <?php $ftp_server="192.168.0.4"; $ftp_user="amit"; $ftp_pass="tywg61gh"; $con = ftp_connect($ftp_server); $res = ftp_login($con, $ftp_user, $ftp_pass); ftp_chdir($con, 'demo'); echo ftp_pwd($con); if (ftp_cdup($con)) { echo "Directory changed!\n"; } else { echo "Directory change not successful!\n"; } echo ftp_pwd($con); ftp_close($con); ?>
[ { "code": null, "e": 1114, "s": 1062, "text": "The ftp_connect() function opens an FTB connection." }, { "code": null, "e": 1146, "s": 1114, "text": "ftp_connect(host,port,timeout);" }, { "code": null, "e": 1182, "s": 1146, "text": "host − The FTP server to connect to" }, { "code": null, "e": 1218, "s": 1182, "text": "host − The FTP server to connect to" }, { "code": null, "e": 1312, "s": 1218, "text": "port − The port of the FTP server. The default is 21. The host can be a domain or IP address." }, { "code": null, "e": 1406, "s": 1312, "text": "port − The port of the FTP server. The default is 21. The host can be a domain or IP address." }, { "code": null, "e": 1450, "s": 1406, "text": "timeout − The timeout for network operation" }, { "code": null, "e": 1494, "s": 1450, "text": "timeout − The timeout for network operation" }, { "code": null, "e": 1572, "s": 1494, "text": "The ftp_connect() function returns an FTP stream on success or FALSE on error" }, { "code": null, "e": 1658, "s": 1572, "text": "The following is an example: to open an FTP connection, to work in it and closing it." }, { "code": null, "e": 2050, "s": 1658, "text": "<?php\n $ftp_server=\"192.168.0.4\";\n $ftp_user=\"amit\";\n $ftp_pass=\"tywg61gh\";\n $con = ftp_connect($ftp_server); \n $res = ftp_login($con, $ftp_user, $ftp_pass);\n ftp_chdir($con, 'demo');\n echo ftp_pwd($con);\n if (ftp_cdup($con)) {\n echo \"Directory changed!\\n\";\n } else {\n echo \"Directory change not successful!\\n\";\n }\n echo ftp_pwd($con);\n ftp_close($con);\n?>" } ]
Beginner’s Guide to TensorFlow 2.x for Deep Learning Applications | by Orhan G. Yalçın | Towards Data Science
If you are reading this article, I am sure that we share similar interests and are/will be in similar industries. So let’s connect via Linkedin! Please do not hesitate to send a contact request! Orhan G. Yalçın — Linkedin If you have recently started learning machine learning, you might have already realized the power of artificial neural networks and deep learning compared to traditional machine learning. Compared to other models, artificial neural networks require an extra set of technical skills and conceptual knowledge. The most important of these technical skills is the ability to use a deep learning framework. A good deep learning framework speeds up the development process and provides efficient data processing, visualization, and deployment tools. When it comes to choosing a deep learning framework, as of 2020, you only have two viable options : Well, we can compare TensorFlow an PyTorch for days, but this post is not about framework benchmarking. This post is about what you can achieve with TensorFlow. TensorFlow is an end-to-end framework and platform designed to build and train machine learning models, especially deep learning models. It was developed by Google and released as an open-source platform in 2015. The two programming languages with stable and official TensorFlow APIs are Python and C. Besides, C++, Java, JavaScript, Go, and Swift are other programming languages where developers may find limited-to-extensive TensorFlow compatibility. Most developers end up using Python since Python has compelling data libraries such as NumPy, pandas, and Matplotlib. There are several advantages of using a powerful deep learning framework, and the non-exhaustive list below points out to some of them: Reduced time to build and train models; Useful data processing tools; Compatibility with other popular data libraries such as NumPy, matplotlib, and pandas; A rich catalog of pre-trained models with TF Hub; Tools to deploy trained models across different devices such as iOS, Android, Windows, macOS, and Web; Great community support; A desirable skill by tech companies. Currently, we are using the second major version of TensorFlow: TensorFlow 2.x. It took almost nine years to achieve this level of maturity. However, I can say that we are still in the beginning phase of the ultimate deep learning platform because the current trends indicate that deep learning processes will be much more streamlined in the future. Some claims that API based practices will be the standard way of using deep learning and artificial neural networks. But, let’s not get ahead of ourselves and take a look at the history of the TensorFlow platform: The TensorFlow team deliberately uses the term platform since its deep learning library is just a part of the whole technology. I — In 2011, Google Brain developed a proprietary machine learning library for internal Google use, called DistBelief. DistBelief was primarily used for Google’s core businesses, such as Google Search and Google Ads. I — In 2015, to speed up the advancements in artificial intelligence, Google decided to release TensorFlow as an open-source library. Tensorflow Beta was released. I — In 2016, Google announced Tensor Processing Units (TPUs). Tensors are the building bricks of TensorFlow applications, and as the name suggests, TPUs are specially designed ASICs for deep learning operations. ASIC stands for application-specific integrated circuit. ASICs are customized for a particular use such as deep learning or cryptocurrency mining, rather than general-purpose use. The Developments of 2017: I — In February, TensorFlow 1.0 was released, setting a milestone. Before February 2017, TensorFlow was still in 0.x.x versions, the initial development process. In general, version 1.0.0 defines the public API with a stable production capability.Therefore, February 2017 was indeed a big milestone for TensorFlow. I — Seeing the rapid advancements in mobile technologies, the TensorFlow team announced TensorFlow Lite, a library for machine learning development in mobile devices, in May 2017. I — Finally, in December 2017, Google introduced KubeFlow. Kubeflow is an open-source platform that allows operation and deployment of TensorFlow models on Kubernetes. In other words, “the Machine Learning Toolkit for Kubernetes” The Developments of 2018: I — In March, Google announced TensorFlow.js 1.0, which enable developers to implement and serve machine learning models using JavaScript. I — In July 2018, Google announced the Edge TPU. Edge TPU is Google’s purpose-built ASIC designed to run TensorFlow Lite machine learning (ML) models on smartphones. The Developments of 2019: I — In January 2019, the TensorFlow team announced the official release date for TensorFlow 2.0.0: September 2019. I — In May 2019, TensorFlow Graphics was announced to tackle issues related to graphic rendering and 3D modeling. I — In September 2019, the TensorFlow team released TensorFlow 2.0, the current major version, which streamlined many of the inconveniencies of building neural networks. I — With version 2.0, TensorFlow finally embraced Keras as the official main High-level API to build, train, evaluate neural networks. I — TensorFlow 2.0 streamlined the data loading and processing tools and provided newly added features. I — Eager Execution was made the default option, replacing Graph execution. This strategy was adopted because PyTorch has attracted many researchers with eager execution. With Eager execution, TensorFlow calculates the values of tensors as they occur in your code. As you can see, TensorFlow is much more than a deep learning library for Python. It is an end-to-end platform that you can process your data, build & train machine learning models, serve the trained models across different devices with different programming languages. Below you can see the current diagram of the TensorFlow platform: As of 2020, the real competition is taking place between TensorFlow and PyTorch. Due to its maturity, extensive support in multiple programming languages, popularity in the job market, extensive community support, and supporting technologies, TensorFlow currently has the upper hand. In 2018, Jeff Hale developed a power ranking for the deep learning frameworks in the market. He weighs the mentions found in the online job listings, the relevant articles and the blog posts, and on GitHub. Since 2018, PyTorch has achieved an upward momentum, and I believe it must have a higher score by now. But, I believe TensorFlow still has superiority over PyTorch due to its maturity. You have come to this point, and I hope you already developed an understanding of what TensorFlow is and how you can benefit from it. If you are convinced to learn TensorFlow, in the next posts, I will explain the topics below with actual code examples: The very basics of TensorFlow: Tensors, Variables, and Eager Execution; and Five major capabilities of TensorFlow 2.x that cover the entire deep learning pipeline operations. The second post is already published: towardsdatascience.com And the third one: towardsdatascience.com You can follow my account and subscribe to my newsletter: Subscribe Now Over the years, TensorFlow turned into a big platform covering every need of machine learning experts from head to toe. There is still a long way to go, but we are far ahead compared to where we were ten years ago. Join the rise of this new technology and learn to implement your own deep learning models with TensorFlow's help. Don’t miss out... Finally, if you are interested in applied deep learning tutorials, check out some of my articles:
[ { "code": null, "e": 394, "s": 171, "text": "If you are reading this article, I am sure that we share similar interests and are/will be in similar industries. So let’s connect via Linkedin! Please do not hesitate to send a contact request! Orhan G. Yalçın — Linkedin" }, { "code": null, "e": 702, "s": 394, "text": "If you have recently started learning machine learning, you might have already realized the power of artificial neural networks and deep learning compared to traditional machine learning. Compared to other models, artificial neural networks require an extra set of technical skills and conceptual knowledge." }, { "code": null, "e": 1038, "s": 702, "text": "The most important of these technical skills is the ability to use a deep learning framework. A good deep learning framework speeds up the development process and provides efficient data processing, visualization, and deployment tools. When it comes to choosing a deep learning framework, as of 2020, you only have two viable options :" }, { "code": null, "e": 1199, "s": 1038, "text": "Well, we can compare TensorFlow an PyTorch for days, but this post is not about framework benchmarking. This post is about what you can achieve with TensorFlow." }, { "code": null, "e": 1412, "s": 1199, "text": "TensorFlow is an end-to-end framework and platform designed to build and train machine learning models, especially deep learning models. It was developed by Google and released as an open-source platform in 2015." }, { "code": null, "e": 1770, "s": 1412, "text": "The two programming languages with stable and official TensorFlow APIs are Python and C. Besides, C++, Java, JavaScript, Go, and Swift are other programming languages where developers may find limited-to-extensive TensorFlow compatibility. Most developers end up using Python since Python has compelling data libraries such as NumPy, pandas, and Matplotlib." }, { "code": null, "e": 1906, "s": 1770, "text": "There are several advantages of using a powerful deep learning framework, and the non-exhaustive list below points out to some of them:" }, { "code": null, "e": 1946, "s": 1906, "text": "Reduced time to build and train models;" }, { "code": null, "e": 1976, "s": 1946, "text": "Useful data processing tools;" }, { "code": null, "e": 2063, "s": 1976, "text": "Compatibility with other popular data libraries such as NumPy, matplotlib, and pandas;" }, { "code": null, "e": 2113, "s": 2063, "text": "A rich catalog of pre-trained models with TF Hub;" }, { "code": null, "e": 2216, "s": 2113, "text": "Tools to deploy trained models across different devices such as iOS, Android, Windows, macOS, and Web;" }, { "code": null, "e": 2241, "s": 2216, "text": "Great community support;" }, { "code": null, "e": 2278, "s": 2241, "text": "A desirable skill by tech companies." }, { "code": null, "e": 2842, "s": 2278, "text": "Currently, we are using the second major version of TensorFlow: TensorFlow 2.x. It took almost nine years to achieve this level of maturity. However, I can say that we are still in the beginning phase of the ultimate deep learning platform because the current trends indicate that deep learning processes will be much more streamlined in the future. Some claims that API based practices will be the standard way of using deep learning and artificial neural networks. But, let’s not get ahead of ourselves and take a look at the history of the TensorFlow platform:" }, { "code": null, "e": 2970, "s": 2842, "text": "The TensorFlow team deliberately uses the term platform since its deep learning library is just a part of the whole technology." }, { "code": null, "e": 3187, "s": 2970, "text": "I — In 2011, Google Brain developed a proprietary machine learning library for internal Google use, called DistBelief. DistBelief was primarily used for Google’s core businesses, such as Google Search and Google Ads." }, { "code": null, "e": 3351, "s": 3187, "text": "I — In 2015, to speed up the advancements in artificial intelligence, Google decided to release TensorFlow as an open-source library. Tensorflow Beta was released." }, { "code": null, "e": 3563, "s": 3351, "text": "I — In 2016, Google announced Tensor Processing Units (TPUs). Tensors are the building bricks of TensorFlow applications, and as the name suggests, TPUs are specially designed ASICs for deep learning operations." }, { "code": null, "e": 3743, "s": 3563, "text": "ASIC stands for application-specific integrated circuit. ASICs are customized for a particular use such as deep learning or cryptocurrency mining, rather than general-purpose use." }, { "code": null, "e": 3769, "s": 3743, "text": "The Developments of 2017:" }, { "code": null, "e": 4084, "s": 3769, "text": "I — In February, TensorFlow 1.0 was released, setting a milestone. Before February 2017, TensorFlow was still in 0.x.x versions, the initial development process. In general, version 1.0.0 defines the public API with a stable production capability.Therefore, February 2017 was indeed a big milestone for TensorFlow." }, { "code": null, "e": 4264, "s": 4084, "text": "I — Seeing the rapid advancements in mobile technologies, the TensorFlow team announced TensorFlow Lite, a library for machine learning development in mobile devices, in May 2017." }, { "code": null, "e": 4494, "s": 4264, "text": "I — Finally, in December 2017, Google introduced KubeFlow. Kubeflow is an open-source platform that allows operation and deployment of TensorFlow models on Kubernetes. In other words, “the Machine Learning Toolkit for Kubernetes”" }, { "code": null, "e": 4520, "s": 4494, "text": "The Developments of 2018:" }, { "code": null, "e": 4659, "s": 4520, "text": "I — In March, Google announced TensorFlow.js 1.0, which enable developers to implement and serve machine learning models using JavaScript." }, { "code": null, "e": 4825, "s": 4659, "text": "I — In July 2018, Google announced the Edge TPU. Edge TPU is Google’s purpose-built ASIC designed to run TensorFlow Lite machine learning (ML) models on smartphones." }, { "code": null, "e": 4851, "s": 4825, "text": "The Developments of 2019:" }, { "code": null, "e": 4966, "s": 4851, "text": "I — In January 2019, the TensorFlow team announced the official release date for TensorFlow 2.0.0: September 2019." }, { "code": null, "e": 5080, "s": 4966, "text": "I — In May 2019, TensorFlow Graphics was announced to tackle issues related to graphic rendering and 3D modeling." }, { "code": null, "e": 5250, "s": 5080, "text": "I — In September 2019, the TensorFlow team released TensorFlow 2.0, the current major version, which streamlined many of the inconveniencies of building neural networks." }, { "code": null, "e": 5385, "s": 5250, "text": "I — With version 2.0, TensorFlow finally embraced Keras as the official main High-level API to build, train, evaluate neural networks." }, { "code": null, "e": 5489, "s": 5385, "text": "I — TensorFlow 2.0 streamlined the data loading and processing tools and provided newly added features." }, { "code": null, "e": 5660, "s": 5489, "text": "I — Eager Execution was made the default option, replacing Graph execution. This strategy was adopted because PyTorch has attracted many researchers with eager execution." }, { "code": null, "e": 5754, "s": 5660, "text": "With Eager execution, TensorFlow calculates the values of tensors as they occur in your code." }, { "code": null, "e": 6089, "s": 5754, "text": "As you can see, TensorFlow is much more than a deep learning library for Python. It is an end-to-end platform that you can process your data, build & train machine learning models, serve the trained models across different devices with different programming languages. Below you can see the current diagram of the TensorFlow platform:" }, { "code": null, "e": 6373, "s": 6089, "text": "As of 2020, the real competition is taking place between TensorFlow and PyTorch. Due to its maturity, extensive support in multiple programming languages, popularity in the job market, extensive community support, and supporting technologies, TensorFlow currently has the upper hand." }, { "code": null, "e": 6765, "s": 6373, "text": "In 2018, Jeff Hale developed a power ranking for the deep learning frameworks in the market. He weighs the mentions found in the online job listings, the relevant articles and the blog posts, and on GitHub. Since 2018, PyTorch has achieved an upward momentum, and I believe it must have a higher score by now. But, I believe TensorFlow still has superiority over PyTorch due to its maturity." }, { "code": null, "e": 7019, "s": 6765, "text": "You have come to this point, and I hope you already developed an understanding of what TensorFlow is and how you can benefit from it. If you are convinced to learn TensorFlow, in the next posts, I will explain the topics below with actual code examples:" }, { "code": null, "e": 7095, "s": 7019, "text": "The very basics of TensorFlow: Tensors, Variables, and Eager Execution; and" }, { "code": null, "e": 7194, "s": 7095, "text": "Five major capabilities of TensorFlow 2.x that cover the entire deep learning pipeline operations." }, { "code": null, "e": 7232, "s": 7194, "text": "The second post is already published:" }, { "code": null, "e": 7255, "s": 7232, "text": "towardsdatascience.com" }, { "code": null, "e": 7274, "s": 7255, "text": "And the third one:" }, { "code": null, "e": 7297, "s": 7274, "text": "towardsdatascience.com" }, { "code": null, "e": 7355, "s": 7297, "text": "You can follow my account and subscribe to my newsletter:" }, { "code": null, "e": 7369, "s": 7355, "text": "Subscribe Now" }, { "code": null, "e": 7716, "s": 7369, "text": "Over the years, TensorFlow turned into a big platform covering every need of machine learning experts from head to toe. There is still a long way to go, but we are far ahead compared to where we were ten years ago. Join the rise of this new technology and learn to implement your own deep learning models with TensorFlow's help. Don’t miss out..." } ]
Addition of two number using ‘-‘ operator?
Operator overloading is an important concept in C++. It is a type of polymorphism in which an operator is overloaded to give user-defined meaning to it. The overloaded operator is used to perform the operation on the user-defined data type. For example, '+' operator can be overloaded to perform addition on various data types, like for Integer, String(concatenation), etc. Input 10 20 20 30 Output 30 50 To perform addition of two numbers using ‘-‘ operator by Operator overloading. Binary operators will require one object as an argument so they can perform the operation. If we are using Friend functions here then it will need two arguments. The operator is being invoked: ob1-ob2. The object before the operator will invoke the function and the object after the operator will be passed as an argument to the function. So, in this case, ob1 is invoking object and ob2 is passed as an argument to the function. We are passing 10, 20 as the values of ob1’s x and y and 20, 30 as the values of ob2’s x and y. #include <iostream> using namespace std; class sum { public: int x, y, z; void getdata(int a, int b) { x=a; y=b; } void display() { cout<<"\nSum of X:"<<x; cout<<"\nSum of Y:"<<y; } void operator-(sum &); }; void sum::operator-(sum &ob) { x=x+ob.x; y=y+ob.y; display(); } int main() { sum ob1, ob2; ob1.getdata(10,20); ob2.getdata(20,30); ob1-ob2; }
[ { "code": null, "e": 1436, "s": 1062, "text": "Operator overloading is an important concept in C++. It is a type of polymorphism in which an operator is overloaded to give user-defined meaning to it. The overloaded operator is used to perform the operation on the user-defined data type. For example, '+' operator can be overloaded to perform addition on various data types, like for Integer, String(concatenation), etc." }, { "code": null, "e": 1442, "s": 1436, "text": "Input" }, { "code": null, "e": 1454, "s": 1442, "text": "10 20\n20 30" }, { "code": null, "e": 1461, "s": 1454, "text": "Output" }, { "code": null, "e": 1467, "s": 1461, "text": "30\n50" }, { "code": null, "e": 1708, "s": 1467, "text": "To perform addition of two numbers using ‘-‘ operator by Operator overloading. Binary operators will require one object as an argument so they can perform the operation. If we are using Friend functions here then it will need two arguments." }, { "code": null, "e": 1976, "s": 1708, "text": "The operator is being invoked: ob1-ob2. The object before the operator will invoke the function and the object after the operator will be passed as an argument to the function. So, in this case, ob1 is invoking object and ob2 is passed as an argument to the function." }, { "code": null, "e": 2072, "s": 1976, "text": "We are passing 10, 20 as the values of ob1’s x and y and 20, 30 as the values of ob2’s x and y." }, { "code": null, "e": 2491, "s": 2072, "text": "#include <iostream>\nusing namespace std;\nclass sum {\n public:\n int x, y, z;\n void getdata(int a, int b) {\n x=a;\n y=b;\n }\n void display() {\n cout<<\"\\nSum of X:\"<<x;\n cout<<\"\\nSum of Y:\"<<y;\n }\n void operator-(sum &);\n};\nvoid sum::operator-(sum &ob) {\n x=x+ob.x;\n y=y+ob.y;\n display();\n}\nint main() {\n sum ob1, ob2;\n ob1.getdata(10,20);\n ob2.getdata(20,30);\n ob1-ob2;\n}" } ]
How to add a character to the beginning of every word in a string in JavaScript?
We are required to write a function that takes in two strings, we have to return a new string which is just the same as the first of the two arguments but have second argument prepended to its every word. For example − Input → ‘hello stranger, how are you’, ‘@@’ Output → ‘@@hello @@stranger, @@how @@are @@you’ If second argument is not provided, take ‘#’ as default. const str = 'hello stranger, how are you'; const prependString = (str, text = '#') => { return str .split(" ") .map(word => `${text}${word}`) .join(" "); }; console.log(prependString(str)); console.log(prependString(str, '43')); The output in the console will be − #hello #stranger, #how #are #you 43hello 43stranger, 43how 43are 43you
[ { "code": null, "e": 1267, "s": 1062, "text": "We are required to write a function that takes in two strings, we have to return a new string\nwhich is just the same as the first of the two arguments but have second argument prepended\nto its every word." }, { "code": null, "e": 1281, "s": 1267, "text": "For example −" }, { "code": null, "e": 1374, "s": 1281, "text": "Input → ‘hello stranger, how are you’, ‘@@’\nOutput → ‘@@hello @@stranger, @@how @@are @@you’" }, { "code": null, "e": 1431, "s": 1374, "text": "If second argument is not provided, take ‘#’ as default." }, { "code": null, "e": 1675, "s": 1431, "text": "const str = 'hello stranger, how are you';\nconst prependString = (str, text = '#') => {\n return str\n .split(\" \")\n .map(word => `${text}${word}`)\n .join(\" \");\n};\nconsole.log(prependString(str));\nconsole.log(prependString(str, '43'));" }, { "code": null, "e": 1711, "s": 1675, "text": "The output in the console will be −" }, { "code": null, "e": 1782, "s": 1711, "text": "#hello #stranger, #how #are #you\n43hello 43stranger, 43how 43are 43you" } ]
Teradata - SELECT Statement
SELECT statement is used to retrieve records from a table. Following is the basic syntax of SELECT statement. SELECT column 1, column 2, ..... FROM tablename; Consider the following employee table. Following is an example of SELECT statement. SELECT EmployeeNo,FirstName,LastName FROM Employee; When this query is executed, it fetches EmployeeNo, FirstName and LastName columns from the employee table. EmployeeNo FirstName LastName ----------- ------------------------------ --------------------------- 101 Mike James 104 Alex Stuart 102 Robert Williams 105 Robert James 103 Peter Paul If you want to fetch all the columns from a table, you can use the following command instead of listing down all columns. SELECT * FROM Employee; The above query will fetch all records from the employee table. WHERE clause is used to filter the records returned by the SELECT statement. A condition is associated with WHERE clause. Only, the records that satisfy the condition in the WHERE clause are returned. Following is the syntax of the SELECT statement with WHERE clause. SELECT * FROM tablename WHERE[condition]; The following query fetches records where EmployeeNo is 101. SELECT * FROM Employee WHERE EmployeeNo = 101; When this query is executed, it returns the following records. EmployeeNo FirstName LastName ----------- ------------------------------ ----------------------------- 101 Mike James When the SELECT statement is executed, the returned rows are not in any specific order. ORDER BY clause is used to arrange the records in ascending/descending order on any columns. Following is the syntax of the SELECT statement with ORDER BY clause. SELECT * FROM tablename ORDER BY column 1, column 2..; The following query fetches records from the employee table and orders the results by FirstName. SELECT * FROM Employee ORDER BY FirstName; When the above query is executed, it produces the following output. EmployeeNo FirstName LastName ----------- ------------------------------ ----------------------------- 104 Alex Stuart 101 Mike James 103 Peter Paul 102 Robert Williams 105 Robert James GROUP BY clause is used with SELECT statement and arranges similar records into groups. Following is the syntax of the SELECT statement with GROUP BY clause. SELECT column 1, column2 .... FROM tablename GROUP BY column 1, column 2..; The following example groups the records by DepartmentNo column and identifies the total count from each department. SELECT DepartmentNo,Count(*) FROM Employee GROUP BY DepartmentNo; When the above query is executed, it produces the following output. DepartmentNo Count(*) ------------ ----------- 3 1 1 1 2 3 Print Add Notes Bookmark this page
[ { "code": null, "e": 2689, "s": 2630, "text": "SELECT statement is used to retrieve records from a table." }, { "code": null, "e": 2740, "s": 2689, "text": "Following is the basic syntax of SELECT statement." }, { "code": null, "e": 2794, "s": 2740, "text": "SELECT \ncolumn 1, column 2, ..... \nFROM \ntablename;\n" }, { "code": null, "e": 2833, "s": 2794, "text": "Consider the following employee table." }, { "code": null, "e": 2878, "s": 2833, "text": "Following is an example of SELECT statement." }, { "code": null, "e": 2931, "s": 2878, "text": "SELECT EmployeeNo,FirstName,LastName \nFROM Employee;" }, { "code": null, "e": 3039, "s": 2931, "text": "When this query is executed, it fetches EmployeeNo, FirstName and LastName columns from the employee table." }, { "code": null, "e": 3501, "s": 3039, "text": " EmployeeNo FirstName LastName \n----------- ------------------------------ --------------------------- \n 101 Mike James \n 104 Alex Stuart \n 102 Robert Williams \n 105 Robert James \n 103 Peter Paul\n" }, { "code": null, "e": 3623, "s": 3501, "text": "If you want to fetch all the columns from a table, you can use the following command instead of listing down all columns." }, { "code": null, "e": 3648, "s": 3623, "text": "SELECT * FROM Employee;\n" }, { "code": null, "e": 3712, "s": 3648, "text": "The above query will fetch all records from the employee table." }, { "code": null, "e": 3913, "s": 3712, "text": "WHERE clause is used to filter the records returned by the SELECT statement. A condition is associated with WHERE clause. Only, the records that satisfy the condition in the WHERE clause are returned." }, { "code": null, "e": 3980, "s": 3913, "text": "Following is the syntax of the SELECT statement with WHERE clause." }, { "code": null, "e": 4024, "s": 3980, "text": "SELECT * FROM tablename \nWHERE[condition];\n" }, { "code": null, "e": 4085, "s": 4024, "text": "The following query fetches records where EmployeeNo is 101." }, { "code": null, "e": 4133, "s": 4085, "text": "SELECT * FROM Employee \nWHERE EmployeeNo = 101;" }, { "code": null, "e": 4196, "s": 4133, "text": "When this query is executed, it returns the following records." }, { "code": null, "e": 4394, "s": 4196, "text": " EmployeeNo FirstName LastName \n----------- ------------------------------ ----------------------------- \n 101 Mike James \n" }, { "code": null, "e": 4575, "s": 4394, "text": "When the SELECT statement is executed, the returned rows are not in any specific order. ORDER BY clause is used to arrange the records in ascending/descending order on any columns." }, { "code": null, "e": 4645, "s": 4575, "text": "Following is the syntax of the SELECT statement with ORDER BY clause." }, { "code": null, "e": 4702, "s": 4645, "text": "SELECT * FROM tablename \nORDER BY column 1, column 2..;\n" }, { "code": null, "e": 4799, "s": 4702, "text": "The following query fetches records from the employee table and orders the results by FirstName." }, { "code": null, "e": 4843, "s": 4799, "text": "SELECT * FROM Employee \nORDER BY FirstName;" }, { "code": null, "e": 4911, "s": 4843, "text": "When the above query is executed, it produces the following output." }, { "code": null, "e": 5350, "s": 4911, "text": " EmployeeNo FirstName LastName \n----------- ------------------------------ ----------------------------- \n 104 Alex Stuart \n 101 Mike James \n 103 Peter Paul \n 102 Robert Williams \n 105 Robert James \n" }, { "code": null, "e": 5438, "s": 5350, "text": "GROUP BY clause is used with SELECT statement and arranges similar records into groups." }, { "code": null, "e": 5508, "s": 5438, "text": "Following is the syntax of the SELECT statement with GROUP BY clause." }, { "code": null, "e": 5586, "s": 5508, "text": "SELECT column 1, column2 .... FROM tablename \nGROUP BY column 1, column 2..;\n" }, { "code": null, "e": 5703, "s": 5586, "text": "The following example groups the records by DepartmentNo column and identifies the total count from each department." }, { "code": null, "e": 5773, "s": 5703, "text": "SELECT DepartmentNo,Count(*) FROM \nEmployee \nGROUP BY DepartmentNo;" }, { "code": null, "e": 5841, "s": 5773, "text": "When the above query is executed, it produces the following output." }, { "code": null, "e": 5962, "s": 5841, "text": " DepartmentNo Count(*) \n------------ ----------- \n 3 1 \n 1 1 \n 2 3 \n" }, { "code": null, "e": 5969, "s": 5962, "text": " Print" }, { "code": null, "e": 5980, "s": 5969, "text": " Add Notes" } ]
Group by function in R using Dplyr - GeeksforGeeks
31 Aug, 2021 Group_by() function belongs to the dplyr package in the R programming language, which groups the data frames. Group_by() function alone will not give any output. It should be followed by summarise() function with an appropriate action to perform. It works similar to GROUP BY in SQL and pivot table in excel. Syntax: group_by(col,...) Syntax: group_by(col,..) %>% summarise(action) The dataset in use: Sample_Superstore This is the simplest way by which a column can be grouped, just pass the name of the column to be grouped in the group_by() function and the action to be performed on this grouped column in summarise() function. Example: Grouping single column by group_by() R library(dplyr) df = read.csv("Sample_Superstore.csv") df_grp_region = df %>% group_by(Region) %>% summarise(total_sales = sum(Sales), total_profits = sum(Profit), .groups = 'drop') View(df_grp_region) Output: Group_by() function can also be performed on two or more columns, the column names need to be in the correct order. The grouping will occur according to the first column name in the group_by function and then the grouping will be done according to the second column. Example: Grouping multiple columns R library(dplyr) df = read.csv("Sample_Superstore.csv") df_grp_reg_cat = df %>% group_by(Region, Category) %>% summarise(total_Sales = sum(Sales), total_Profit = sum(Profit), .groups = 'drop') View(df_grp_reg_cat) Output: We can also calculate mean, count, minimum or maximum by replacing the sum in the summarise or aggregate function. For example, we will find mean sales and profits for the same group_by example above. Example: R library(dplyr) df = read.csv("Sample_Superstore.csv") df_grp_reg_cat = df %>% group_by(Region, Category) %>% summarise(mean_Sales = mean(Sales), mean_Profit = mean(Profit), .groups = 'drop') View(df_grp_reg_cat) Output: pasulakiransai Picked R Dplyr R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Loops in R (for, while, repeat) How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Data Visualization in R Printing Output of an R Program Logistic Regression in R Programming K-Means Clustering in R Programming Remove rows with NA in one column of R DataFrame
[ { "code": null, "e": 24592, "s": 24564, "text": "\n31 Aug, 2021" }, { "code": null, "e": 24901, "s": 24592, "text": "Group_by() function belongs to the dplyr package in the R programming language, which groups the data frames. Group_by() function alone will not give any output. It should be followed by summarise() function with an appropriate action to perform. It works similar to GROUP BY in SQL and pivot table in excel." }, { "code": null, "e": 24909, "s": 24901, "text": "Syntax:" }, { "code": null, "e": 24927, "s": 24909, "text": "group_by(col,...)" }, { "code": null, "e": 24935, "s": 24927, "text": "Syntax:" }, { "code": null, "e": 24974, "s": 24935, "text": "group_by(col,..) %>% summarise(action)" }, { "code": null, "e": 24994, "s": 24974, "text": "The dataset in use:" }, { "code": null, "e": 25012, "s": 24994, "text": "Sample_Superstore" }, { "code": null, "e": 25224, "s": 25012, "text": "This is the simplest way by which a column can be grouped, just pass the name of the column to be grouped in the group_by() function and the action to be performed on this grouped column in summarise() function." }, { "code": null, "e": 25270, "s": 25224, "text": "Example: Grouping single column by group_by()" }, { "code": null, "e": 25272, "s": 25270, "text": "R" }, { "code": "library(dplyr) df = read.csv(\"Sample_Superstore.csv\") df_grp_region = df %>% group_by(Region) %>% summarise(total_sales = sum(Sales), total_profits = sum(Profit), .groups = 'drop') View(df_grp_region)", "e": 25551, "s": 25272, "text": null }, { "code": null, "e": 25559, "s": 25551, "text": "Output:" }, { "code": null, "e": 25828, "s": 25561, "text": "Group_by() function can also be performed on two or more columns, the column names need to be in the correct order. The grouping will occur according to the first column name in the group_by function and then the grouping will be done according to the second column." }, { "code": null, "e": 25863, "s": 25828, "text": "Example: Grouping multiple columns" }, { "code": null, "e": 25865, "s": 25863, "text": "R" }, { "code": "library(dplyr) df = read.csv(\"Sample_Superstore.csv\") df_grp_reg_cat = df %>% group_by(Region, Category) %>% summarise(total_Sales = sum(Sales), total_Profit = sum(Profit), .groups = 'drop') View(df_grp_reg_cat)", "e": 26151, "s": 25865, "text": null }, { "code": null, "e": 26159, "s": 26151, "text": "Output:" }, { "code": null, "e": 26360, "s": 26159, "text": "We can also calculate mean, count, minimum or maximum by replacing the sum in the summarise or aggregate function. For example, we will find mean sales and profits for the same group_by example above." }, { "code": null, "e": 26370, "s": 26360, "text": "Example: " }, { "code": null, "e": 26372, "s": 26370, "text": "R" }, { "code": "library(dplyr) df = read.csv(\"Sample_Superstore.csv\") df_grp_reg_cat = df %>% group_by(Region, Category) %>% summarise(mean_Sales = mean(Sales), mean_Profit = mean(Profit), .groups = 'drop') View(df_grp_reg_cat)", "e": 26658, "s": 26372, "text": null }, { "code": null, "e": 26666, "s": 26658, "text": "Output:" }, { "code": null, "e": 26681, "s": 26666, "text": "pasulakiransai" }, { "code": null, "e": 26688, "s": 26681, "text": "Picked" }, { "code": null, "e": 26696, "s": 26688, "text": "R Dplyr" }, { "code": null, "e": 26707, "s": 26696, "text": "R Language" }, { "code": null, "e": 26805, "s": 26707, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26814, "s": 26805, "text": "Comments" }, { "code": null, "e": 26827, "s": 26814, "text": "Old Comments" }, { "code": null, "e": 26859, "s": 26827, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 26917, "s": 26859, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 26969, "s": 26917, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 27013, "s": 26969, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 27065, "s": 27013, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27089, "s": 27065, "text": "Data Visualization in R" }, { "code": null, "e": 27121, "s": 27089, "text": "Printing Output of an R Program" }, { "code": null, "e": 27158, "s": 27121, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 27194, "s": 27158, "text": "K-Means Clustering in R Programming" } ]
Find if there is a path between two vertices in a directed graph | Set 2 - GeeksforGeeks
30 Jun, 2021 Given a Directed Graph and two vertices in it, check whether there is a path from the first given vertex to second. Example: Consider the following Graph: Input : (u, v) = (1, 3) Output: Yes Explanation: There is a path from 1 to 3, 1 -> 2 -> 3 Input : (u, v) = (3, 6) Output: No Explanation: There is no path from 3 to 6 A BFS or DFS based solution of this problem is discussed here.Approach: Here we will discuss a Dynamic Programming based solution using Floyd Warshall Algorithm. Create a boolean 2D matrix mat where mat[i][j] will be true if there is a path from vertex i to j. For every starting vertex i and ending vertex j iterate over all intermediate vertex k and do check if there is a path for i to j through k then mark mat[i][j] as true. Finally, check if mat[u][v] is true then return true else return false. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find if there is a// path between two vertices in a// directed graph using Dynamic Programming #include <bits/stdc++.h>using namespace std;#define X 6#define Z 2 // function to find if there is a// path between two vertices in a// directed graphbool existPath(int V, int edges[X][Z], int u, int v){ // dp matrix bool mat[V][V]; memset(mat, false, sizeof(mat)); // set dp[i][j]=true if there is // edge between i to j for (int i = 0; i < X; i++) mat[edges[i][0]][edges[i][1]] = true; // check for all intermediate vertex for (int k = 0; k < V; k++) { for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { mat[i][j] = mat[i][j] || mat[i][k] && mat[k][j]; } } } // if vertex is invalid if (u >= V || v >= V) { return false; } // if there is a path if (mat[u][v]) return true; return false;} // Driver functionint main(){ int V = 4; int edges[X][Z] = { { 0, 2 }, { 0, 1 }, { 1, 2 }, { 2, 3 }, { 2, 0 }, { 3, 3 } }; int u = 1, v = 3; if (existPath(V, edges, u, v)) cout << "Yes\n"; else cout << "No\n"; return 0;} // Java program to find if there is a path// between two vertices in a directed graph// using Dynamic Programmingimport java.util.*; class GFG{ static final int X = 6;static final int Z = 2; // Function to find if there is a// path between two vertices in a// directed graphstatic boolean existPath(int V, int edges[][], int u, int v){ // mat matrix boolean [][]mat = new boolean[V][V]; // set mat[i][j]=true if there is // edge between i to j for (int i = 0; i < X; i++) mat[edges[i][0]][edges[i][1]] = true; // Check for all intermediate vertex for(int k = 0; k < V; k++) { for(int i = 0; i < V; i++) { for(int j = 0; j < V; j++) { mat[i][j] = mat[i][j] || mat[i][k] && mat[k][j]; } } } // If vertex is invalid if (u >= V || v >= V) { return false; } // If there is a path if (mat[u][v]) return true; return false;} // Driver codepublic static void main(String[] args){ int V = 4; int edges[][] = { { 0, 2 }, { 0, 1 }, { 1, 2 }, { 2, 3 }, { 2, 0 }, { 3, 3 } }; int u = 1, v = 3; if (existPath(V, edges, u, v)) System.out.print("Yes\n"); else System.out.print("No\n");}} // This code is contributed by Princi Singh # Python3 program to find if there# is a path between two vertices in a# directed graph using Dynamic ProgrammingX = 6Z = 2 # Function to find if there is a# path between two vertices in a# directed graphdef existPath(V, edges, u, v): # dp matrix mat = [[False for i in range(V)] for j in range(V)] # Set dp[i][j]=true if there is # edge between i to j for i in range(X): mat[edges[i][0]][edges[i][1]] = True # Check for all intermediate vertex for k in range(V): for i in range(V): for j in range(V): mat[i][j] = (mat[i][j] or mat[i][k] and mat[k][j]) # If vertex is invalid if (u >= V or v >= V): return False # If there is a path if (mat[u][v]): return True return False # Driver codeV = 4edges = [ [ 0, 2 ], [ 0, 1 ], [ 1, 2 ], [ 2, 3 ], [ 2, 0 ], [ 3, 3 ] ] u, v = 1, 3 if (existPath(V, edges, u, v)): print("Yes")else: print("No") # This code is contributed by divyeshrabadiya07 // C# program to find if there is a path// between two vertices in a directed graph// using Dynamic Programmingusing System;class GFG{ static readonly int X = 6;static readonly int Z = 2; // Function to find if there is a// path between two vertices in a// directed graphstatic bool existPath(int V, int [,]edges, int u, int v){ // mat matrix bool [,]mat = new bool[V, V]; // set mat[i,j]=true if there is // edge between i to j for (int i = 0; i < X; i++) mat[edges[i, 0], edges[i, 1]] = true; // Check for all intermediate vertex for(int k = 0; k < V; k++) { for(int i = 0; i < V; i++) { for(int j = 0; j < V; j++) { mat[i, j] = mat[i, j] || mat[i, k] && mat[k, j]; } } } // If vertex is invalid if (u >= V || v >= V) { return false; } // If there is a path if (mat[u, v]) return true; return false;} // Driver codepublic static void Main(String[] args){ int V = 4; int [,]edges = { { 0, 2 }, { 0, 1 }, { 1, 2 }, { 2, 3 }, { 2, 0 }, { 3, 3 } }; int u = 1, v = 3; if (existPath(V, edges, u, v)) Console.Write("Yes\n"); else Console.Write("No\n");}} // This code is contributed by sapnasingh4991 <script> // Javascript program to find if there is a path// between two vertices in a directed graph// using Dynamic Programming var X = 6;var Z = 2; // Function to find if there is a// path between two vertices in a// directed graphfunction existPath(V, edges, u, v){ // mat matrix var mat = Array.from(Array(V), ()=>Array(V)); // set mat[i,j]=true if there is // edge between i to j for (var i = 0; i < X; i++) mat[edges[i][0]][edges[i][1]] = true; // Check for all intermediate vertex for(var k = 0; k < V; k++) { for(var i = 0; i < V; i++) { for(var j = 0; j < V; j++) { mat[i][j] = mat[i][j] || mat[i][k] && mat[k][j]; } } } // If vertex is invalid if (u >= V || v >= V) { return false; } // If there is a path if (mat[u][v]) return true; return false;} // Driver codevar V = 4;var edges = [ [ 0, 2 ], [ 0, 1 ], [ 1, 2 ], [ 2, 3 ], [ 2, 0 ], [ 3, 3 ] ];var u = 1, v = 3;if (existPath(V, edges, u, v)) document.write("Yes<br>");else document.write("No<br>"); </script> Yes Time Complexity : O ( V 3) Auxiliary Space : O ( V 2) princi singh sapnasingh4991 divyeshrabadiya07 noob2000 Algorithms Data Structures Dynamic Programming Graph Matrix Data Structures Dynamic Programming Matrix Graph 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? Difference between Informed and Uninformed Search in AI SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Doubly Linked List | Set 1 (Introduction and Insertion) Implementing a Linked List in Java using Class Introduction to Algorithms
[ { "code": null, "e": 24871, "s": 24843, "text": "\n30 Jun, 2021" }, { "code": null, "e": 24987, "s": 24871, "text": "Given a Directed Graph and two vertices in it, check whether there is a path from the first given vertex to second." }, { "code": null, "e": 24997, "s": 24987, "text": "Example: " }, { "code": null, "e": 25029, "s": 24997, "text": "Consider the following Graph: " }, { "code": null, "e": 25119, "s": 25029, "text": "Input : (u, v) = (1, 3) Output: Yes Explanation: There is a path from 1 to 3, 1 -> 2 -> 3" }, { "code": null, "e": 25198, "s": 25119, "text": "Input : (u, v) = (3, 6) Output: No Explanation: There is no path from 3 to 6 " }, { "code": null, "e": 25361, "s": 25198, "text": "A BFS or DFS based solution of this problem is discussed here.Approach: Here we will discuss a Dynamic Programming based solution using Floyd Warshall Algorithm. " }, { "code": null, "e": 25460, "s": 25361, "text": "Create a boolean 2D matrix mat where mat[i][j] will be true if there is a path from vertex i to j." }, { "code": null, "e": 25629, "s": 25460, "text": "For every starting vertex i and ending vertex j iterate over all intermediate vertex k and do check if there is a path for i to j through k then mark mat[i][j] as true." }, { "code": null, "e": 25701, "s": 25629, "text": "Finally, check if mat[u][v] is true then return true else return false." }, { "code": null, "e": 25753, "s": 25701, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25757, "s": 25753, "text": "C++" }, { "code": null, "e": 25762, "s": 25757, "text": "Java" }, { "code": null, "e": 25770, "s": 25762, "text": "Python3" }, { "code": null, "e": 25773, "s": 25770, "text": "C#" }, { "code": null, "e": 25784, "s": 25773, "text": "Javascript" }, { "code": "// C++ program to find if there is a// path between two vertices in a// directed graph using Dynamic Programming #include <bits/stdc++.h>using namespace std;#define X 6#define Z 2 // function to find if there is a// path between two vertices in a// directed graphbool existPath(int V, int edges[X][Z], int u, int v){ // dp matrix bool mat[V][V]; memset(mat, false, sizeof(mat)); // set dp[i][j]=true if there is // edge between i to j for (int i = 0; i < X; i++) mat[edges[i][0]][edges[i][1]] = true; // check for all intermediate vertex for (int k = 0; k < V; k++) { for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { mat[i][j] = mat[i][j] || mat[i][k] && mat[k][j]; } } } // if vertex is invalid if (u >= V || v >= V) { return false; } // if there is a path if (mat[u][v]) return true; return false;} // Driver functionint main(){ int V = 4; int edges[X][Z] = { { 0, 2 }, { 0, 1 }, { 1, 2 }, { 2, 3 }, { 2, 0 }, { 3, 3 } }; int u = 1, v = 3; if (existPath(V, edges, u, v)) cout << \"Yes\\n\"; else cout << \"No\\n\"; return 0;}", "e": 27076, "s": 25784, "text": null }, { "code": "// Java program to find if there is a path// between two vertices in a directed graph// using Dynamic Programmingimport java.util.*; class GFG{ static final int X = 6;static final int Z = 2; // Function to find if there is a// path between two vertices in a// directed graphstatic boolean existPath(int V, int edges[][], int u, int v){ // mat matrix boolean [][]mat = new boolean[V][V]; // set mat[i][j]=true if there is // edge between i to j for (int i = 0; i < X; i++) mat[edges[i][0]][edges[i][1]] = true; // Check for all intermediate vertex for(int k = 0; k < V; k++) { for(int i = 0; i < V; i++) { for(int j = 0; j < V; j++) { mat[i][j] = mat[i][j] || mat[i][k] && mat[k][j]; } } } // If vertex is invalid if (u >= V || v >= V) { return false; } // If there is a path if (mat[u][v]) return true; return false;} // Driver codepublic static void main(String[] args){ int V = 4; int edges[][] = { { 0, 2 }, { 0, 1 }, { 1, 2 }, { 2, 3 }, { 2, 0 }, { 3, 3 } }; int u = 1, v = 3; if (existPath(V, edges, u, v)) System.out.print(\"Yes\\n\"); else System.out.print(\"No\\n\");}} // This code is contributed by Princi Singh", "e": 28493, "s": 27076, "text": null }, { "code": "# Python3 program to find if there# is a path between two vertices in a# directed graph using Dynamic ProgrammingX = 6Z = 2 # Function to find if there is a# path between two vertices in a# directed graphdef existPath(V, edges, u, v): # dp matrix mat = [[False for i in range(V)] for j in range(V)] # Set dp[i][j]=true if there is # edge between i to j for i in range(X): mat[edges[i][0]][edges[i][1]] = True # Check for all intermediate vertex for k in range(V): for i in range(V): for j in range(V): mat[i][j] = (mat[i][j] or mat[i][k] and mat[k][j]) # If vertex is invalid if (u >= V or v >= V): return False # If there is a path if (mat[u][v]): return True return False # Driver codeV = 4edges = [ [ 0, 2 ], [ 0, 1 ], [ 1, 2 ], [ 2, 3 ], [ 2, 0 ], [ 3, 3 ] ] u, v = 1, 3 if (existPath(V, edges, u, v)): print(\"Yes\")else: print(\"No\") # This code is contributed by divyeshrabadiya07", "e": 29596, "s": 28493, "text": null }, { "code": "// C# program to find if there is a path// between two vertices in a directed graph// using Dynamic Programmingusing System;class GFG{ static readonly int X = 6;static readonly int Z = 2; // Function to find if there is a// path between two vertices in a// directed graphstatic bool existPath(int V, int [,]edges, int u, int v){ // mat matrix bool [,]mat = new bool[V, V]; // set mat[i,j]=true if there is // edge between i to j for (int i = 0; i < X; i++) mat[edges[i, 0], edges[i, 1]] = true; // Check for all intermediate vertex for(int k = 0; k < V; k++) { for(int i = 0; i < V; i++) { for(int j = 0; j < V; j++) { mat[i, j] = mat[i, j] || mat[i, k] && mat[k, j]; } } } // If vertex is invalid if (u >= V || v >= V) { return false; } // If there is a path if (mat[u, v]) return true; return false;} // Driver codepublic static void Main(String[] args){ int V = 4; int [,]edges = { { 0, 2 }, { 0, 1 }, { 1, 2 }, { 2, 3 }, { 2, 0 }, { 3, 3 } }; int u = 1, v = 3; if (existPath(V, edges, u, v)) Console.Write(\"Yes\\n\"); else Console.Write(\"No\\n\");}} // This code is contributed by sapnasingh4991", "e": 30988, "s": 29596, "text": null }, { "code": "<script> // Javascript program to find if there is a path// between two vertices in a directed graph// using Dynamic Programming var X = 6;var Z = 2; // Function to find if there is a// path between two vertices in a// directed graphfunction existPath(V, edges, u, v){ // mat matrix var mat = Array.from(Array(V), ()=>Array(V)); // set mat[i,j]=true if there is // edge between i to j for (var i = 0; i < X; i++) mat[edges[i][0]][edges[i][1]] = true; // Check for all intermediate vertex for(var k = 0; k < V; k++) { for(var i = 0; i < V; i++) { for(var j = 0; j < V; j++) { mat[i][j] = mat[i][j] || mat[i][k] && mat[k][j]; } } } // If vertex is invalid if (u >= V || v >= V) { return false; } // If there is a path if (mat[u][v]) return true; return false;} // Driver codevar V = 4;var edges = [ [ 0, 2 ], [ 0, 1 ], [ 1, 2 ], [ 2, 3 ], [ 2, 0 ], [ 3, 3 ] ];var u = 1, v = 3;if (existPath(V, edges, u, v)) document.write(\"Yes<br>\");else document.write(\"No<br>\"); </script>", "e": 32204, "s": 30988, "text": null }, { "code": null, "e": 32208, "s": 32204, "text": "Yes" }, { "code": null, "e": 32265, "s": 32210, "text": "Time Complexity : O ( V 3) Auxiliary Space : O ( V 2) " }, { "code": null, "e": 32280, "s": 32267, "text": "princi singh" }, { "code": null, "e": 32295, "s": 32280, "text": "sapnasingh4991" }, { "code": null, "e": 32313, "s": 32295, "text": "divyeshrabadiya07" }, { "code": null, "e": 32322, "s": 32313, "text": "noob2000" }, { "code": null, "e": 32333, "s": 32322, "text": "Algorithms" }, { "code": null, "e": 32349, "s": 32333, "text": "Data Structures" }, { "code": null, "e": 32369, "s": 32349, "text": "Dynamic Programming" }, { "code": null, "e": 32375, "s": 32369, "text": "Graph" }, { "code": null, "e": 32382, "s": 32375, "text": "Matrix" }, { "code": null, "e": 32398, "s": 32382, "text": "Data Structures" }, { "code": null, "e": 32418, "s": 32398, "text": "Dynamic Programming" }, { "code": null, "e": 32425, "s": 32418, "text": "Matrix" }, { "code": null, "e": 32431, "s": 32425, "text": "Graph" }, { "code": null, "e": 32442, "s": 32431, "text": "Algorithms" }, { "code": null, "e": 32540, "s": 32442, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32549, "s": 32540, "text": "Comments" }, { "code": null, "e": 32562, "s": 32549, "text": "Old Comments" }, { "code": null, "e": 32611, "s": 32562, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 32636, "s": 32611, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 32663, "s": 32636, "text": "Introduction to Algorithms" }, { "code": null, "e": 32691, "s": 32663, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 32747, "s": 32691, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 32796, "s": 32747, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 32821, "s": 32796, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 32877, "s": 32821, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 32924, "s": 32877, "text": "Implementing a Linked List in Java using Class" } ]
How to setup the Python and Spark environment for development, with good software engineering practices | by Bogdan Cojocar | Towards Data Science
In this article we will discuss about how to set up our development environment in order to create good quality python code and how to automate some of the tedious tasks to speed up deployments. We will go over the following steps: setup our dependencies in a isolated virtual environment with pipenv how to setup a project structure for multiple jobs how to run a pyspark job how to use a Makefile to automate development steps how to test the quality of our code using flake8 how to run unit tests for PySpark apps using pytest-spark running a test coverage, to see if we have created enough unit tests using pytest-cov A virtual environment helps us to isolate the dependencies for a specific application from the overall dependencies of the system. This is great because we will not get into dependencies issues with the existing libraries, and it’s easier to install or uninstall them on a separate system, say a docker container or a server. For this task we will use pipenv. To install it on a mac os system for example run: brew install pipenv To declare our dependencies (libraries) for the app we need to create a Pipfile in the route path of our project: [[source]]url = 'https://pypi.python.org/simple'verify_ssl = truename = 'pypi'[requires]python_version = "3.6"[packages]flake8 = "*"pytest-spark = ">=0.4.4"pyspark = ">=2.4.0"pytest-cov = "*" There are three components here. In the [[source]] tag we declare the url from where all the packages are downloaded, in [requires] we define the python version, and finally in [packages] the dependencies that we need. We can bound a dependency to a certain version, or just take the latest one using the “*”symbol. To create the virtual environment and to activate it, we need to run two commands in the terminal: pipenv --three installpipenv shell Once this is done once, you should see you are in a new venv by having the name of the project appearing in the terminal at the command line (by default the env is takes the name of the project): (pyspark-project-template) host:project$ Now you can move in and out using two commands. Deactivate env and move back to the standard env: deactivate Activate the virtual environment again (you need to be in the root of the project): source `pipenv --venv`/bin/activate The project can have the following structure: pyspark-project-template src/ jobs/ pi/ __init__.py resources/ args.json word_count/ __init__.py resources/ args.json word_count.csv main.py test/ jobs/ pi/ test_pi.py word_count/ test_word_count.py Some __init__.py files are excluded to make things simpler, but you can find the link on github to the complete project at the end of the tutorial. We basically have the source code and the tests. Each job is separated into a folder, and each job has a resource folder where we add the extra files and configurations that that job needs. In this tutorial I have used two classic examples — pi, to generate the pi number up to a number of decimals, and word count, to count the number of words in a csv file. Let’s see first how the main.py files looks like: When we run our job we need two command line arguments: — job, is the name of the job we want to run (in out case pi or word_count) and — res-path, is the relative path to the jobs. We need the second argument because spark needs to know the full path to our resources. In a production environment, where we deploy our code on a cluster, we would move our resources to HDFS or S3, and we would use that path instead. Before explaining the code further, we need to mention that we have to zip the job folder and pass it to the spark-submit statement. Assuming we are in the root of the project: cd src/ zip -r ../jobs.zip jobs/ This will make the code available as a module in our app. Basically in main.py at line 16, we are programatically importing the job module. Both our jobs, pi and word_count, have a run function, so we just need to run this function, to start the job (line 17 in main.py). We also pass the configurations of the job there. Let’s have a look at our word_count job to understand further the example: This code is defined in the __init__.py file in the word_count folder. We can see here that we use two config parameters to read the csv file: the relative path, and the location of the csv file, in the resources folder. The rest of the code just counts the words, so we will not go into further details here. It’s worth to mention that each job has, in the resources folder an args.json file. Here we actually define the configuration that we pass to the job. This is the config file of the word_count job: { "words_file_path": "/word_count/resources/word_count.csv"} So we have all the details now to run our spark-submit command: spark-submit --py-files jobs.zip src/main.py --job word_count --res-path /your/path/pyspark-project-template/src/jobs To run the other job, pi, we just need to change the argument of the — job flag. To wrote tests for pyspark application we use pytest-spark, a really easy to use module. The word_count job unit tests: We need to import the functions that we want to test from the src module. The more interesting part here is how we do the test_word_count_run. We can see there is no spark session initialised, we just received it as a parameter in our test. This is thanks to the pytest-spark module, so we can concentrate on writing the tests, instead of writing boilerplate code. Next let’s discuss about code coverage. How do we know if we write enough unit tests? Easy, we run a test coverage tool, that tells us what code is not tested yet. For python we can use the pytest-cov module. To run all the tests using code coverage we have to run: pytest --cov=src test/jobs/ where — cov flag is telling pytest where to check for coverage. Test coverage results: ---------- coverage: platform darwin, python 3.7.2-final-0 -----------Name Stmts Miss Cover-----------------------------------------------------src/__init__.py 0 0 100%src/jobs/__init__.py 0 0 100%src/jobs/pi/__init__.py 11 0 100%src/jobs/word_count/__init__.py 9 0 100%-----------------------------------------------------TOTAL 20 0 100% Our test coverage is 100%, but wait a minute, one file is missing! Why is main.py not listed there? If we consider that we have python code that we don’t need to test, we can exclude it from the reports. To do this we need to create a .coveragerc file in the root of our project. For this example it looks something like this: [run]omit = src/main.py Great, we have some code, we can run it, we have unit tests with good coverage. We are done right? Not yet! We also need to make sure that we write easy to read code, following python best practices. To do this we have to inspect our code with a python module called flake8. To run it: flake8 ./src It will analyse the src folder. If we have clean code, we should get no warnings. But no, we have a few issues: flake8 ./src./src/jobs/pi/__init__.py:13:1: E302 expected 2 blank lines, found 1./src/jobs/pi/__init__.py:15:73: E231 missing whitespace after ','./src/jobs/pi/__init__.py:15:80: E501 line too long (113 > 79 characters) Let’s see the code: We can see we have an E302 warning at line 13. That means we need an extra line between the two methods. Then an E231 and E501 at line 15. The first warning on this line, tells us that we need an extra space between the range(1, number_of_steps +1), and config[ , and the second warning notifies us that the line is too long, and it’s hard to read (we can’t even see it in full in the gist!). After we solve all the warnings the code definitely looks easier to read: Because we have run a bunch of commands in the terminal, in this final step we are looking into how to simplify and automate this task. We can create a Makefile in the root of the project as the one bellow: .DEFAULT_GOAL := runinit: pipenv --three install pipenv shellanalyze: flake8 ./srcrun_tests: pytest --cov=src test/jobs/run: find . -name '__pycache__' | xargs rm -rf rm -f jobs.zip cd src/ && zip -r ../jobs.zip jobs/ spark-submit --py-files jobs.zip src/main.py --job $(JOB_NAME) --res-path $(CONF_PATH) If we want to run the tests with coverage, we can simply type: make run_tests And if we want to run the pi job: make run JOB_NAME=pi CONF_PATH=/your/path/pyspark-project-template/src/jobs That’s all folks! I hope you find this useful. As always the code is stored on github.
[ { "code": null, "e": 367, "s": 172, "text": "In this article we will discuss about how to set up our development environment in order to create good quality python code and how to automate some of the tedious tasks to speed up deployments." }, { "code": null, "e": 404, "s": 367, "text": "We will go over the following steps:" }, { "code": null, "e": 473, "s": 404, "text": "setup our dependencies in a isolated virtual environment with pipenv" }, { "code": null, "e": 524, "s": 473, "text": "how to setup a project structure for multiple jobs" }, { "code": null, "e": 549, "s": 524, "text": "how to run a pyspark job" }, { "code": null, "e": 601, "s": 549, "text": "how to use a Makefile to automate development steps" }, { "code": null, "e": 650, "s": 601, "text": "how to test the quality of our code using flake8" }, { "code": null, "e": 708, "s": 650, "text": "how to run unit tests for PySpark apps using pytest-spark" }, { "code": null, "e": 794, "s": 708, "text": "running a test coverage, to see if we have created enough unit tests using pytest-cov" }, { "code": null, "e": 1154, "s": 794, "text": "A virtual environment helps us to isolate the dependencies for a specific application from the overall dependencies of the system. This is great because we will not get into dependencies issues with the existing libraries, and it’s easier to install or uninstall them on a separate system, say a docker container or a server. For this task we will use pipenv." }, { "code": null, "e": 1204, "s": 1154, "text": "To install it on a mac os system for example run:" }, { "code": null, "e": 1224, "s": 1204, "text": "brew install pipenv" }, { "code": null, "e": 1338, "s": 1224, "text": "To declare our dependencies (libraries) for the app we need to create a Pipfile in the route path of our project:" }, { "code": null, "e": 1530, "s": 1338, "text": "[[source]]url = 'https://pypi.python.org/simple'verify_ssl = truename = 'pypi'[requires]python_version = \"3.6\"[packages]flake8 = \"*\"pytest-spark = \">=0.4.4\"pyspark = \">=2.4.0\"pytest-cov = \"*\"" }, { "code": null, "e": 1846, "s": 1530, "text": "There are three components here. In the [[source]] tag we declare the url from where all the packages are downloaded, in [requires] we define the python version, and finally in [packages] the dependencies that we need. We can bound a dependency to a certain version, or just take the latest one using the “*”symbol." }, { "code": null, "e": 1945, "s": 1846, "text": "To create the virtual environment and to activate it, we need to run two commands in the terminal:" }, { "code": null, "e": 1980, "s": 1945, "text": "pipenv --three installpipenv shell" }, { "code": null, "e": 2176, "s": 1980, "text": "Once this is done once, you should see you are in a new venv by having the name of the project appearing in the terminal at the command line (by default the env is takes the name of the project):" }, { "code": null, "e": 2218, "s": 2176, "text": "(pyspark-project-template) host:project$ " }, { "code": null, "e": 2266, "s": 2218, "text": "Now you can move in and out using two commands." }, { "code": null, "e": 2316, "s": 2266, "text": "Deactivate env and move back to the standard env:" }, { "code": null, "e": 2327, "s": 2316, "text": "deactivate" }, { "code": null, "e": 2411, "s": 2327, "text": "Activate the virtual environment again (you need to be in the root of the project):" }, { "code": null, "e": 2447, "s": 2411, "text": "source `pipenv --venv`/bin/activate" }, { "code": null, "e": 2493, "s": 2447, "text": "The project can have the following structure:" }, { "code": null, "e": 2913, "s": 2493, "text": "pyspark-project-template src/ jobs/ pi/ __init__.py resources/ args.json word_count/ __init__.py resources/ args.json word_count.csv main.py test/ jobs/ pi/ test_pi.py word_count/ test_word_count.py" }, { "code": null, "e": 3061, "s": 2913, "text": "Some __init__.py files are excluded to make things simpler, but you can find the link on github to the complete project at the end of the tutorial." }, { "code": null, "e": 3251, "s": 3061, "text": "We basically have the source code and the tests. Each job is separated into a folder, and each job has a resource folder where we add the extra files and configurations that that job needs." }, { "code": null, "e": 3421, "s": 3251, "text": "In this tutorial I have used two classic examples — pi, to generate the pi number up to a number of decimals, and word count, to count the number of words in a csv file." }, { "code": null, "e": 3471, "s": 3421, "text": "Let’s see first how the main.py files looks like:" }, { "code": null, "e": 3888, "s": 3471, "text": "When we run our job we need two command line arguments: — job, is the name of the job we want to run (in out case pi or word_count) and — res-path, is the relative path to the jobs. We need the second argument because spark needs to know the full path to our resources. In a production environment, where we deploy our code on a cluster, we would move our resources to HDFS or S3, and we would use that path instead." }, { "code": null, "e": 4065, "s": 3888, "text": "Before explaining the code further, we need to mention that we have to zip the job folder and pass it to the spark-submit statement. Assuming we are in the root of the project:" }, { "code": null, "e": 4098, "s": 4065, "text": "cd src/ zip -r ../jobs.zip jobs/" }, { "code": null, "e": 4238, "s": 4098, "text": "This will make the code available as a module in our app. Basically in main.py at line 16, we are programatically importing the job module." }, { "code": null, "e": 4420, "s": 4238, "text": "Both our jobs, pi and word_count, have a run function, so we just need to run this function, to start the job (line 17 in main.py). We also pass the configurations of the job there." }, { "code": null, "e": 4495, "s": 4420, "text": "Let’s have a look at our word_count job to understand further the example:" }, { "code": null, "e": 5003, "s": 4495, "text": "This code is defined in the __init__.py file in the word_count folder. We can see here that we use two config parameters to read the csv file: the relative path, and the location of the csv file, in the resources folder. The rest of the code just counts the words, so we will not go into further details here. It’s worth to mention that each job has, in the resources folder an args.json file. Here we actually define the configuration that we pass to the job. This is the config file of the word_count job:" }, { "code": null, "e": 5065, "s": 5003, "text": "{ \"words_file_path\": \"/word_count/resources/word_count.csv\"}" }, { "code": null, "e": 5129, "s": 5065, "text": "So we have all the details now to run our spark-submit command:" }, { "code": null, "e": 5247, "s": 5129, "text": "spark-submit --py-files jobs.zip src/main.py --job word_count --res-path /your/path/pyspark-project-template/src/jobs" }, { "code": null, "e": 5328, "s": 5247, "text": "To run the other job, pi, we just need to change the argument of the — job flag." }, { "code": null, "e": 5417, "s": 5328, "text": "To wrote tests for pyspark application we use pytest-spark, a really easy to use module." }, { "code": null, "e": 5448, "s": 5417, "text": "The word_count job unit tests:" }, { "code": null, "e": 5813, "s": 5448, "text": "We need to import the functions that we want to test from the src module. The more interesting part here is how we do the test_word_count_run. We can see there is no spark session initialised, we just received it as a parameter in our test. This is thanks to the pytest-spark module, so we can concentrate on writing the tests, instead of writing boilerplate code." }, { "code": null, "e": 6079, "s": 5813, "text": "Next let’s discuss about code coverage. How do we know if we write enough unit tests? Easy, we run a test coverage tool, that tells us what code is not tested yet. For python we can use the pytest-cov module. To run all the tests using code coverage we have to run:" }, { "code": null, "e": 6107, "s": 6079, "text": "pytest --cov=src test/jobs/" }, { "code": null, "e": 6171, "s": 6107, "text": "where — cov flag is telling pytest where to check for coverage." }, { "code": null, "e": 6194, "s": 6171, "text": "Test coverage results:" }, { "code": null, "e": 6689, "s": 6194, "text": "---------- coverage: platform darwin, python 3.7.2-final-0 -----------Name Stmts Miss Cover-----------------------------------------------------src/__init__.py 0 0 100%src/jobs/__init__.py 0 0 100%src/jobs/pi/__init__.py 11 0 100%src/jobs/word_count/__init__.py 9 0 100%-----------------------------------------------------TOTAL 20 0 100%" }, { "code": null, "e": 6789, "s": 6689, "text": "Our test coverage is 100%, but wait a minute, one file is missing! Why is main.py not listed there?" }, { "code": null, "e": 7016, "s": 6789, "text": "If we consider that we have python code that we don’t need to test, we can exclude it from the reports. To do this we need to create a .coveragerc file in the root of our project. For this example it looks something like this:" }, { "code": null, "e": 7040, "s": 7016, "text": "[run]omit = src/main.py" }, { "code": null, "e": 7315, "s": 7040, "text": "Great, we have some code, we can run it, we have unit tests with good coverage. We are done right? Not yet! We also need to make sure that we write easy to read code, following python best practices. To do this we have to inspect our code with a python module called flake8." }, { "code": null, "e": 7326, "s": 7315, "text": "To run it:" }, { "code": null, "e": 7339, "s": 7326, "text": "flake8 ./src" }, { "code": null, "e": 7451, "s": 7339, "text": "It will analyse the src folder. If we have clean code, we should get no warnings. But no, we have a few issues:" }, { "code": null, "e": 7671, "s": 7451, "text": "flake8 ./src./src/jobs/pi/__init__.py:13:1: E302 expected 2 blank lines, found 1./src/jobs/pi/__init__.py:15:73: E231 missing whitespace after ','./src/jobs/pi/__init__.py:15:80: E501 line too long (113 > 79 characters)" }, { "code": null, "e": 7691, "s": 7671, "text": "Let’s see the code:" }, { "code": null, "e": 8084, "s": 7691, "text": "We can see we have an E302 warning at line 13. That means we need an extra line between the two methods. Then an E231 and E501 at line 15. The first warning on this line, tells us that we need an extra space between the range(1, number_of_steps +1), and config[ , and the second warning notifies us that the line is too long, and it’s hard to read (we can’t even see it in full in the gist!)." }, { "code": null, "e": 8158, "s": 8084, "text": "After we solve all the warnings the code definitely looks easier to read:" }, { "code": null, "e": 8294, "s": 8158, "text": "Because we have run a bunch of commands in the terminal, in this final step we are looking into how to simplify and automate this task." }, { "code": null, "e": 8365, "s": 8294, "text": "We can create a Makefile in the root of the project as the one bellow:" }, { "code": null, "e": 8670, "s": 8365, "text": ".DEFAULT_GOAL := runinit: pipenv --three install pipenv shellanalyze: flake8 ./srcrun_tests: pytest --cov=src test/jobs/run: find . -name '__pycache__' | xargs rm -rf rm -f jobs.zip cd src/ && zip -r ../jobs.zip jobs/ spark-submit --py-files jobs.zip src/main.py --job $(JOB_NAME) --res-path $(CONF_PATH)" }, { "code": null, "e": 8733, "s": 8670, "text": "If we want to run the tests with coverage, we can simply type:" }, { "code": null, "e": 8748, "s": 8733, "text": "make run_tests" }, { "code": null, "e": 8782, "s": 8748, "text": "And if we want to run the pi job:" }, { "code": null, "e": 8858, "s": 8782, "text": "make run JOB_NAME=pi CONF_PATH=/your/path/pyspark-project-template/src/jobs" }, { "code": null, "e": 8905, "s": 8858, "text": "That’s all folks! I hope you find this useful." } ]
Excel Data Analysis - Lookup Functions
You can use Excel functions to − Find values in a range of data - VLOOKUP and HLOOKUP Obtain a value or the reference to a value from within a table or range - INDEX Obtain the relative position of a specified item in a range of cells - MATCH You can also combine these functions to get the required results based on the inputs you have. The syntax of the VLOOKUP function is VLOOKUP (lookup_value, table_array, col_index_num, [range_lookup]) Where lookup_value − is the value you want to look up. Lookup_value can be a value or a reference to a cell. Lookup_value must be in the first column of the range of cells you specify in table_array lookup_value − is the value you want to look up. Lookup_value can be a value or a reference to a cell. Lookup_value must be in the first column of the range of cells you specify in table_array table_array − is the range of cells in which the VLOOKUP will search for the lookup_value and the return value. table_array must contain the lookup_value in the first column, and the return value you want to find Note − The first column containing the lookup_value can either be sorted in ascending order or not. However, the result will be based on the order of this column. table_array − is the range of cells in which the VLOOKUP will search for the lookup_value and the return value. table_array must contain the lookup_value in the first column, and the lookup_value in the first column, and the return value you want to find Note − The first column containing the lookup_value can either be sorted in ascending order or not. However, the result will be based on the order of this column. the return value you want to find Note − The first column containing the lookup_value can either be sorted in ascending order or not. However, the result will be based on the order of this column. col_index_num − is the column number in the table_array that contains the return value. The numbers start with 1 for the left-most column of table-array col_index_num − is the column number in the table_array that contains the return value. The numbers start with 1 for the left-most column of table-array range_lookup − is an optional logical value that specifies whether you want VLOOKUP to find an exact match or an approximate match. range_lookup can be omitted, in which case it is assumed to be TRUE and VLOOKUP tries to find an approximate match TRUE, in which case VLOOKUP tries to find an approximate match. In other words, if an exact match is not found, the next largest value that is less than lookup_value is returned FALSE, in which case VLOOKUP tries to find an exact match 1, in which case it is assumed to be TRUE and VLOOKUP tries to find an approximate match 0, in which case it is assumed to be FALSE and VLOOKUP tries to find an exact match range_lookup − is an optional logical value that specifies whether you want VLOOKUP to find an exact match or an approximate match. range_lookup can be omitted, in which case it is assumed to be TRUE and VLOOKUP tries to find an approximate match omitted, in which case it is assumed to be TRUE and VLOOKUP tries to find an approximate match TRUE, in which case VLOOKUP tries to find an approximate match. In other words, if an exact match is not found, the next largest value that is less than lookup_value is returned TRUE, in which case VLOOKUP tries to find an approximate match. In other words, if an exact match is not found, the next largest value that is less than lookup_value is returned FALSE, in which case VLOOKUP tries to find an exact match FALSE, in which case VLOOKUP tries to find an exact match 1, in which case it is assumed to be TRUE and VLOOKUP tries to find an approximate match 1, in which case it is assumed to be TRUE and VLOOKUP tries to find an approximate match 0, in which case it is assumed to be FALSE and VLOOKUP tries to find an exact match 0, in which case it is assumed to be FALSE and VLOOKUP tries to find an exact match Note − If range_lookup is omitted or TRUE or 1, VLOOKUP works correctly only when the first column in table_array is sorted in ascending order. Otherwise, it may result in incorrect values. In such a case, use FALSE for range_lookup. Consider a list of student marks. You can obtain the corresponding grades with VLOOKUP from an array containing the marks intervals and pass category. table_array − Note that the first column marks based on which the grades are obtained is sorted in ascending order. Hence, using TRUE for range_lookup argument you can get approximate match that is what is required. Name this array as Grades. It is a good practice to name arrays in this way so that you need not remember the cell ranges. Now, you are ready to look up the grade for the list of marks you have as follows − As you can observe, col_index_num − indicates the column of the return value in table_array is 2 col_index_num − indicates the column of the return value in table_array is 2 the range_lookup is TRUE The first column containing the lookup value in the table_array grades is in ascending order. Hence, the results will be correct. You can get the return value for approximate matches also. i.e. VLOOKUP computes as follows − the range_lookup is TRUE The first column containing the lookup value in the table_array grades is in ascending order. Hence, the results will be correct. The first column containing the lookup value in the table_array grades is in ascending order. Hence, the results will be correct. You can get the return value for approximate matches also. i.e. VLOOKUP computes as follows − You can get the return value for approximate matches also. i.e. VLOOKUP computes as follows − You will get the following results − Consider a list of products containing the Product ID and price for each of the products. The product ID and price will be added to the end of the list whenever a new product is launched. This would mean that the product IDs need not be in ascending order. The product list might be as shown below − table_array − Name this array as ProductInfo. You can obtain the price of a product given the product ID with the VLOOKUP function as the product ID is in the first column. The price is in column 3 and hence col_index_ num should be 3. Use VLOOKUP Function with range_lookup as TRUE Use VLOOKUP Function with range_lookup as FALSE The correct answer is from the ProductInfo array is 171.65. You can check the results. You observe that you got − The correct result when range_lookup is FALSE, and A wrong result when range_lookup is TRUE. This is because, the first column in the ProductInfo array is not sorted in ascending order. Hence, remember to use FALSE whenever the data is not sorted. You can use HLOOKUP function if the data is in rows rather than columns. Let us take the example of product information. Suppose the array looks as follows − Name this Array ProductRange. You can find the price of a product given the product ID with HLOOKUP function. Name this Array ProductRange. You can find the price of a product given the product ID with HLOOKUP function. The Syntax of HLOOKUP function is HLOOKUP (lookup_value, table_array, row_index_num, [range_lookup]) Where lookup_value − is the value to be found in the first row of the table lookup_value − is the value to be found in the first row of the table table_array − is a table of information in which data is looked up table_array − is a table of information in which data is looked up row_index_num − is the row number in table_array from which the matching value will be returned row_index_num − is the row number in table_array from which the matching value will be returned range_lookup − is a logical value that specifies whether you want HLOOKUP to find an exact match or an approximate match range_lookup − is a logical value that specifies whether you want HLOOKUP to find an exact match or an approximate match range_lookup can be omitted, in which case it is assumed to be TRUE and HLOOKUP tries to find an approximate match TRUE, in which case HLOOKUP tries to find an approximate match. In other words, if an exact match is not found, the next largest value that is less than lookup_value is returned FALSE, in which case HLOOKUP tries to find an exact match 1, in which case it is assumed to be TRUE and HLOOKUP tries to find an approximate match 0, in which case it is assumed to be FALSE and HLOOKUP tries to find an exact match range_lookup can be omitted, in which case it is assumed to be TRUE and HLOOKUP tries to find an approximate match omitted, in which case it is assumed to be TRUE and HLOOKUP tries to find an approximate match TRUE, in which case HLOOKUP tries to find an approximate match. In other words, if an exact match is not found, the next largest value that is less than lookup_value is returned TRUE, in which case HLOOKUP tries to find an approximate match. In other words, if an exact match is not found, the next largest value that is less than lookup_value is returned FALSE, in which case HLOOKUP tries to find an exact match FALSE, in which case HLOOKUP tries to find an exact match 1, in which case it is assumed to be TRUE and HLOOKUP tries to find an approximate match 1, in which case it is assumed to be TRUE and HLOOKUP tries to find an approximate match 0, in which case it is assumed to be FALSE and HLOOKUP tries to find an exact match 0, in which case it is assumed to be FALSE and HLOOKUP tries to find an exact match Note − If range_lookup is Omitted or TRUE or 1, HLOOKUP works correctly only when the first column in table_array is sorted in ascending order. Otherwise, it may result in incorrect values. In such a case, use FALSE for range_lookup. You can obtain the price of a product given the product ID with the HLOOKUP function as the product ID is in the first row. The price is in row 3 and hence row_index_ num should be 3. Use HLOOKUP Function with range_lookup as TRUE. Use HLOOKUP Function with range_lookup as FALSE. The correct answer from the ProductRange array is 171.65. You can check the results. You observe that as in the case of VLOOKUP, you got The correct result when range_lookup is FALSE, and The correct result when range_lookup is FALSE, and A wrong result when range_lookup is TRUE. A wrong result when range_lookup is TRUE. This is because the first row in the ProductRange array is not sorted in ascending order. Hence, remember to use FALSE whenever the data is not sorted. Consider the example of student marks used in VLOOKUP. Suppose you have the data in rows instead of columns as shown in the table given below − table_array − Name this array as GradesRange. Note that the first row marks based on which the grades are obtained is sorted in ascending order. Hence, using HLOOKUP with TRUE for range_lookup argument, you can get the Grades with approximate match and that is what is required. As you can observe, row_index_num − indicates the column of the return value in table_array is 2 row_index_num − indicates the column of the return value in table_array is 2 the range_lookup is TRUE The first column containing the lookup value in the table_array Grades is in ascending order. Hence, the results will be correct. You can get the return value for approximate matches also. i.e. HLOOKUP computes as follows − the range_lookup is TRUE The first column containing the lookup value in the table_array Grades is in ascending order. Hence, the results will be correct. The first column containing the lookup value in the table_array Grades is in ascending order. Hence, the results will be correct. You can get the return value for approximate matches also. i.e. HLOOKUP computes as follows − You can get the return value for approximate matches also. i.e. HLOOKUP computes as follows − You will get the following results − When you have an array of data, you can retrieve a value in the array by specifying the row number and column number of that value in the array. Consider the following sales data, wherein you find the sales in each of the North, South, East and West regions by the salespersons who are listed. Name the array as SalesData. Using INDEX Function, you can find − The Sales of any of the Salespersons in a certain Region. Total Sales in a Region by all the Salespersons. Total Sales by a Salesperson in all the Regions. You will get the following results − Suppose you do not know the row numbers for the salespersons and column numbers for the regions. Then, you need to find the row number and column number first before you retrieve the value with the index function. You can do it with the MATCH function as explained in the next section. If you need the position of an item in a range, you can use the MATCH function. You can combine MATCH and INDEX functions as follows − You will get the following results − 102 Lectures 10 hours Pavan Lalwani 101 Lectures 6 hours Pavan Lalwani 56 Lectures 5.5 hours Pavan Lalwani 63 Lectures 3.5 hours Yoda Learning 134 Lectures 8.5 hours Yoda Learning 33 Lectures 3 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2667, "s": 2634, "text": "You can use Excel functions to −" }, { "code": null, "e": 2720, "s": 2667, "text": "Find values in a range of data - VLOOKUP and HLOOKUP" }, { "code": null, "e": 2800, "s": 2720, "text": "Obtain a value or the reference to a value from within a table or range - INDEX" }, { "code": null, "e": 2878, "s": 2800, "text": "Obtain the relative position of a specified item in a range of cells - MATCH" }, { "code": null, "e": 2973, "s": 2878, "text": "You can also combine these functions to get the required results based on the inputs you have." }, { "code": null, "e": 3011, "s": 2973, "text": "The syntax of the VLOOKUP function is" }, { "code": null, "e": 3079, "s": 3011, "text": "VLOOKUP (lookup_value, table_array, col_index_num, [range_lookup])\n" }, { "code": null, "e": 3085, "s": 3079, "text": "Where" }, { "code": null, "e": 3278, "s": 3085, "text": "lookup_value − is the value you want to look up. Lookup_value can be a value or a reference to a cell. Lookup_value must be in the first column of the range of cells you specify in table_array" }, { "code": null, "e": 3471, "s": 3278, "text": "lookup_value − is the value you want to look up. Lookup_value can be a value or a reference to a cell. Lookup_value must be in the first column of the range of cells you specify in table_array" }, { "code": null, "e": 3850, "s": 3471, "text": "table_array − is the range of cells in which the VLOOKUP will search for the lookup_value and the return value. table_array must contain\n\nthe lookup_value in the first column, and\nthe return value you want to find\nNote − The first column containing the lookup_value can either be sorted in ascending order or not. However, the result will be based on the order of this column.\n\n" }, { "code": null, "e": 3987, "s": 3850, "text": "table_array − is the range of cells in which the VLOOKUP will search for the lookup_value and the return value. table_array must contain" }, { "code": null, "e": 4029, "s": 3987, "text": "the lookup_value in the first column, and" }, { "code": null, "e": 4071, "s": 4029, "text": "the lookup_value in the first column, and" }, { "code": null, "e": 4268, "s": 4071, "text": "the return value you want to find\nNote − The first column containing the lookup_value can either be sorted in ascending order or not. However, the result will be based on the order of this column." }, { "code": null, "e": 4302, "s": 4268, "text": "the return value you want to find" }, { "code": null, "e": 4465, "s": 4302, "text": "Note − The first column containing the lookup_value can either be sorted in ascending order or not. However, the result will be based on the order of this column." }, { "code": null, "e": 4618, "s": 4465, "text": "col_index_num − is the column number in the table_array that contains the return value. The numbers start with 1 for the left-most column of table-array" }, { "code": null, "e": 4771, "s": 4618, "text": "col_index_num − is the column number in the table_array that contains the return value. The numbers start with 1 for the left-most column of table-array" }, { "code": null, "e": 5429, "s": 4771, "text": "range_lookup − is an optional logical value that specifies whether you want VLOOKUP to find an exact match or an approximate match. range_lookup can be\n\nomitted, in which case it is assumed to be TRUE and VLOOKUP tries to find an approximate match\nTRUE, in which case VLOOKUP tries to find an approximate match. In other words, if an exact match is not found, the next largest value that is less than lookup_value is returned\nFALSE, in which case VLOOKUP tries to find an exact match\n1, in which case it is assumed to be TRUE and VLOOKUP tries to find an approximate match\n0, in which case it is assumed to be FALSE and VLOOKUP tries to find an exact match\n" }, { "code": null, "e": 5581, "s": 5429, "text": "range_lookup − is an optional logical value that specifies whether you want VLOOKUP to find an exact match or an approximate match. range_lookup can be" }, { "code": null, "e": 5676, "s": 5581, "text": "omitted, in which case it is assumed to be TRUE and VLOOKUP tries to find an approximate match" }, { "code": null, "e": 5771, "s": 5676, "text": "omitted, in which case it is assumed to be TRUE and VLOOKUP tries to find an approximate match" }, { "code": null, "e": 5949, "s": 5771, "text": "TRUE, in which case VLOOKUP tries to find an approximate match. In other words, if an exact match is not found, the next largest value that is less than lookup_value is returned" }, { "code": null, "e": 6127, "s": 5949, "text": "TRUE, in which case VLOOKUP tries to find an approximate match. In other words, if an exact match is not found, the next largest value that is less than lookup_value is returned" }, { "code": null, "e": 6185, "s": 6127, "text": "FALSE, in which case VLOOKUP tries to find an exact match" }, { "code": null, "e": 6243, "s": 6185, "text": "FALSE, in which case VLOOKUP tries to find an exact match" }, { "code": null, "e": 6332, "s": 6243, "text": "1, in which case it is assumed to be TRUE and VLOOKUP tries to find an approximate match" }, { "code": null, "e": 6421, "s": 6332, "text": "1, in which case it is assumed to be TRUE and VLOOKUP tries to find an approximate match" }, { "code": null, "e": 6505, "s": 6421, "text": "0, in which case it is assumed to be FALSE and VLOOKUP tries to find an exact match" }, { "code": null, "e": 6589, "s": 6505, "text": "0, in which case it is assumed to be FALSE and VLOOKUP tries to find an exact match" }, { "code": null, "e": 6823, "s": 6589, "text": "Note − If range_lookup is omitted or TRUE or 1, VLOOKUP works correctly only when the first column in table_array is sorted in ascending order. Otherwise, it may result in incorrect values. In such a case, use FALSE for range_lookup." }, { "code": null, "e": 6974, "s": 6823, "text": "Consider a list of student marks. You can obtain the corresponding grades with VLOOKUP from an array containing the marks intervals and pass category." }, { "code": null, "e": 6988, "s": 6974, "text": "table_array −" }, { "code": null, "e": 7190, "s": 6988, "text": "Note that the first column marks based on which the grades are obtained is sorted in ascending order. Hence, using TRUE for range_lookup argument you can get approximate match that is what is required." }, { "code": null, "e": 7217, "s": 7190, "text": "Name this array as Grades." }, { "code": null, "e": 7397, "s": 7217, "text": "It is a good practice to name arrays in this way so that you need not remember the cell ranges. Now, you are ready to look up the grade for the list of marks you have as follows −" }, { "code": null, "e": 7417, "s": 7397, "text": "As you can observe," }, { "code": null, "e": 7495, "s": 7417, "text": "col_index_num − indicates the column of the return value in table_array is 2" }, { "code": null, "e": 7573, "s": 7495, "text": "col_index_num − indicates the column of the return value in table_array is 2" }, { "code": null, "e": 7824, "s": 7573, "text": "the range_lookup is TRUE\n\nThe first column containing the lookup value in the table_array grades is in ascending order. Hence, the results will be correct.\nYou can get the return value for approximate matches also. i.e. VLOOKUP computes as follows −\n" }, { "code": null, "e": 7849, "s": 7824, "text": "the range_lookup is TRUE" }, { "code": null, "e": 7979, "s": 7849, "text": "The first column containing the lookup value in the table_array grades is in ascending order. Hence, the results will be correct." }, { "code": null, "e": 8109, "s": 7979, "text": "The first column containing the lookup value in the table_array grades is in ascending order. Hence, the results will be correct." }, { "code": null, "e": 8203, "s": 8109, "text": "You can get the return value for approximate matches also. i.e. VLOOKUP computes as follows −" }, { "code": null, "e": 8297, "s": 8203, "text": "You can get the return value for approximate matches also. i.e. VLOOKUP computes as follows −" }, { "code": null, "e": 8334, "s": 8297, "text": "You will get the following results −" }, { "code": null, "e": 8634, "s": 8334, "text": "Consider a list of products containing the Product ID and price for each of the products. The product ID and price will be added to the end of the list whenever a new product is launched. This would mean that the product IDs need not be in ascending order. The product list might be as shown below −" }, { "code": null, "e": 8648, "s": 8634, "text": "table_array −" }, { "code": null, "e": 8680, "s": 8648, "text": "Name this array as ProductInfo." }, { "code": null, "e": 8870, "s": 8680, "text": "You can obtain the price of a product given the product ID with the VLOOKUP function as the product ID is in the first column. The price is in column 3 and hence col_index_ num should be 3." }, { "code": null, "e": 8917, "s": 8870, "text": "Use VLOOKUP Function with range_lookup as TRUE" }, { "code": null, "e": 8965, "s": 8917, "text": "Use VLOOKUP Function with range_lookup as FALSE" }, { "code": null, "e": 9052, "s": 8965, "text": "The correct answer is from the ProductInfo array is 171.65. You can check the results." }, { "code": null, "e": 9079, "s": 9052, "text": "You observe that you got −" }, { "code": null, "e": 9130, "s": 9079, "text": "The correct result when range_lookup is FALSE, and" }, { "code": null, "e": 9172, "s": 9130, "text": "A wrong result when range_lookup is TRUE." }, { "code": null, "e": 9327, "s": 9172, "text": "This is because, the first column in the ProductInfo array is not sorted in ascending order. Hence, remember to use FALSE whenever the data is not sorted." }, { "code": null, "e": 9400, "s": 9327, "text": "You can use HLOOKUP function if the data is in rows rather than columns." }, { "code": null, "e": 9485, "s": 9400, "text": "Let us take the example of product information. Suppose the array looks as follows −" }, { "code": null, "e": 9595, "s": 9485, "text": "Name this Array ProductRange. You can find the price of a product given the product ID with HLOOKUP function." }, { "code": null, "e": 9705, "s": 9595, "text": "Name this Array ProductRange. You can find the price of a product given the product ID with HLOOKUP function." }, { "code": null, "e": 9739, "s": 9705, "text": "The Syntax of HLOOKUP function is" }, { "code": null, "e": 9807, "s": 9739, "text": "HLOOKUP (lookup_value, table_array, row_index_num, [range_lookup])\n" }, { "code": null, "e": 9813, "s": 9807, "text": "Where" }, { "code": null, "e": 9883, "s": 9813, "text": "lookup_value − is the value to be found in the first row of the table" }, { "code": null, "e": 9953, "s": 9883, "text": "lookup_value − is the value to be found in the first row of the table" }, { "code": null, "e": 10020, "s": 9953, "text": "table_array − is a table of information in which data is looked up" }, { "code": null, "e": 10087, "s": 10020, "text": "table_array − is a table of information in which data is looked up" }, { "code": null, "e": 10183, "s": 10087, "text": "row_index_num − is the row number in table_array from which the matching value will be returned" }, { "code": null, "e": 10279, "s": 10183, "text": "row_index_num − is the row number in table_array from which the matching value will be returned" }, { "code": null, "e": 10400, "s": 10279, "text": "range_lookup − is a logical value that specifies whether you want HLOOKUP to find an exact match or an approximate match" }, { "code": null, "e": 10521, "s": 10400, "text": "range_lookup − is a logical value that specifies whether you want HLOOKUP to find an exact match or an approximate match" }, { "code": null, "e": 11047, "s": 10521, "text": "range_lookup can be\n\nomitted, in which case it is assumed to be TRUE and HLOOKUP tries to find an approximate match\nTRUE, in which case HLOOKUP tries to find an approximate match. In other words, if an exact match is not found, the next largest value that is less than lookup_value is returned\nFALSE, in which case HLOOKUP tries to find an exact match\n1, in which case it is assumed to be TRUE and HLOOKUP tries to find an approximate match\n0, in which case it is assumed to be FALSE and HLOOKUP tries to find an exact match\n" }, { "code": null, "e": 11067, "s": 11047, "text": "range_lookup can be" }, { "code": null, "e": 11162, "s": 11067, "text": "omitted, in which case it is assumed to be TRUE and HLOOKUP tries to find an approximate match" }, { "code": null, "e": 11257, "s": 11162, "text": "omitted, in which case it is assumed to be TRUE and HLOOKUP tries to find an approximate match" }, { "code": null, "e": 11435, "s": 11257, "text": "TRUE, in which case HLOOKUP tries to find an approximate match. In other words, if an exact match is not found, the next largest value that is less than lookup_value is returned" }, { "code": null, "e": 11613, "s": 11435, "text": "TRUE, in which case HLOOKUP tries to find an approximate match. In other words, if an exact match is not found, the next largest value that is less than lookup_value is returned" }, { "code": null, "e": 11671, "s": 11613, "text": "FALSE, in which case HLOOKUP tries to find an exact match" }, { "code": null, "e": 11729, "s": 11671, "text": "FALSE, in which case HLOOKUP tries to find an exact match" }, { "code": null, "e": 11818, "s": 11729, "text": "1, in which case it is assumed to be TRUE and HLOOKUP tries to find an approximate match" }, { "code": null, "e": 11907, "s": 11818, "text": "1, in which case it is assumed to be TRUE and HLOOKUP tries to find an approximate match" }, { "code": null, "e": 11991, "s": 11907, "text": "0, in which case it is assumed to be FALSE and HLOOKUP tries to find an exact match" }, { "code": null, "e": 12075, "s": 11991, "text": "0, in which case it is assumed to be FALSE and HLOOKUP tries to find an exact match" }, { "code": null, "e": 12309, "s": 12075, "text": "Note − If range_lookup is Omitted or TRUE or 1, HLOOKUP works correctly only when the first column in table_array is sorted in ascending order. Otherwise, it may result in incorrect values. In such a case, use FALSE for range_lookup." }, { "code": null, "e": 12493, "s": 12309, "text": "You can obtain the price of a product given the product ID with the HLOOKUP function as the product ID is in the first row. The price is in row 3 and hence row_index_ num should be 3." }, { "code": null, "e": 12541, "s": 12493, "text": "Use HLOOKUP Function with range_lookup as TRUE." }, { "code": null, "e": 12590, "s": 12541, "text": "Use HLOOKUP Function with range_lookup as FALSE." }, { "code": null, "e": 12675, "s": 12590, "text": "The correct answer from the ProductRange array is 171.65. You can check the results." }, { "code": null, "e": 12727, "s": 12675, "text": "You observe that as in the case of VLOOKUP, you got" }, { "code": null, "e": 12778, "s": 12727, "text": "The correct result when range_lookup is FALSE, and" }, { "code": null, "e": 12829, "s": 12778, "text": "The correct result when range_lookup is FALSE, and" }, { "code": null, "e": 12871, "s": 12829, "text": "A wrong result when range_lookup is TRUE." }, { "code": null, "e": 12913, "s": 12871, "text": "A wrong result when range_lookup is TRUE." }, { "code": null, "e": 13065, "s": 12913, "text": "This is because the first row in the ProductRange array is not sorted in ascending order. Hence, remember to use FALSE whenever the data is not sorted." }, { "code": null, "e": 13209, "s": 13065, "text": "Consider the example of student marks used in VLOOKUP. Suppose you have the data in rows instead of columns as shown in the table given below −" }, { "code": null, "e": 13223, "s": 13209, "text": "table_array −" }, { "code": null, "e": 13255, "s": 13223, "text": "Name this array as GradesRange." }, { "code": null, "e": 13488, "s": 13255, "text": "Note that the first row marks based on which the grades are obtained is sorted in ascending order. Hence, using HLOOKUP with TRUE for range_lookup argument, you can get the Grades with approximate match and that is what is required." }, { "code": null, "e": 13508, "s": 13488, "text": "As you can observe," }, { "code": null, "e": 13585, "s": 13508, "text": "row_index_num − indicates the column of the return value in table_array is 2" }, { "code": null, "e": 13662, "s": 13585, "text": "row_index_num − indicates the column of the return value in table_array is 2" }, { "code": null, "e": 13913, "s": 13662, "text": "the range_lookup is TRUE\n\nThe first column containing the lookup value in the table_array Grades is in ascending order. Hence, the results will be correct.\nYou can get the return value for approximate matches also. i.e. HLOOKUP computes as follows −\n" }, { "code": null, "e": 13938, "s": 13913, "text": "the range_lookup is TRUE" }, { "code": null, "e": 14068, "s": 13938, "text": "The first column containing the lookup value in the table_array Grades is in ascending order. Hence, the results will be correct." }, { "code": null, "e": 14198, "s": 14068, "text": "The first column containing the lookup value in the table_array Grades is in ascending order. Hence, the results will be correct." }, { "code": null, "e": 14292, "s": 14198, "text": "You can get the return value for approximate matches also. i.e. HLOOKUP computes as follows −" }, { "code": null, "e": 14386, "s": 14292, "text": "You can get the return value for approximate matches also. i.e. HLOOKUP computes as follows −" }, { "code": null, "e": 14423, "s": 14386, "text": "You will get the following results −" }, { "code": null, "e": 14568, "s": 14423, "text": "When you have an array of data, you can retrieve a value in the array by specifying the row number and column number of that value in the array." }, { "code": null, "e": 14717, "s": 14568, "text": "Consider the following sales data, wherein you find the sales in each of the North, South, East and West regions by the salespersons who are listed." }, { "code": null, "e": 14746, "s": 14717, "text": "Name the array as SalesData." }, { "code": null, "e": 14783, "s": 14746, "text": "Using INDEX Function, you can find −" }, { "code": null, "e": 14841, "s": 14783, "text": "The Sales of any of the Salespersons in a certain Region." }, { "code": null, "e": 14890, "s": 14841, "text": "Total Sales in a Region by all the Salespersons." }, { "code": null, "e": 14939, "s": 14890, "text": "Total Sales by a Salesperson in all the Regions." }, { "code": null, "e": 14976, "s": 14939, "text": "You will get the following results −" }, { "code": null, "e": 15190, "s": 14976, "text": "Suppose you do not know the row numbers for the salespersons and column numbers for the regions. Then, you need to find the row number and column number first before you retrieve the value with the index function." }, { "code": null, "e": 15262, "s": 15190, "text": "You can do it with the MATCH function as explained in the next section." }, { "code": null, "e": 15397, "s": 15262, "text": "If you need the position of an item in a range, you can use the MATCH function. You can combine MATCH and INDEX functions as follows −" }, { "code": null, "e": 15434, "s": 15397, "text": "You will get the following results −" }, { "code": null, "e": 15469, "s": 15434, "text": "\n 102 Lectures \n 10 hours \n" }, { "code": null, "e": 15484, "s": 15469, "text": " Pavan Lalwani" }, { "code": null, "e": 15518, "s": 15484, "text": "\n 101 Lectures \n 6 hours \n" }, { "code": null, "e": 15533, "s": 15518, "text": " Pavan Lalwani" }, { "code": null, "e": 15568, "s": 15533, "text": "\n 56 Lectures \n 5.5 hours \n" }, { "code": null, "e": 15583, "s": 15568, "text": " Pavan Lalwani" }, { "code": null, "e": 15618, "s": 15583, "text": "\n 63 Lectures \n 3.5 hours \n" }, { "code": null, "e": 15633, "s": 15618, "text": " Yoda Learning" }, { "code": null, "e": 15669, "s": 15633, "text": "\n 134 Lectures \n 8.5 hours \n" }, { "code": null, "e": 15684, "s": 15669, "text": " Yoda Learning" }, { "code": null, "e": 15717, "s": 15684, "text": "\n 33 Lectures \n 3 hours \n" }, { "code": null, "e": 15739, "s": 15717, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 15746, "s": 15739, "text": " Print" }, { "code": null, "e": 15757, "s": 15746, "text": " Add Notes" } ]
H2O Driverless AI: End-to-End Machine Learning (for anyone!) | by Rohan Gupta | Towards Data Science
In today’s world, being a Data Scientist is not limited to those without technical knowledge. While it is recommended and sometimes important to know a little bit of code, you can get by with just intuitive knowledge. Especially if you’re on H2O’s Driverless AI platform. If you haven’t heard of H2O.ai, it is the company that created the open-source machine learning platform, H2O, which is used by many in the Fortune 500. H2O aims at creating efficiency-driven machine learning environments by leveraging its user-friendly interface and modular capabilities. Note: Don't confuse the open-source H2O AI platform with the Driverless AI. They are two separate things. I suggest reading through the documentation on each to learn more. H2O 3 (open-source) is a free library on python/R that contains many ML algorithms, models and tuning features that make machine learning more efficient. The Driverless AI, on the other hand, is an enterprise product that has its own platform, UI and UX. It is like a web application that can be used to create and configure models using knobs and other visual apparatus that tune parameters, essentially replacing the tedious process of actually coding your model. The H2O DAI can build and validate AI models from scratch and the only thing required is your dataset. The data doesn’t even have to be cleaned or feature-engineered as the H2O DAI is built to handle those tasks and allows you to configure the automation of important steps such as feature scaling or applying categorical encoding on variables. Without further ado, I will begin the H2O Driverless AI tutorial. H2O Driverless AI is an enterprise product and therefore isn’t recommended for an individual to purchase. Instead, your firm should deploy H2O locally and allow employees to take advantage of its robust interface. However, you and I are individuals and for the purpose of this tutorial, I am using H2O’s 21-day free trial. You can do the same if you want to follow along and are not ready to purchase the product yet. Note: There are some requirements for running h2o on your machine. It is recommended that you run h2o on Linux or Windows, however, you can run it on a Mac using docker. You can learn how to do that here.I will go through the requirements for Windows since that’s what I’m using for this tutorial. If you’re on Linux (prod. environment recommended), follow these instructions. Start by visiting h2o.ai. Look for the Driverless AI product, fill out the form and download the latest stable version of the Driverless AI DEB. On Windows, there are 2 additional requirements: Windows subsystems for Linux (WSL) must be enabled as specified at https://docs.microsoft.com/en-us/windows/wsl/install-win10 Ubuntu 18.04 from the Windows Store. (Note that Ubuntu 16.04 for WSL is no longer supported.) So, you need to first install Ubuntu 18.04 for WSL (which you can activate if you “run as admin” (Instruction in the first link). Once that’s done, run the following commands in Ubuntu 18.04 LTS to install and run H2O-DAI: # Install Driverless AI. Expect installation of the .deb file to take several minutes on WSL.sudo dpkg -i dai_VERSION.deb# Run Driverless AI.sudo -H -u dai /opt/h2oai/dai/run-dai.sh Another way to install H2O-DAI on windows is through Docker. You can find specific instructions for that here. Get on your browser and in the URL box, type the followinglocalhost:12345 This should work if you installed H2O on a local machine. The general syntax for running an instance is <server>:12345 Use ‘localhost’ on a local server. It should then automatically launch the login page, which will look like this. For Trial Users, the login ID and password are both “h2oai”. Log in the details and click sign in. You should now see the Datasets page, wherein H2O will show you any past-uploaded data or other files stored on the system. H2O Driverless AI is very flexible when it comes to sourcing your data sets. Since a majority of its applications are on real-time/series data, H2O has the ability to extract information from a number of sources such as an Amazon S3 server, Hadoop file system, via Local upload, or the H2O file system. I uploaded a file from my computer, which is the Telco Customer Churn Database (from Kaggle). This file contains customer data, with each column (except customer ID) factoring in on the churn prediction. As soon as my data set was uploaded, I could access the Autoviz tab. When you visualize a data set through Autoviz, it will give you different kinds of possible plots to summarize your data. All you have to do is upload your data, and Autoviz will be ready to use. Some graphs are also interactive and can be moved around like in Plotly. All visuals are downloadable, so you can save them on your server or in a file system. To start any experiment or activity, you need to have a project. So go on the Project tab and it should look like this : You’ll now want to create a new project, just pick a name and description to start with. Once that’s done, you’ll have a screen like the one right below. This is where you manage your project, its data, and experiments. Use the Link Dataset button to link your files to this project. I’ve attached my data set on Customer Churn and it shows up under Training on the left side. If I right-click my dataset, I have the option of splitting it. I would need to split the dataset for training and testing, so I click Split and get the following options: I choose the names of the two different data sets, pick a Target column (The column we want to predict), folds and time-columns if necessary, and select the split ratio. I picked 0.75 since that would give me 2500 values in my test set, which is enough to test the model on. Every time you run a particular model on a data set, it’s called an experiment. H2O makes the process of model selection much easier with this feature. You can use multiple experiments to pick the right model. Go to your Project’s dashboard and click New Experiment. The Experiment Setup Assistant should open up. You can now start filling in the details of this experiment. Start with the name, then choose the training set. More details will show up (as you see in the GIF above). You can now select your Target Column, your test data set and you can change the training settings according to your needs. A personalized description of the model, according to the settings you’ve picked, will show up on the left side of the screen. You can even click on Expert Settings to go in deeper and change other parameters. Once you click on Launch Experiment, a new screen will come up. You’ll see something like this and if you do, it just means that H2O is running your experiment — LIVE! As the experiment moves along, it will start showing the model’s iteration data, as well as the most important variables (which may change as the model progresses). On the bottom right, you can also switch between screens to see: ~ ROC curve ~ Precision-Recall~ Gain/Lift charts~ K-S test chart (Kolmogorov-Smirnov)~ CPU Usage. Once your experiment is completed you should be able to see a screen like this and your CPU Usage tab would have changed to Summary: Right above variable importance, there is a menu of actions you can choose from. The only option unavailable on the screen is Deploy. There’s a reason for that. It’s because we haven’t downloaded our MOJO/POJO files yet. We’ll do that towards the end. First, let’s interpret this model. Navigate back to the Experiment tab and find your experiment. Open it up once again and click on the button that says Interpret This Model. The interpretation window will start loading and might take some time. It should look like this: Once the interpretation page is loaded to 100%, you will get a menu for interpreting the model. This page can also be accessed via the MLI tab.There a number of tabs on the left side of the page, as you can see in the GIFs below. Summary: Gives us an overview of the MLI (Machine Learning Interpreter) with some parameters of the model such as its most important variables with definitions, the number of LIME clusters used, a summary of the surrogate model. The GIF below shows a sample Summary page: DAI Model: Here you can see the model developed by the Driverless AI. Within the DAI Model, you can see a full picture of the feature importance within this model, each variable has its explanation pop up when you hover over the variable. It can also show you a Partial Dependence plot over the contract variable, and moreover, you can see the Disparate Impact Analysis with a full confusion matrix from our experiment. Surrogate Models: Apart from the DAI model analytics, we also get information about our Surrogate models. These are in the Surrogate tab, and allow us to see parameters and data from our other models such as the K-Lime clusters, Decision Tree model, and Random Forest Models. Within Random Forest, we can also see Feature Importance, Partial Dependence, and LOCO. Dashboard: Below is what the MLI Dashboard looks like. It contains all our important graphs and parameters on one page, so we can quickly navigate to where we want. The Diagnostics tab contains a page with certain accuracy metrics and graphs that can be used to diagnose the model after an experiment is run. It contains everything from the ROC Curve, Precision-Recall Curve, Gains/Lifts, K-S Chart, and Confusion Matrix with True/False Positive/Negatives. Here’s what the diagnostics page looks like: As I had mentioned above, deploy was not possible because we didn’t have our MOJO file. To deploy your model locally or on a cloud server, you would first need to create the MOJO file. According to their website, “ H2O-generated MOJO and POJO models are intended to be easily embeddable in any Java environment.” So go back to the Experiments tab and load your experiment. You’ll see the menu again with option buttons in green. Go ahead and click the button that says Build MOJO Scoring Pipeline. It will now show you the screen to your left and will start building your MOJO pipeline. Once you have your MOJO Pipeline available, you will have the option to Deploy your model. You can choose to put it on an Amazon Lambda server or you can use the REST API Server. Once you’ve chosen your destination, H2O ill automatically deploy your model and give you its location. The resources tab has a number of options to. Firstly, it will have an option to take you to the Driverless AI documentation. It also contains links to download the H2O Driverless AI client APIs for R and Python. This is super useful if you want to learn more about the capabilities of Driverless AI and use it within your business. In conclusion, I just want to mention that I am in no way associated with the Company H2O, that developed this product. I am a user of their products who thought it would be a good idea to post this tutorial since there aren’t many out there currently. It took me a while to learn H2O Driverless AI and I thought I would make it easier for others through this tutorial. Feel free to comment on this post and ask me any questions about my work, or how I plan on using H2O in my personal/work projects. I might write another post in the future comparing Driverless AI to the H2O 3 (Open-source), and any feedback towards that would be great. Thanks for reading. I hope this was able to help you in ways unimaginable. For more information and tutorials on H2O Driverless AI, visit h2o.ai.
[ { "code": null, "e": 444, "s": 172, "text": "In today’s world, being a Data Scientist is not limited to those without technical knowledge. While it is recommended and sometimes important to know a little bit of code, you can get by with just intuitive knowledge. Especially if you’re on H2O’s Driverless AI platform." }, { "code": null, "e": 734, "s": 444, "text": "If you haven’t heard of H2O.ai, it is the company that created the open-source machine learning platform, H2O, which is used by many in the Fortune 500. H2O aims at creating efficiency-driven machine learning environments by leveraging its user-friendly interface and modular capabilities." }, { "code": null, "e": 907, "s": 734, "text": "Note: Don't confuse the open-source H2O AI platform with the Driverless AI. They are two separate things. I suggest reading through the documentation on each to learn more." }, { "code": null, "e": 1373, "s": 907, "text": "H2O 3 (open-source) is a free library on python/R that contains many ML algorithms, models and tuning features that make machine learning more efficient. The Driverless AI, on the other hand, is an enterprise product that has its own platform, UI and UX. It is like a web application that can be used to create and configure models using knobs and other visual apparatus that tune parameters, essentially replacing the tedious process of actually coding your model." }, { "code": null, "e": 1784, "s": 1373, "text": "The H2O DAI can build and validate AI models from scratch and the only thing required is your dataset. The data doesn’t even have to be cleaned or feature-engineered as the H2O DAI is built to handle those tasks and allows you to configure the automation of important steps such as feature scaling or applying categorical encoding on variables. Without further ado, I will begin the H2O Driverless AI tutorial." }, { "code": null, "e": 2202, "s": 1784, "text": "H2O Driverless AI is an enterprise product and therefore isn’t recommended for an individual to purchase. Instead, your firm should deploy H2O locally and allow employees to take advantage of its robust interface. However, you and I are individuals and for the purpose of this tutorial, I am using H2O’s 21-day free trial. You can do the same if you want to follow along and are not ready to purchase the product yet." }, { "code": null, "e": 2579, "s": 2202, "text": "Note: There are some requirements for running h2o on your machine. It is recommended that you run h2o on Linux or Windows, however, you can run it on a Mac using docker. You can learn how to do that here.I will go through the requirements for Windows since that’s what I’m using for this tutorial. If you’re on Linux (prod. environment recommended), follow these instructions." }, { "code": null, "e": 2724, "s": 2579, "text": "Start by visiting h2o.ai. Look for the Driverless AI product, fill out the form and download the latest stable version of the Driverless AI DEB." }, { "code": null, "e": 2773, "s": 2724, "text": "On Windows, there are 2 additional requirements:" }, { "code": null, "e": 2899, "s": 2773, "text": "Windows subsystems for Linux (WSL) must be enabled as specified at https://docs.microsoft.com/en-us/windows/wsl/install-win10" }, { "code": null, "e": 2993, "s": 2899, "text": "Ubuntu 18.04 from the Windows Store. (Note that Ubuntu 16.04 for WSL is no longer supported.)" }, { "code": null, "e": 3216, "s": 2993, "text": "So, you need to first install Ubuntu 18.04 for WSL (which you can activate if you “run as admin” (Instruction in the first link). Once that’s done, run the following commands in Ubuntu 18.04 LTS to install and run H2O-DAI:" }, { "code": null, "e": 3399, "s": 3216, "text": "# Install Driverless AI. Expect installation of the .deb file to take several minutes on WSL.sudo dpkg -i dai_VERSION.deb# Run Driverless AI.sudo -H -u dai /opt/h2oai/dai/run-dai.sh" }, { "code": null, "e": 3510, "s": 3399, "text": "Another way to install H2O-DAI on windows is through Docker. You can find specific instructions for that here." }, { "code": null, "e": 3584, "s": 3510, "text": "Get on your browser and in the URL box, type the followinglocalhost:12345" }, { "code": null, "e": 3703, "s": 3584, "text": "This should work if you installed H2O on a local machine. The general syntax for running an instance is <server>:12345" }, { "code": null, "e": 3817, "s": 3703, "text": "Use ‘localhost’ on a local server. It should then automatically launch the login page, which will look like this." }, { "code": null, "e": 4040, "s": 3817, "text": "For Trial Users, the login ID and password are both “h2oai”. Log in the details and click sign in. You should now see the Datasets page, wherein H2O will show you any past-uploaded data or other files stored on the system." }, { "code": null, "e": 4343, "s": 4040, "text": "H2O Driverless AI is very flexible when it comes to sourcing your data sets. Since a majority of its applications are on real-time/series data, H2O has the ability to extract information from a number of sources such as an Amazon S3 server, Hadoop file system, via Local upload, or the H2O file system." }, { "code": null, "e": 4547, "s": 4343, "text": "I uploaded a file from my computer, which is the Telco Customer Churn Database (from Kaggle). This file contains customer data, with each column (except customer ID) factoring in on the churn prediction." }, { "code": null, "e": 4812, "s": 4547, "text": "As soon as my data set was uploaded, I could access the Autoviz tab. When you visualize a data set through Autoviz, it will give you different kinds of possible plots to summarize your data. All you have to do is upload your data, and Autoviz will be ready to use." }, { "code": null, "e": 4972, "s": 4812, "text": "Some graphs are also interactive and can be moved around like in Plotly. All visuals are downloadable, so you can save them on your server or in a file system." }, { "code": null, "e": 5093, "s": 4972, "text": "To start any experiment or activity, you need to have a project. So go on the Project tab and it should look like this :" }, { "code": null, "e": 5313, "s": 5093, "text": "You’ll now want to create a new project, just pick a name and description to start with. Once that’s done, you’ll have a screen like the one right below. This is where you manage your project, its data, and experiments." }, { "code": null, "e": 5642, "s": 5313, "text": "Use the Link Dataset button to link your files to this project. I’ve attached my data set on Customer Churn and it shows up under Training on the left side. If I right-click my dataset, I have the option of splitting it. I would need to split the dataset for training and testing, so I click Split and get the following options:" }, { "code": null, "e": 5917, "s": 5642, "text": "I choose the names of the two different data sets, pick a Target column (The column we want to predict), folds and time-columns if necessary, and select the split ratio. I picked 0.75 since that would give me 2500 values in my test set, which is enough to test the model on." }, { "code": null, "e": 6184, "s": 5917, "text": "Every time you run a particular model on a data set, it’s called an experiment. H2O makes the process of model selection much easier with this feature. You can use multiple experiments to pick the right model. Go to your Project’s dashboard and click New Experiment." }, { "code": null, "e": 6734, "s": 6184, "text": "The Experiment Setup Assistant should open up. You can now start filling in the details of this experiment. Start with the name, then choose the training set. More details will show up (as you see in the GIF above). You can now select your Target Column, your test data set and you can change the training settings according to your needs. A personalized description of the model, according to the settings you’ve picked, will show up on the left side of the screen. You can even click on Expert Settings to go in deeper and change other parameters." }, { "code": null, "e": 6902, "s": 6734, "text": "Once you click on Launch Experiment, a new screen will come up. You’ll see something like this and if you do, it just means that H2O is running your experiment — LIVE!" }, { "code": null, "e": 7132, "s": 6902, "text": "As the experiment moves along, it will start showing the model’s iteration data, as well as the most important variables (which may change as the model progresses). On the bottom right, you can also switch between screens to see:" }, { "code": null, "e": 7230, "s": 7132, "text": "~ ROC curve ~ Precision-Recall~ Gain/Lift charts~ K-S test chart (Kolmogorov-Smirnov)~ CPU Usage." }, { "code": null, "e": 7363, "s": 7230, "text": "Once your experiment is completed you should be able to see a screen like this and your CPU Usage tab would have changed to Summary:" }, { "code": null, "e": 7650, "s": 7363, "text": "Right above variable importance, there is a menu of actions you can choose from. The only option unavailable on the screen is Deploy. There’s a reason for that. It’s because we haven’t downloaded our MOJO/POJO files yet. We’ll do that towards the end. First, let’s interpret this model." }, { "code": null, "e": 7887, "s": 7650, "text": "Navigate back to the Experiment tab and find your experiment. Open it up once again and click on the button that says Interpret This Model. The interpretation window will start loading and might take some time. It should look like this:" }, { "code": null, "e": 8117, "s": 7887, "text": "Once the interpretation page is loaded to 100%, you will get a menu for interpreting the model. This page can also be accessed via the MLI tab.There a number of tabs on the left side of the page, as you can see in the GIFs below." }, { "code": null, "e": 8389, "s": 8117, "text": "Summary: Gives us an overview of the MLI (Machine Learning Interpreter) with some parameters of the model such as its most important variables with definitions, the number of LIME clusters used, a summary of the surrogate model. The GIF below shows a sample Summary page:" }, { "code": null, "e": 8809, "s": 8389, "text": "DAI Model: Here you can see the model developed by the Driverless AI. Within the DAI Model, you can see a full picture of the feature importance within this model, each variable has its explanation pop up when you hover over the variable. It can also show you a Partial Dependence plot over the contract variable, and moreover, you can see the Disparate Impact Analysis with a full confusion matrix from our experiment." }, { "code": null, "e": 9173, "s": 8809, "text": "Surrogate Models: Apart from the DAI model analytics, we also get information about our Surrogate models. These are in the Surrogate tab, and allow us to see parameters and data from our other models such as the K-Lime clusters, Decision Tree model, and Random Forest Models. Within Random Forest, we can also see Feature Importance, Partial Dependence, and LOCO." }, { "code": null, "e": 9338, "s": 9173, "text": "Dashboard: Below is what the MLI Dashboard looks like. It contains all our important graphs and parameters on one page, so we can quickly navigate to where we want." }, { "code": null, "e": 9675, "s": 9338, "text": "The Diagnostics tab contains a page with certain accuracy metrics and graphs that can be used to diagnose the model after an experiment is run. It contains everything from the ROC Curve, Precision-Recall Curve, Gains/Lifts, K-S Chart, and Confusion Matrix with True/False Positive/Negatives. Here’s what the diagnostics page looks like:" }, { "code": null, "e": 9988, "s": 9675, "text": "As I had mentioned above, deploy was not possible because we didn’t have our MOJO file. To deploy your model locally or on a cloud server, you would first need to create the MOJO file. According to their website, “ H2O-generated MOJO and POJO models are intended to be easily embeddable in any Java environment.”" }, { "code": null, "e": 10262, "s": 9988, "text": "So go back to the Experiments tab and load your experiment. You’ll see the menu again with option buttons in green. Go ahead and click the button that says Build MOJO Scoring Pipeline. It will now show you the screen to your left and will start building your MOJO pipeline." }, { "code": null, "e": 10545, "s": 10262, "text": "Once you have your MOJO Pipeline available, you will have the option to Deploy your model. You can choose to put it on an Amazon Lambda server or you can use the REST API Server. Once you’ve chosen your destination, H2O ill automatically deploy your model and give you its location." }, { "code": null, "e": 10878, "s": 10545, "text": "The resources tab has a number of options to. Firstly, it will have an option to take you to the Driverless AI documentation. It also contains links to download the H2O Driverless AI client APIs for R and Python. This is super useful if you want to learn more about the capabilities of Driverless AI and use it within your business." }, { "code": null, "e": 11518, "s": 10878, "text": "In conclusion, I just want to mention that I am in no way associated with the Company H2O, that developed this product. I am a user of their products who thought it would be a good idea to post this tutorial since there aren’t many out there currently. It took me a while to learn H2O Driverless AI and I thought I would make it easier for others through this tutorial. Feel free to comment on this post and ask me any questions about my work, or how I plan on using H2O in my personal/work projects. I might write another post in the future comparing Driverless AI to the H2O 3 (Open-source), and any feedback towards that would be great." }, { "code": null, "e": 11593, "s": 11518, "text": "Thanks for reading. I hope this was able to help you in ways unimaginable." } ]
C++ Program for Common Divisors of Two Numbers?
Here we will see how we can get the number of common divisors of two numbers. We are not going to find all common divisors, but we will count how many common divisors are there. If two numbers are like 12 and 24, then common divisors are 1, 2, 3, 4, 6, 12. So there are 6 common divisors, so the answer will be 6. begin count := 0 gcd := gcd of a and b for i := 1 to square root of gcd, do if gcd is divisible by 0, then if gcd / i = i, then count := count + 1 else count := count + 2 enf if end if done return count end Live Demo #include<iostream> #include<cmath> using namespace std; int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } int countCommonDivisors(int a,int b) { int gcd_val = gcd(a, b); //get gcd of a and b int count = 0; for (int i=1; i<=sqrt(gcd_val); i++) { if (gcd_val%i==0) { // when'i' is factor of n if (gcd_val/i == i) //if two numbers are same count += 1; else count += 2; } } return count; } main() { int a = 12, b = 24; cout << "Total common divisors: " << countCommonDivisors(a, b); } The differences array: 6 5 10 1
[ { "code": null, "e": 1376, "s": 1062, "text": "Here we will see how we can get the number of common divisors of two numbers. We are not going to find all common divisors, but we will count how many common divisors are there. If two numbers are like 12 and 24, then common divisors are 1, 2, 3, 4, 6, 12. So there are 6 common divisors, so the answer will be 6." }, { "code": null, "e": 1661, "s": 1376, "text": "begin\n count := 0\n gcd := gcd of a and b\n for i := 1 to square root of gcd, do\n if gcd is divisible by 0, then\n if gcd / i = i, then\n count := count + 1\n else\n count := count + 2\n enf if\n end if\n done\n return count\nend" }, { "code": null, "e": 1672, "s": 1661, "text": " Live Demo" }, { "code": null, "e": 2258, "s": 1672, "text": "#include<iostream>\n#include<cmath>\nusing namespace std;\nint gcd(int a, int b) {\n if (a == 0)\n return b;\n return gcd(b%a, a);\n}\nint countCommonDivisors(int a,int b) {\n int gcd_val = gcd(a, b); //get gcd of a and b\n int count = 0;\n for (int i=1; i<=sqrt(gcd_val); i++) {\n if (gcd_val%i==0) { // when'i' is factor of n\n if (gcd_val/i == i) //if two numbers are same\n count += 1;\n else\n count += 2;\n }\n }\n return count;\n}\nmain() {\n int a = 12, b = 24;\n cout << \"Total common divisors: \" << countCommonDivisors(a, b);\n}" }, { "code": null, "e": 2290, "s": 2258, "text": "The differences array: 6 5 10 1" } ]
ETL Testing – Techniques
It is important that you define the correct ETL Testing technique before starting the testing process. You should take an acceptance from all the stakeholders and ensure that a correct technique is selected to perform ETL testing. This technique should be well known to the testing team and they should be aware of the steps involved in the testing process. There are various types of testing techniques that can be used. In this chapter, we will discuss the testing techniques in brief. To perform Analytical Reporting and Analysis, the data in your production should be correct. This testing is done on the data that is moved to the production system. It involves data validation in the production system and comparing it the with the source data. This type of testing is done when the tester has less time to perform the testing operation. It involves checking the count of data in the source and the target systems. It doesn’t involve checking the values of data in the target system. It also doesn’t involve if the data is in ascending or descending order after mapping of data. In this type of testing, a tester validates data values from the source to the target system. It checks the data values in the source system and the corresponding values in the target system after transformation. This type of testing is time-consuming and is normally performed in financial and banking projects. In this type of testing, a tester validates the range of data. All the threshold values in the target system are checked if they are as per the expected result. It also involves integration of data in the target system from multiple source systems after transformation and loading. Example − Age attribute shouldn’t have a value greater than 100. In the date column DD/MM/YY, the month field shouldn’t have a value greater than 12. Application migration testing is normally performed automatically when you move from an old application to a new application system. This testing saves a lot of time. It checks if the data extracted from an old application is same as per the data in the new application system. It includes performing various checks such as data type check, data length check, and index check. Here a Test Engineer performs the following scenarios − Primary Key, Foreign Key, NOT NULL, NULL, and UNIQUE. This testing involves checking for duplicate data in the target system. When there is a huge amount of data in the target system, it is possible that there is duplicate data in the production system that may result in incorrect data in Analytical Reports. Duplicate values can be checked with SQL statement like − Select Cust_Id, Cust_NAME, Quantity, COUNT (*) FROM Customer GROUP BY Cust_Id, Cust_NAME, Quantity HAVING COUNT (*) >1; Duplicate data appears in the target system due to the following reasons − If no primary key is defined, then duplicate values may come. Due to incorrect mapping or environmental issues. Manual errors while transferring data from the source to the target system. Data transformation testing is not performed by running a single SQL statement. It is time-consuming and involves running multiple SQL queries for each row to verify the transformation rules. The tester needs to run SQL queries for each row and then compare the output with the target data. Data quality testing involves performing number check, date check, null check, precision check, etc. A tester performs Syntax Test to report invalid characters, incorrect upper/lower case order, etc. and Reference Tests to check if the data is according to the data model. Incremental testing is performed to verify if Insert and Update statements are executed as per the expected result. This testing is performed step-by-step with old and new data. When we make changes to data transformation and aggregation rules to add new functionality which also helps the tester to find new errors, it is called Regression Testing. The bugs in data that that comes in regression testing are called Regression. When you run the tests after fixing the codes, it is called retesting. System integration testing involves testing the components of a system individually and later integrating the modules. There are three ways a system integration can be done: top-down, bottom-up, and hybrid. Navigation testing is also known as testing the front-end of the system. It involves enduser point of view testing by checking all the aspects of the front-end report − includes data in various fields, calculation and aggregates, etc. 18 Lectures 58 mins Jim Macaulay 11 Lectures 1 hours Jim Macaulay 19 Lectures 1 hours Asim Noaman Lodhi Print Add Notes Bookmark this page
[ { "code": null, "e": 2503, "s": 2145, "text": "It is important that you define the correct ETL Testing technique before starting the testing process. You should take an acceptance from all the stakeholders and ensure that a correct technique is selected to perform ETL testing. This technique should be well known to the testing team and they should be aware of the steps involved in the testing process." }, { "code": null, "e": 2633, "s": 2503, "text": "There are various types of testing techniques that can be used. In this chapter, we will discuss the testing techniques in brief." }, { "code": null, "e": 2895, "s": 2633, "text": "To perform Analytical Reporting and Analysis, the data in your production should be correct. This testing is done on the data that is moved to the production system. It involves data validation in the production system and comparing it the with the source data." }, { "code": null, "e": 3229, "s": 2895, "text": "This type of testing is done when the tester has less time to perform the testing operation. It involves checking the count of data in the source and the target systems. It doesn’t involve checking the values of data in the target system. It also doesn’t involve if the data is in ascending or descending order after mapping of data." }, { "code": null, "e": 3542, "s": 3229, "text": "In this type of testing, a tester validates data values from the source to the target system. It checks the data values in the source system and the corresponding values in the target system after transformation. This type of testing is time-consuming and is normally performed in financial and banking projects." }, { "code": null, "e": 3824, "s": 3542, "text": "In this type of testing, a tester validates the range of data. All the threshold values in the target system are checked if they are as per the expected result. It also involves integration of data in the target system from multiple source systems after transformation and loading." }, { "code": null, "e": 3974, "s": 3824, "text": "Example − Age attribute shouldn’t have a value greater than 100. In the date column DD/MM/YY, the month field shouldn’t have a value greater than 12." }, { "code": null, "e": 4252, "s": 3974, "text": "Application migration testing is normally performed automatically when you move from an old application to a new application system. This testing saves a lot of time. It checks if the data extracted from an old application is same as per the data in the new application system." }, { "code": null, "e": 4461, "s": 4252, "text": "It includes performing various checks such as data type check, data length check, and index check. Here a Test Engineer performs the following scenarios − Primary Key, Foreign Key, NOT NULL, NULL, and UNIQUE." }, { "code": null, "e": 4717, "s": 4461, "text": "This testing involves checking for duplicate data in the target system. When there is a huge amount of data in the target system, it is possible that there is duplicate data in the production system that may result in incorrect data in Analytical Reports." }, { "code": null, "e": 4775, "s": 4717, "text": "Duplicate values can be checked with SQL statement like −" }, { "code": null, "e": 4897, "s": 4775, "text": "Select Cust_Id, Cust_NAME, Quantity, COUNT (*) \nFROM Customer\nGROUP BY Cust_Id, Cust_NAME, Quantity HAVING COUNT (*) >1;\n" }, { "code": null, "e": 4972, "s": 4897, "text": "Duplicate data appears in the target system due to the following reasons −" }, { "code": null, "e": 5034, "s": 4972, "text": "If no primary key is defined, then duplicate values may come." }, { "code": null, "e": 5084, "s": 5034, "text": "Due to incorrect mapping or environmental issues." }, { "code": null, "e": 5160, "s": 5084, "text": "Manual errors while transferring data from the source to the target system." }, { "code": null, "e": 5451, "s": 5160, "text": "Data transformation testing is not performed by running a single SQL statement. It is time-consuming and involves running multiple SQL queries for each row to verify the transformation rules. The tester needs to run SQL queries for each row and then compare the output with the target data." }, { "code": null, "e": 5724, "s": 5451, "text": "Data quality testing involves performing number check, date check, null check, precision check, etc. A tester performs Syntax Test to report invalid characters, incorrect upper/lower case order, etc. and Reference Tests to check if the data is according to the data model." }, { "code": null, "e": 5902, "s": 5724, "text": "Incremental testing is performed to verify if Insert and Update statements are executed as per the expected result. This testing is performed step-by-step with old and new data." }, { "code": null, "e": 6152, "s": 5902, "text": "When we make changes to data transformation and aggregation rules to add new functionality which also helps the tester to find new errors, it is called Regression Testing. The bugs in data that that comes in regression testing are called Regression." }, { "code": null, "e": 6223, "s": 6152, "text": "When you run the tests after fixing the codes, it is called retesting." }, { "code": null, "e": 6430, "s": 6223, "text": "System integration testing involves testing the components of a system individually and later integrating the modules. There are three ways a system integration can be done: top-down, bottom-up, and hybrid." }, { "code": null, "e": 6667, "s": 6430, "text": "Navigation testing is also known as testing the front-end of the system. It involves enduser point of view testing by checking all the aspects of the front-end report − includes data in various fields, calculation and aggregates, etc." }, { "code": null, "e": 6699, "s": 6667, "text": "\n 18 Lectures \n 58 mins\n" }, { "code": null, "e": 6713, "s": 6699, "text": " Jim Macaulay" }, { "code": null, "e": 6746, "s": 6713, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 6760, "s": 6746, "text": " Jim Macaulay" }, { "code": null, "e": 6793, "s": 6760, "text": "\n 19 Lectures \n 1 hours \n" }, { "code": null, "e": 6812, "s": 6793, "text": " Asim Noaman Lodhi" }, { "code": null, "e": 6819, "s": 6812, "text": " Print" }, { "code": null, "e": 6830, "s": 6819, "text": " Add Notes" } ]
Create date from day, month, year fields in MySQL?
You can use in-built function STR_TO_DATE() from MySQL. The syntax is as follows − SELECT STR_TO_DATE(CONCAT(yourYearColumName,'-',LPAD(yourMonthColumName,2,'00'),'-',LPAD(yourDayColumName,2,'00')), '%Y-%m-%d') as anyVariableName from yourTableName; To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table DateCreateDemo −> ( −> `Day` varchar(2), −> `Month` varchar(2), −> `Year` varchar(4) −> ); Query OK, 0 rows affected (1.68 sec) Insert values for all fields using insert command. The query is as follows − mysql> insert into DateCreateDemo values('15','12','2018'); Query OK, 1 row affected (0.09 sec) mysql> insert into DateCreateDemo values('10','11','2016'); Query OK, 1 row affected (0.37 sec) mysql> insert into DateCreateDemo values('12','6','2017'); Query OK, 1 row affected (0.12 sec) mysql> insert into DateCreateDemo values('9','8','2019'); Query OK, 1 row affected (0.17 sec) mysql> insert into DateCreateDemo values('10','5','2020'); Query OK, 1 row affected (0.09 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from DateCreateDemo; The following is the output − +------+-------+------+ | Day | Month | Year | +------+-------+------+ | 15 | 12 | 2018 | | 10 | 11 | 2016 | | 12 | 6 | 2017 | | 9 | 8 | 2019 | | 10 | 5 | 2020 | +------+-------+------+ 5 rows in set (0.00 sec) Create a date using the above three fields which is ‘Day’,’Month’ and ‘Year’. The query is as follows − mysql> select −> STR_TO_DATE(CONCAT(Year,'-',LPAD(Month,2,'00'),'-',LPAD(day,2,'00')), '%Y-%m-%d') as DateDemo from DateCreateDemo; The following is the output − +------------+ | DateDemo | +------------+ | 2018-12-15 | | 2016-11-10 | | 2017-06-12 | | 2019-08-09 | | 2020-05-10 | +------------+ 5 rows in set (0.06 sec)
[ { "code": null, "e": 1145, "s": 1062, "text": "You can use in-built function STR_TO_DATE() from MySQL. The syntax is as follows −" }, { "code": null, "e": 1312, "s": 1145, "text": "SELECT\nSTR_TO_DATE(CONCAT(yourYearColumName,'-',LPAD(yourMonthColumName,2,'00'),'-',LPAD(yourDayColumName,2,'00')), '%Y-%m-%d') as anyVariableName from yourTableName;" }, { "code": null, "e": 1411, "s": 1312, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1574, "s": 1411, "text": "mysql> create table DateCreateDemo\n −> (\n −> `Day` varchar(2),\n −> `Month` varchar(2),\n −> `Year` varchar(4)\n −> );\nQuery OK, 0 rows affected (1.68 sec)" }, { "code": null, "e": 1651, "s": 1574, "text": "Insert values for all fields using insert command. The query is as follows −" }, { "code": null, "e": 2131, "s": 1651, "text": "mysql> insert into DateCreateDemo values('15','12','2018');\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> insert into DateCreateDemo values('10','11','2016');\nQuery OK, 1 row affected (0.37 sec)\n\nmysql> insert into DateCreateDemo values('12','6','2017');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into DateCreateDemo values('9','8','2019');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into DateCreateDemo values('10','5','2020');\nQuery OK, 1 row affected (0.09 sec)" }, { "code": null, "e": 2216, "s": 2131, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2252, "s": 2216, "text": "mysql> select *from DateCreateDemo;" }, { "code": null, "e": 2282, "s": 2252, "text": "The following is the output −" }, { "code": null, "e": 2523, "s": 2282, "text": "+------+-------+------+\n| Day | Month | Year |\n+------+-------+------+\n| 15 | 12 | 2018 |\n| 10 | 11 | 2016 |\n| 12 | 6 | 2017 |\n| 9 | 8 | 2019 |\n| 10 | 5 | 2020 |\n+------+-------+------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2627, "s": 2523, "text": "Create a date using the above three fields which is ‘Day’,’Month’ and ‘Year’. The query is as follows −" }, { "code": null, "e": 2762, "s": 2627, "text": "mysql> select\n −> STR_TO_DATE(CONCAT(Year,'-',LPAD(Month,2,'00'),'-',LPAD(day,2,'00')), '%Y-%m-%d') as DateDemo from DateCreateDemo;" }, { "code": null, "e": 2792, "s": 2762, "text": "The following is the output −" }, { "code": null, "e": 2952, "s": 2792, "text": "+------------+\n| DateDemo |\n+------------+\n| 2018-12-15 |\n| 2016-11-10 |\n| 2017-06-12 |\n| 2019-08-09 |\n| 2020-05-10 |\n+------------+\n5 rows in set (0.06 sec)" } ]
Car driving using hand detection in Python - GeeksforGeeks
11 Dec, 2020 In this project, we are going to demonstrate how one can drive a car by just detecting hand gestures on the steering wheel. Let’s say the requirement is something like this – If driver wants to start the car then put both of your hands on the steering wheel. If someone having no hands on a steering wheel that means brakes of car will be applied slowly. If one hand is detected on the steering wheel that means he/she can drive the car upto a certain limit due to safety purpose. If someone having both of the hands on the steering wheel that means that he/she can drive at any speed because according to our system you are safe and can safely handle car with both of your hands. For this project we need to import two Python libraries that is OpenCV and numpy. How to install these two libraries. 1) pip install opencv-python 2) pip install numpy Below is the implementation : Code #1: import cv2import numpy as np cap = cv2.VideoCapture(0)hand_cascade = cv2.CascadeClassifier('hand.xml') Explanation :We have imported two libraries named opencv and numpy. Then in the next line we use the function VideoCapture(0) of opencv and passed the parameter as 0 because your laptop webcam supports port 0 to use the camera. Now, use the function CascadeClassifier('hand.xml') and pass the xml file as parameter. Store the file of hand.xml in the same directory as of Python file. Code #2 : count = 0 while(True): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) hands = hand_cascade.detectMultiScale(gray, 1.5, 2) contour = hands contour = np.array(contour) if count==0: if len(contour)==2: cv2.putText(img=frame, text='Your engine started', org=(int(100 / 2 - 20), int(100 / 2)), fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=1, color=(0, 255, 0)) for (x, y, w, h) in hands: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) count += 1 if count>0: if len(contour)>=2: cv2.putText(img=frame, text='You can take your car on long drive', org=(int(100 / 2 - 20), int(100 / 2)), fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=1, color=(255, 0, 0)) for (x, y, w, h) in hands: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) elif len(contour)==1: cv2.putText(img=frame, text='You can speed upto 80km/h', org=(int(100 / 2 - 20), int(100 / 2)), fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=1, color=(0, 255, 0)) for (x, y, w, h) in hands: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) elif len(contour)==0: cv2.putText(img=frame, text='Brake is applied slowly', org=(int(100 / 2 - 20), int(100 / 2)), fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=1, color=(0, 0, 255)) count += 1 cv2.imshow('Driver_frame', frame)k = cv2.waitKey(30) & 0xffif k == 27: break Output :Explanation :In this code section, we use the counter that can help us to start the car’s engine and after the car starts we use the counting of contours on a steering wheel. GitHub link of the project – Click Here Project Python 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 Java Swing | Simple User Registration Form Twitter Sentiment Analysis using Python Banking Transaction System using Java Student Information Management System Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24352, "s": 24324, "text": "\n11 Dec, 2020" }, { "code": null, "e": 24527, "s": 24352, "text": "In this project, we are going to demonstrate how one can drive a car by just detecting hand gestures on the steering wheel. Let’s say the requirement is something like this –" }, { "code": null, "e": 24611, "s": 24527, "text": "If driver wants to start the car then put both of your hands on the steering wheel." }, { "code": null, "e": 24707, "s": 24611, "text": "If someone having no hands on a steering wheel that means brakes of car will be applied slowly." }, { "code": null, "e": 24833, "s": 24707, "text": "If one hand is detected on the steering wheel that means he/she can drive the car upto a certain limit due to safety purpose." }, { "code": null, "e": 25033, "s": 24833, "text": "If someone having both of the hands on the steering wheel that means that he/she can drive at any speed because according to our system you are safe and can safely handle car with both of your hands." }, { "code": null, "e": 25151, "s": 25033, "text": "For this project we need to import two Python libraries that is OpenCV and numpy. How to install these two libraries." }, { "code": null, "e": 25202, "s": 25151, "text": "1) pip install opencv-python\n2) pip install numpy\n" }, { "code": null, "e": 25232, "s": 25202, "text": "Below is the implementation :" }, { "code": null, "e": 25241, "s": 25232, "text": "Code #1:" }, { "code": "import cv2import numpy as np cap = cv2.VideoCapture(0)hand_cascade = cv2.CascadeClassifier('hand.xml')", "e": 25345, "s": 25241, "text": null }, { "code": null, "e": 25739, "s": 25345, "text": "Explanation :We have imported two libraries named opencv and numpy. Then in the next line we use the function VideoCapture(0) of opencv and passed the parameter as 0 because your laptop webcam supports port 0 to use the camera. Now, use the function CascadeClassifier('hand.xml') and pass the xml file as parameter. Store the file of hand.xml in the same directory as of Python file. Code #2 :" }, { "code": "count = 0 while(True): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) hands = hand_cascade.detectMultiScale(gray, 1.5, 2) contour = hands contour = np.array(contour) if count==0: if len(contour)==2: cv2.putText(img=frame, text='Your engine started', org=(int(100 / 2 - 20), int(100 / 2)), fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=1, color=(0, 255, 0)) for (x, y, w, h) in hands: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) count += 1 if count>0: if len(contour)>=2: cv2.putText(img=frame, text='You can take your car on long drive', org=(int(100 / 2 - 20), int(100 / 2)), fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=1, color=(255, 0, 0)) for (x, y, w, h) in hands: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) elif len(contour)==1: cv2.putText(img=frame, text='You can speed upto 80km/h', org=(int(100 / 2 - 20), int(100 / 2)), fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=1, color=(0, 255, 0)) for (x, y, w, h) in hands: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) elif len(contour)==0: cv2.putText(img=frame, text='Brake is applied slowly', org=(int(100 / 2 - 20), int(100 / 2)), fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=1, color=(0, 0, 255)) count += 1 cv2.imshow('Driver_frame', frame)k = cv2.waitKey(30) & 0xffif k == 27: break", "e": 27631, "s": 25739, "text": null }, { "code": null, "e": 27814, "s": 27631, "text": "Output :Explanation :In this code section, we use the counter that can help us to start the car’s engine and after the car starts we use the counting of contours on a steering wheel." }, { "code": null, "e": 27855, "s": 27814, "text": " GitHub link of the project – Click Here" }, { "code": null, "e": 27863, "s": 27855, "text": "Project" }, { "code": null, "e": 27870, "s": 27863, "text": "Python" }, { "code": null, "e": 27968, "s": 27870, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27977, "s": 27968, "text": "Comments" }, { "code": null, "e": 27990, "s": 27977, "text": "Old Comments" }, { "code": null, "e": 28039, "s": 27990, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 28082, "s": 28039, "text": "Java Swing | Simple User Registration Form" }, { "code": null, "e": 28122, "s": 28082, "text": "Twitter Sentiment Analysis using Python" }, { "code": null, "e": 28160, "s": 28122, "text": "Banking Transaction System using Java" }, { "code": null, "e": 28198, "s": 28160, "text": "Student Information Management System" }, { "code": null, "e": 28226, "s": 28198, "text": "Read JSON file using Python" }, { "code": null, "e": 28276, "s": 28226, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 28298, "s": 28276, "text": "Python map() function" } ]
Complete Binary Tree | Practice | GeeksforGeeks
Given a Binary Tree, write a function to check whether the given Binary Tree is Complete Binary Tree or not. A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. Example 1: Input: 1 / \ 2 3 Output: Complete Binary Tree Example 2: Input: 1 / \ 2 3 \ / \ 4 5 6 Output: Not Complete Binary Tree Constraints: 1<=Number of Node<=100 0 <= Data of a node <= 106 Your Task: You don't need to take input. Just complete the function isCompleteBT() that takes root node as a parameter and returns true, if the tree is Complete else returns false. 0 amishasahu3283 weeks ago bool isCompleteBT(Node* root){ //code here if(!root) return true; // Intution : // In a complete binary tree you will never encounter null node between the not null nodes. queue<Node*> q; q.push(root); bool foundNull = false; while(!q.empty()) { Node *curr = q.front(); q.pop(); if(curr->left) { if(foundNull) return false; q.push(curr->left); } else foundNull = true; if(curr->right) { if(foundNull) return false; q.push(curr->right); } else foundNull = true; } return true; } 0 feyza2 months ago JAVA class GfG { boolean isCompleteBT(Node root) { int index = 0; int numNodes = countNodes(root); if(checkComplete(root, index, numNodes) == true) return true; return false; } boolean checkComplete(Node root, int index, int numberNodes){ if(root == null) return true; if(index >= numberNodes) return false; return (checkComplete(root.left, 2 * index + 1, numberNodes) && checkComplete(root.right, 2 * index + 2, numberNodes)); } int countNodes(Node root){ if(root == null) return 0; return (1+countNodes(root.left) + countNodes(root.right)); } } +1 nonefrompict2 months ago C++ Code! bool isCompleteBT(Node* root){ //code here bool end=false; queue<Node*>q; q.push(root); while(q.empty()==false){ Node* temp=q.front(); q.pop(); if(temp==NULL){ end=true; }else{ if(end){ return false; } q.push(temp->left); q.push(temp->right); } } return true; } +1 vt28522412 months ago Easiest Java - 0.1 time hint - if not null found after null, return false; boolean isCompleteBT(Node root) { Queue<Node> q=new LinkedList<>(); q.add(root); boolean nullFound=false; while(!q.isEmpty()){ int size=q.size(); for(int i=0; i<size; i++){ Node temp=q.remove(); if(temp==null){ nullFound=true; } else{ if(nullFound) return false; q.add(temp.left); q.add(temp.right); } } } return true;} 0 lindan1232 months ago bool isCompleteBT(Node* root){ queue<Node*> q; q.push(root); int flag=0; while(q.empty()==false) { int n = q.size(); while(n--) { Node* temp = q.front(); q.pop(); if(temp->left!=NULL) { if(flag==1) { return false; } q.push(temp->left); } if(temp->left==NULL) { flag=1; } if(temp->right!=NULL) { if(flag==1) { return false; } else if(flag==0) { q.push(temp->right); } } if(temp->right==NULL) { flag=1; } } } return true; } Time Taken : 0.0 Cpp +2 shashikantsolanki0423 months ago HINT : In a complete binary tree you will never encounter null between the values. +1 badgujarsachin833 months ago bool isCompleteBT(Node* root){ //code here queue<Node*> q; q.push(root); bool found=false; while(!q.empty()){ Node* x=q.front(); q.pop(); if(x->left!=NULL){ if(found){ return false; } q.push(x->left); }else{ found=true; } if(x->right!=NULL){ if(found){ return false; } q.push(x->right); }else{ found=true; } } return true; } -1 chessnoobdj4 months ago C++ 2 approaches bool isCompleteBT(Node* root){ if(!root) return true; queue<node*> q; bool isComplete = false; q.push(root); while(!q.empty()){ if(q.front()->left){ if(isComplete) return false; else q.push(q.front()->left); } else isComplete = true; if(q.front()->right){ if(isComplete) return false; else q.push(q.front()->right); } else isComplete = true; q.pop(); } return true; } bool isCompleteBT(Node* root){ string str = ""; bool flg = false; int val = 1; queue <Node*> q; q.push(root); while(!q.empty()){ int n = q.size(); if(flg && n != val) return false; if(val != n) flg = true; if(flg){ for(int i=0; str[i]!='\0'; i++){ while(str[i] == 'N' && str[i+1] == 'N') i++; if(str[i] == 'N' && str[i+1]!='\0') return false; } } //cout << n << " " << flg << " " << val << " " << str << "\n"; str = ""; while(n--){ Node *temp = q.front(); q.pop(); if(temp->left){ q.push(temp->left); str += to_string(temp->left->data); } else str += 'N'; if(temp->right){ q.push(temp->right); str += to_string(temp->right->data); } else str += 'N'; } val *= 2; } return true; } -1 sharad nailwal4 months ago bool isCompleteBT(Node* root){ queue<Node*> q; q.push(root); bool found=false; while(!q.empty()){ Node* temp=q.front();q.pop(); if(temp->left!=NULL){ if(found)return false; q.push(temp->left); } else found=true; if(temp->right!=NULL){ if(found)return false; q.push(temp->right); } else found=true; } return true; } -1 kake13375 months ago bool isCompleteBT(Node* root){ queue<Node*> q; q.push(root); bool CT=true; bool flag=false; while(!q.empty()) { int c=q.size(); while(c>0) { Node* curr=q.front(); q.pop(); c--; Node *L=curr->left; Node *R=curr->right; if(L!=NULL && R!=NULL) { if(flag) { CT=false; break; } else { q.push(L); q.push(R); } } else if(L!=NULL && R==NULL) { if(flag) { CT=false; break; } else { flag=true; q.push(L); } } else if(L==NULL && R!=NULL) { CT=false; break; } else flag=true; } if(!CT) break; } return CT; } 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": 500, "s": 238, "text": "Given a Binary Tree, write a function to check whether the given Binary Tree is Complete Binary Tree or not. A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible." }, { "code": null, "e": 578, "s": 500, "text": "\nExample 1:\nInput:\n 1\n / \\\n 2 3\nOutput:\nComplete Binary Tree" }, { "code": null, "e": 589, "s": 578, "text": "Example 2:" }, { "code": null, "e": 726, "s": 589, "text": "Input:\n 1\n / \\\n 2 3\n \\ / \\\n 4 5 6\nOutput:\nNot Complete Binary Tree\n" }, { "code": null, "e": 789, "s": 726, "text": "Constraints:\n1<=Number of Node<=100\n0 <= Data of a node <= 106" }, { "code": null, "e": 970, "s": 789, "text": "Your Task:\nYou don't need to take input. Just complete the function isCompleteBT() that takes root node as a parameter and returns true, if the tree is Complete else returns false." }, { "code": null, "e": 976, "s": 974, "text": "0" }, { "code": null, "e": 1001, "s": 976, "text": "amishasahu3283 weeks ago" }, { "code": null, "e": 1838, "s": 1001, "text": " bool isCompleteBT(Node* root){\n //code here\n if(!root) return true;\n // Intution : \n // In a complete binary tree you will never encounter null node between the not null nodes.\n queue<Node*> q;\n q.push(root);\n bool foundNull = false;\n while(!q.empty())\n {\n Node *curr = q.front();\n q.pop();\n if(curr->left)\n {\n if(foundNull)\n return false;\n q.push(curr->left);\n }\n else\n foundNull = true;\n if(curr->right)\n {\n if(foundNull)\n return false;\n q.push(curr->right);\n }\n else\n foundNull = true;\n }\n return true;\n \n }" }, { "code": null, "e": 1840, "s": 1838, "text": "0" }, { "code": null, "e": 1858, "s": 1840, "text": "feyza2 months ago" }, { "code": null, "e": 2567, "s": 1858, "text": "JAVA\n\nclass GfG\n{\n\tboolean isCompleteBT(Node root)\n {\n int index = 0;\n int numNodes = countNodes(root);\n \n if(checkComplete(root, index, numNodes) == true)\n return true;\n \n return false;\n\t}\n\t\n\tboolean checkComplete(Node root, int index, int numberNodes){\n\t if(root == null) return true;\n\t \n\t if(index >= numberNodes)\n\t return false;\n\t \n\t return (checkComplete(root.left, 2 * index + 1, numberNodes)\n && checkComplete(root.right, 2 * index + 2, numberNodes)); \n\t}\n\t\n\tint countNodes(Node root){\n\t if(root == null)\n\t return 0;\n\t \n\t return (1+countNodes(root.left) + countNodes(root.right));\n\t}\n\n}" }, { "code": null, "e": 2570, "s": 2567, "text": "+1" }, { "code": null, "e": 2595, "s": 2570, "text": "nonefrompict2 months ago" }, { "code": null, "e": 2606, "s": 2595, "text": "C++ Code! " }, { "code": null, "e": 3052, "s": 2608, "text": "bool isCompleteBT(Node* root){ //code here bool end=false; queue<Node*>q; q.push(root); while(q.empty()==false){ Node* temp=q.front(); q.pop(); if(temp==NULL){ end=true; }else{ if(end){ return false; } q.push(temp->left); q.push(temp->right); } } return true; }" }, { "code": null, "e": 3055, "s": 3052, "text": "+1" }, { "code": null, "e": 3077, "s": 3055, "text": "vt28522412 months ago" }, { "code": null, "e": 3101, "s": 3077, "text": "Easiest Java - 0.1 time" }, { "code": null, "e": 3152, "s": 3101, "text": "hint - if not null found after null, return false;" }, { "code": null, "e": 3710, "s": 3154, "text": "boolean isCompleteBT(Node root) { Queue<Node> q=new LinkedList<>(); q.add(root); boolean nullFound=false; while(!q.isEmpty()){ int size=q.size(); for(int i=0; i<size; i++){ Node temp=q.remove(); if(temp==null){ nullFound=true; } else{ if(nullFound) return false; q.add(temp.left); q.add(temp.right); } } } return true;} " }, { "code": null, "e": 3712, "s": 3710, "text": "0" }, { "code": null, "e": 3734, "s": 3712, "text": "lindan1232 months ago" }, { "code": null, "e": 4994, "s": 3734, "text": "bool isCompleteBT(Node* root){\n \n queue<Node*> q;\n q.push(root);\n int flag=0;\n while(q.empty()==false)\n {\n int n = q.size();\n while(n--)\n {\n Node* temp = q.front();\n q.pop();\n \n if(temp->left!=NULL)\n {\n if(flag==1)\n {\n return false;\n }\n q.push(temp->left);\n }\n if(temp->left==NULL)\n {\n flag=1;\n }\n if(temp->right!=NULL)\n {\n if(flag==1)\n {\n return false;\n }\n else if(flag==0)\n {\n q.push(temp->right);\n }\n }\n if(temp->right==NULL)\n {\n flag=1;\n }\n }\n }\n return true;\n }" }, { "code": null, "e": 5013, "s": 4996, "text": "Time Taken : 0.0" }, { "code": null, "e": 5017, "s": 5013, "text": "Cpp" }, { "code": null, "e": 5020, "s": 5017, "text": "+2" }, { "code": null, "e": 5053, "s": 5020, "text": "shashikantsolanki0423 months ago" }, { "code": null, "e": 5137, "s": 5053, "text": "HINT : In a complete binary tree you will never encounter null between the values. " }, { "code": null, "e": 5140, "s": 5137, "text": "+1" }, { "code": null, "e": 5169, "s": 5140, "text": "badgujarsachin833 months ago" }, { "code": null, "e": 5819, "s": 5169, "text": " bool isCompleteBT(Node* root){\n //code here\n queue<Node*> q;\n q.push(root);\n bool found=false;\n while(!q.empty()){\n Node* x=q.front();\n q.pop();\n if(x->left!=NULL){\n if(found){\n return false;\n }\n q.push(x->left);\n }else{\n found=true;\n }\n if(x->right!=NULL){\n if(found){\n return false;\n }\n q.push(x->right);\n }else{\n found=true;\n }\n }\n return true;\n }" }, { "code": null, "e": 5822, "s": 5819, "text": "-1" }, { "code": null, "e": 5846, "s": 5822, "text": "chessnoobdj4 months ago" }, { "code": null, "e": 5863, "s": 5846, "text": "C++ 2 approaches" }, { "code": null, "e": 6363, "s": 5863, "text": "bool isCompleteBT(Node* root){\n if(!root) return true;\n queue<node*> q;\n bool isComplete = false;\n q.push(root);\n while(!q.empty()){\n if(q.front()->left){\n if(isComplete) return false;\n else q.push(q.front()->left);\n }\n else isComplete = true;\n if(q.front()->right){\n if(isComplete) return false;\n else q.push(q.front()->right);\n }\n else isComplete = true;\n q.pop();\n }\n return true;\n}" }, { "code": null, "e": 7631, "s": 6363, "text": "bool isCompleteBT(Node* root){\n string str = \"\";\n bool flg = false;\n int val = 1;\n queue <Node*> q;\n q.push(root);\n while(!q.empty()){\n int n = q.size();\n if(flg && n != val)\n return false;\n if(val != n)\n flg = true;\n if(flg){\n for(int i=0; str[i]!='\\0'; i++){\n while(str[i] == 'N' && str[i+1] == 'N')\n i++;\n if(str[i] == 'N' && str[i+1]!='\\0')\n return false;\n }\n }\n //cout << n << \" \" << flg << \" \" << val << \" \" << str << \"\\n\";\n str = \"\";\n while(n--){\n Node *temp = q.front();\n q.pop();\n if(temp->left){\n q.push(temp->left);\n str += to_string(temp->left->data);\n }\n else\n str += 'N';\n if(temp->right){\n q.push(temp->right);\n str += to_string(temp->right->data);\n }\n else\n str += 'N';\n }\n val *= 2;\n }\n return true;\n }\n" }, { "code": null, "e": 7634, "s": 7631, "text": "-1" }, { "code": null, "e": 7661, "s": 7634, "text": "sharad nailwal4 months ago" }, { "code": null, "e": 8155, "s": 7661, "text": " bool isCompleteBT(Node* root){ queue<Node*> q; q.push(root); bool found=false; while(!q.empty()){ Node* temp=q.front();q.pop(); if(temp->left!=NULL){ if(found)return false; q.push(temp->left); } else found=true; if(temp->right!=NULL){ if(found)return false; q.push(temp->right); } else found=true; } return true; }" }, { "code": null, "e": 8158, "s": 8155, "text": "-1" }, { "code": null, "e": 8179, "s": 8158, "text": "kake13375 months ago" }, { "code": null, "e": 9426, "s": 8179, "text": " bool isCompleteBT(Node* root){ queue<Node*> q; q.push(root); bool CT=true; bool flag=false; while(!q.empty()) { int c=q.size(); while(c>0) { Node* curr=q.front(); q.pop(); c--; Node *L=curr->left; Node *R=curr->right; if(L!=NULL && R!=NULL) { if(flag) { CT=false; break; } else { q.push(L); q.push(R); } } else if(L!=NULL && R==NULL) { if(flag) { CT=false; break; } else { flag=true; q.push(L); } } else if(L==NULL && R!=NULL) { CT=false; break; } else flag=true; } if(!CT) break; } return CT; }" }, { "code": null, "e": 9572, "s": 9426, "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": 9608, "s": 9572, "text": " Login to access your submissions. " }, { "code": null, "e": 9618, "s": 9608, "text": "\nProblem\n" }, { "code": null, "e": 9628, "s": 9618, "text": "\nContest\n" }, { "code": null, "e": 9691, "s": 9628, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9839, "s": 9691, "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": 10047, "s": 9839, "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": 10153, "s": 10047, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to use NVIDIA GPUs for Machine Learning with the new Data Science PC from Maingear | by Déborah Mesquita | Towards Data Science
Deep Learning enables us to perform many human-like tasks, but if you’re a data scientist and you don’t work in a FAANG company (or if you’re not developing the next AI startup) chances are that you still use good and old (ok, maybe not that old) Machine Learning to perform your daily tasks. One characteristic of Deep Learning is that it’s very computationally intensive, so all the main DL libraries make use of GPUs to improve the processing speed. But if you ever felt left out of the party because you don't work with Deep Learning, those days are over: with the RAPIDS suite of libraries now we can run our data science and analytics pipelines entirely on GPUs. In this article we’re going to talk about some of these RAPIDS libraries and get to know a little more about the new Data Science PC from Maingear. Generally speaking, GPUs are fast because they have high-bandwidth memories and hardware that performs floating-point arithmetic at significantly higher rates than conventional CPUs [1]. GPUs' main task is to perform the calculations needed to render 3D computer graphics. But then in 2007 NVIDIA created CUDA. CUDA is a parallel computing platform that provides an API for developers, allowing them to build tools that can make use of GPUs for general-purpose processing. GPUs had evolved into highly parallel multi-core systems, allowing very efficient manipulation of large blocks of data. This design is more effective than general-purpose central processing unit (CPUs) for algorithms in situations where processing large blocks of data is done in parallel — CUDA article on Wikipedia [2] Processing large blocks of data is basically what Machine Learning does, so GPUs come in handy for ML tasks. TensorFlow and Pytorch are examples of libraries that already make use of GPUs. Now with the RAPIDS suite of libraries we can also manipulate dataframes and run machine learning algorithms on GPUs as well. RAPIDS is a suite of open source libraries that integrates with popular data science libraries and workflows to speed up machine learning [3]. Some RAPIDS projects include cuDF, a pandas-like dataframe manipulation library; cuML, a collection of machine learning libraries that will provide GPU versions of algorithms available in sciKit-learn; cuGraph, a NetworkX-like accelerated graph analytics library [4]. Pandas and sciKit-learn are two of the main data science libraries, so let’s get to know more about cuDF and cuML. cuDF provides a pandas-like API for dataframe manipulation, so if you know how to use pandas you already know how to use cuDF. There is also the Dask-cuDF library if you want to distribute your workflow across multiple GPUs [5]. We can create series and dataframes just like pandas: import numpy as npimport cudfs = cudf.Series([1,2,3,None,4])df = cudf.DataFrame([('a', list(range(20))), ('b', list(reversed(range(20)))), ('c', list(range(20)))]) It’s also possible to convert a pandas dataframe to a cuDF dataframe (but this is not recommended): import pandas as pdimport cudfdf = pd.DataFrame({'a': [0, 1, 2, 3],'b': [0.1, 0.2, None, 0.3]})gdf = cudf.DataFrame.from_pandas(df) We can also do the opposite and convert a cuDF dataframe to a pandas dataframe: import cudfdf = cudf.DataFrame([('a', list(range(20))), ('b', list(reversed(range(20)))), ('c', list(range(20)))])pandas_df = df.head().to_pandas() Or convert to numpy arrays: import cudfdf = cudf.DataFrame([('a', list(range(20))), ('b', list(reversed(range(20)))), ('c', list(range(20)))])df.as_matrix()df['a'].to_array() Everything else we do with dataframes (viewing data, sorting, selecting, dealing with missing values, working with csv files and so on) works the same: import cudfdf = cudf.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 = cudf.Series([1,2,3,None,4])s.fillna(999)df = cudf.read_csv('example_output/foo.csv')df.to_csv('example_output/foo.csv', index=False) About performance, just to give an example, loading a 1gb csv file using pandas took 13 seconds and loading it with cuDF took 2.53 seconds. cuML integrates with other RAPIDS projects to implement machine learning algorithms and mathematical primitives functions. In most cases, cuML’s Python API matches the API from sciKit-learn. The project still has some limitations (currently the instances of cuML RandomForestClassifier cannot be pickled for example) but they have a short 6-week release schedule so they’re always adding new features. There are implementations for Regression, Classification, Clustering and Dimensionality Reduction algorithms, among other tools. The API is indeed very consistent with sciKit API: import cudfimport numpy as npfrom cuml.linear_model import LogisticRegressionX = cudf.DataFrame()X['col1'] = np.array([1,1,2,2], dtype = np.float32)X['col2'] = np.array([1,2,2,3], dtype = np.float32)y = cudf.Series( np.array([0.0, 0.0, 1.0, 1.0], dtype = np.float32) )# trainingreg = LogisticRegression()reg.fit(X,y)print("Coefficients:")print(reg.coef_.copy_to_host())print("Intercept:")print(reg.intercept_.copy_to_host())# making predictionsX_new = cudf.DataFrame()X_new['col1'] = np.array([1,5], dtype = np.float32)X_new['col2'] = np.array([2,5], dtype = np.float32)preds = reg.predict(X_new)print("Predictions:")print(preds) This is all great, but how can we use these tools? Well, first you need to get an NVIDIA GPU card compatible with RAPIDS. If you don’t want to spend time figuring out the best choices for the hardware specs, NVIDIA is releasing the Data Science PC. The PC comes with a software stack optimized to run all these libraries for Machine Learning and Deep Learning. It comes with Ubuntu 18.04 and you can use docker containers from NVIDIA GPU Cloud or use the native conda environment. One of the best things about the PC is that you get all the libraries and software fully installed. If you ever had to install NVIDIA drivers on a Linux distro or had to install TensorFlow from source you know how dreamy this is. These are the system specifications: GPU NVIDIA Titan RTX with 24 GB of GPU memory or 2-way NVIDIA Titan RTX connected via NVIDIA NVLink offering a combined 48 GB of GPU memory CPU Intel Core i7 class CPU or higher System memory Minimum of 48 GB DDR4 system memory for single GPU configuration and Minimum of 96 GB of DDR4 system memory for dual GPU configurations Disk Minimum of 1 TB SSD The Maingear VYBE PRO Data Science PC comes with up to two dual NVIDIA TITAN RTX 24GB cards and each PC is hand-assembled. Training a XGBoost model on a VYBER PRO PC using a dataset with 4,000,000 rows and 1000 columns (this dataframe uses approx. 15 GB of memory) takes 1min 46s on CPU (with a memory increment of 73325 MiB) and only 21.2s on GPUs (with a memory increment of 520 MiB). With Data Science we are always in need to explore and try new things. Among other Software Engineering challenges that make our workflow difficult, the size and the time it takes to compute our data are two bottlenecks that prevent us from getting to a flow state while running our experiments. Having a PC and tools that can improve this can really speed up our work and help us spot interesting patterns in our data faster. Imagine getting a 40 GB csv file and just simply loading it into memory to see what it is about. The RAPIDS tools bring to machine learning engineers the GPU processing speed improvements deep learning engineers were already familiar with. To make products that use machine learning we need to iterate and make sure we have solid end to end pipelines, and using GPUs to execute them will hopefully improve our outputs for the projects.
[ { "code": null, "e": 465, "s": 172, "text": "Deep Learning enables us to perform many human-like tasks, but if you’re a data scientist and you don’t work in a FAANG company (or if you’re not developing the next AI startup) chances are that you still use good and old (ok, maybe not that old) Machine Learning to perform your daily tasks." }, { "code": null, "e": 841, "s": 465, "text": "One characteristic of Deep Learning is that it’s very computationally intensive, so all the main DL libraries make use of GPUs to improve the processing speed. But if you ever felt left out of the party because you don't work with Deep Learning, those days are over: with the RAPIDS suite of libraries now we can run our data science and analytics pipelines entirely on GPUs." }, { "code": null, "e": 989, "s": 841, "text": "In this article we’re going to talk about some of these RAPIDS libraries and get to know a little more about the new Data Science PC from Maingear." }, { "code": null, "e": 1262, "s": 989, "text": "Generally speaking, GPUs are fast because they have high-bandwidth memories and hardware that performs floating-point arithmetic at significantly higher rates than conventional CPUs [1]. GPUs' main task is to perform the calculations needed to render 3D computer graphics." }, { "code": null, "e": 1462, "s": 1262, "text": "But then in 2007 NVIDIA created CUDA. CUDA is a parallel computing platform that provides an API for developers, allowing them to build tools that can make use of GPUs for general-purpose processing." }, { "code": null, "e": 1783, "s": 1462, "text": "GPUs had evolved into highly parallel multi-core systems, allowing very efficient manipulation of large blocks of data. This design is more effective than general-purpose central processing unit (CPUs) for algorithms in situations where processing large blocks of data is done in parallel — CUDA article on Wikipedia [2]" }, { "code": null, "e": 2098, "s": 1783, "text": "Processing large blocks of data is basically what Machine Learning does, so GPUs come in handy for ML tasks. TensorFlow and Pytorch are examples of libraries that already make use of GPUs. Now with the RAPIDS suite of libraries we can also manipulate dataframes and run machine learning algorithms on GPUs as well." }, { "code": null, "e": 2241, "s": 2098, "text": "RAPIDS is a suite of open source libraries that integrates with popular data science libraries and workflows to speed up machine learning [3]." }, { "code": null, "e": 2509, "s": 2241, "text": "Some RAPIDS projects include cuDF, a pandas-like dataframe manipulation library; cuML, a collection of machine learning libraries that will provide GPU versions of algorithms available in sciKit-learn; cuGraph, a NetworkX-like accelerated graph analytics library [4]." }, { "code": null, "e": 2624, "s": 2509, "text": "Pandas and sciKit-learn are two of the main data science libraries, so let’s get to know more about cuDF and cuML." }, { "code": null, "e": 2853, "s": 2624, "text": "cuDF provides a pandas-like API for dataframe manipulation, so if you know how to use pandas you already know how to use cuDF. There is also the Dask-cuDF library if you want to distribute your workflow across multiple GPUs [5]." }, { "code": null, "e": 2907, "s": 2853, "text": "We can create series and dataframes just like pandas:" }, { "code": null, "e": 3111, "s": 2907, "text": "import numpy as npimport cudfs = cudf.Series([1,2,3,None,4])df = cudf.DataFrame([('a', list(range(20))), ('b', list(reversed(range(20)))), ('c', list(range(20)))])" }, { "code": null, "e": 3211, "s": 3111, "text": "It’s also possible to convert a pandas dataframe to a cuDF dataframe (but this is not recommended):" }, { "code": null, "e": 3343, "s": 3211, "text": "import pandas as pdimport cudfdf = pd.DataFrame({'a': [0, 1, 2, 3],'b': [0.1, 0.2, None, 0.3]})gdf = cudf.DataFrame.from_pandas(df)" }, { "code": null, "e": 3423, "s": 3343, "text": "We can also do the opposite and convert a cuDF dataframe to a pandas dataframe:" }, { "code": null, "e": 3611, "s": 3423, "text": "import cudfdf = cudf.DataFrame([('a', list(range(20))), ('b', list(reversed(range(20)))), ('c', list(range(20)))])pandas_df = df.head().to_pandas()" }, { "code": null, "e": 3639, "s": 3611, "text": "Or convert to numpy arrays:" }, { "code": null, "e": 3826, "s": 3639, "text": "import cudfdf = cudf.DataFrame([('a', list(range(20))), ('b', list(reversed(range(20)))), ('c', list(range(20)))])df.as_matrix()df['a'].to_array()" }, { "code": null, "e": 3978, "s": 3826, "text": "Everything else we do with dataframes (viewing data, sorting, selecting, dealing with missing values, working with csv files and so on) works the same:" }, { "code": null, "e": 4331, "s": 3978, "text": "import cudfdf = cudf.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 = cudf.Series([1,2,3,None,4])s.fillna(999)df = cudf.read_csv('example_output/foo.csv')df.to_csv('example_output/foo.csv', index=False)" }, { "code": null, "e": 4471, "s": 4331, "text": "About performance, just to give an example, loading a 1gb csv file using pandas took 13 seconds and loading it with cuDF took 2.53 seconds." }, { "code": null, "e": 4873, "s": 4471, "text": "cuML integrates with other RAPIDS projects to implement machine learning algorithms and mathematical primitives functions. In most cases, cuML’s Python API matches the API from sciKit-learn. The project still has some limitations (currently the instances of cuML RandomForestClassifier cannot be pickled for example) but they have a short 6-week release schedule so they’re always adding new features." }, { "code": null, "e": 5053, "s": 4873, "text": "There are implementations for Regression, Classification, Clustering and Dimensionality Reduction algorithms, among other tools. The API is indeed very consistent with sciKit API:" }, { "code": null, "e": 5683, "s": 5053, "text": "import cudfimport numpy as npfrom cuml.linear_model import LogisticRegressionX = cudf.DataFrame()X['col1'] = np.array([1,1,2,2], dtype = np.float32)X['col2'] = np.array([1,2,2,3], dtype = np.float32)y = cudf.Series( np.array([0.0, 0.0, 1.0, 1.0], dtype = np.float32) )# trainingreg = LogisticRegression()reg.fit(X,y)print(\"Coefficients:\")print(reg.coef_.copy_to_host())print(\"Intercept:\")print(reg.intercept_.copy_to_host())# making predictionsX_new = cudf.DataFrame()X_new['col1'] = np.array([1,5], dtype = np.float32)X_new['col2'] = np.array([2,5], dtype = np.float32)preds = reg.predict(X_new)print(\"Predictions:\")print(preds)" }, { "code": null, "e": 5932, "s": 5683, "text": "This is all great, but how can we use these tools? Well, first you need to get an NVIDIA GPU card compatible with RAPIDS. If you don’t want to spend time figuring out the best choices for the hardware specs, NVIDIA is releasing the Data Science PC." }, { "code": null, "e": 6431, "s": 5932, "text": "The PC comes with a software stack optimized to run all these libraries for Machine Learning and Deep Learning. It comes with Ubuntu 18.04 and you can use docker containers from NVIDIA GPU Cloud or use the native conda environment. One of the best things about the PC is that you get all the libraries and software fully installed. If you ever had to install NVIDIA drivers on a Linux distro or had to install TensorFlow from source you know how dreamy this is. These are the system specifications:" }, { "code": null, "e": 6435, "s": 6431, "text": "GPU" }, { "code": null, "e": 6571, "s": 6435, "text": "NVIDIA Titan RTX with 24 GB of GPU memory or 2-way NVIDIA Titan RTX connected via NVIDIA NVLink offering a combined 48 GB of GPU memory" }, { "code": null, "e": 6575, "s": 6571, "text": "CPU" }, { "code": null, "e": 6609, "s": 6575, "text": "Intel Core i7 class CPU or higher" }, { "code": null, "e": 6623, "s": 6609, "text": "System memory" }, { "code": null, "e": 6759, "s": 6623, "text": "Minimum of 48 GB DDR4 system memory for single GPU configuration and Minimum of 96 GB of DDR4 system memory for dual GPU configurations" }, { "code": null, "e": 6764, "s": 6759, "text": "Disk" }, { "code": null, "e": 6784, "s": 6764, "text": "Minimum of 1 TB SSD" }, { "code": null, "e": 6907, "s": 6784, "text": "The Maingear VYBE PRO Data Science PC comes with up to two dual NVIDIA TITAN RTX 24GB cards and each PC is hand-assembled." }, { "code": null, "e": 7171, "s": 6907, "text": "Training a XGBoost model on a VYBER PRO PC using a dataset with 4,000,000 rows and 1000 columns (this dataframe uses approx. 15 GB of memory) takes 1min 46s on CPU (with a memory increment of 73325 MiB) and only 21.2s on GPUs (with a memory increment of 520 MiB)." }, { "code": null, "e": 7695, "s": 7171, "text": "With Data Science we are always in need to explore and try new things. Among other Software Engineering challenges that make our workflow difficult, the size and the time it takes to compute our data are two bottlenecks that prevent us from getting to a flow state while running our experiments. Having a PC and tools that can improve this can really speed up our work and help us spot interesting patterns in our data faster. Imagine getting a 40 GB csv file and just simply loading it into memory to see what it is about." } ]
How to sort a column of a Pandas DataFrame?
To sort a column in a Pandas DataFrame, we can use the sort_values() method. Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df. Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df. Print input DataFrame, df. Print input DataFrame, df. Initialize a variable col to sort the column. Initialize a variable col to sort the column. Print the sorted DataFrame. Print the sorted DataFrame. Live Demo import pandas as pd df = pd.DataFrame( { "x": [5, 2, 7, 0], "y": [4, 10, 5, 1], `"z": [9, 3, 5, 1] } ) print "Input DataFrame is:\n", df col = "x" df = df[col].sort_values(ascending=False) print "After sorting column ", col, "DataFrame is:\n", df Input DataFrame is: x y z 0 5 4 9 1 2 10 3 2 7 5 5 3 0 1 1 After sorting column x DataFrame is: 2 7 0 5 1 2 3 0 Name: x, dtype: int64
[ { "code": null, "e": 1139, "s": 1062, "text": "To sort a column in a Pandas DataFrame, we can use the sort_values() method." }, { "code": null, "e": 1223, "s": 1139, "text": "Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df." }, { "code": null, "e": 1307, "s": 1223, "text": "Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df." }, { "code": null, "e": 1334, "s": 1307, "text": "Print input DataFrame, df." }, { "code": null, "e": 1361, "s": 1334, "text": "Print input DataFrame, df." }, { "code": null, "e": 1407, "s": 1361, "text": "Initialize a variable col to sort the column." }, { "code": null, "e": 1453, "s": 1407, "text": "Initialize a variable col to sort the column." }, { "code": null, "e": 1481, "s": 1453, "text": "Print the sorted DataFrame." }, { "code": null, "e": 1509, "s": 1481, "text": "Print the sorted DataFrame." }, { "code": null, "e": 1520, "s": 1509, "text": " Live Demo" }, { "code": null, "e": 1788, "s": 1520, "text": "import pandas as pd\n\ndf = pd.DataFrame(\n {\n \"x\": [5, 2, 7, 0],\n \"y\": [4, 10, 5, 1],\n `\"z\": [9, 3, 5, 1]\n }\n)\n\nprint \"Input DataFrame is:\\n\", df\ncol = \"x\"\ndf = df[col].sort_values(ascending=False)\nprint \"After sorting column \", col, \"DataFrame is:\\n\", df" }, { "code": null, "e": 1942, "s": 1788, "text": "Input DataFrame is:\n x y z\n0 5 4 9\n1 2 10 3\n2 7 5 5\n3 0 1 1\nAfter sorting column x DataFrame is:\n2 7\n0 5\n1 2\n3 0\nName: x, dtype: int64" } ]
How to Build a Fake News Detection Web App Using Flask | by Fangyi Yu | Towards Data Science
The spread of fake news is unstoppable with the adoption of different social networks. On Twitter, Facebook, Reddit, people take advantage of fake news to spread rumours, win political benefits and click rates. Detecting fake news is critical for a healthy society, and there are multiple different approaches to detect fake news. From a machine learning standpoint, fake news detection is a binary classification problem; hence we can use traditional classification methods or state-of-the-art Neural Networks to deal with this problem. This tutorial will create a natural language processing application from scratch and deploy it on Flask. In the end, you will have a Fake news detection web app running on your local machine. See the teaser here. The tutorial is organized in the following structure: Step1: Load data from Kaggle to Google Colab. Step2: Text preprocessing. Step3: Model training and validation. Step4: Pickle and load model. Step5: Create a Flask APP and a virtual environment. Step6: Add functionalities. Conclusion. Note: The complete notebook is on GitHub. Well, the most fundamental part of a machine learning project is data. We will use the Fake and real news dataset from Kaggle to build our machine learning model. I wrote a blog about how to download data from Kaggle to Google Colab before. Feel free to follow the steps inside. There are two separate CSV files in the folder, True and False, corresponding to Real and Fake news. Let’s have a look at what the data look like: true = pd.read_csv('True.csv')fake = pd.read_csv('Fake.csv')true.head(3) The datasets have four columns, but they have no label yet, let’s create labels first. Fake news as label 0 and Real news label 1. true['label'] = 1fake['label'] = 0 The datasets are relatively clean and organized. For the sake of training speed, we are using the first 5000 data points in both datasets to build the model. You can also use the complete datasets to get a more comprehensive result. # Combine the sub-datasets in one.frames = [true.loc[:5000][:], fake.loc[:5000][:]]df = pd.concat(frames)df.tail() Let’s also separate features and labels as well as make a copy of the DataFrame for later training. X = df.drop('label', axis=1) y = df['label']# Delete missing datadf = df.dropna()df2 = df.copy()df2.reset_index(inplace=True) Cool! Time for the real text preprocessing, which includes deleting punctuations, lowering all capitalized characters, deleting all stopwords, and stemming, most of the time we call this process as tokenization. from nltk.corpus import stopwordsfrom nltk.stem.porter import PorterStemmerimport reimport nltknltk.download('stopwords')ps = PorterStemmer()corpus = []for i in range(0, len(df2)): review = re.sub('[^a-zA-Z]', ' ', df2['text'][i]) review = review.lower() review = review.split() review = [ps.stem(word) for word in review if not word in stopwords.words('english')] review = ' '.join(review) corpus.append(review) Next, let’s use the TF-IDF vectorizer to convert each token to a vector, aka, vectorize tokens or word embedding. You can play with this dataset with other word embedding techniques, such as Word2Vec, Glove, and even BERT, but I found TF-IDF good enough to generate an accurate result. A concise explanation for TF-IDF (Term Frequency — Inverse Document Frequency): it calculates how important a word is by considering both the frequency of that word in a document and other documents in the same corpus. For example, the word “detection” appears quite a lot in this article but not in other articles in the MEDIUM corpus; hence “detection” is a critical word in this post, but the word “term” exists almost in any document with a high frequency, so it’s not so important. A more detailed introduction about TF-IDF can be found in this Medium blog. from sklearn.feature_extraction.text import TfidfVectorizertfidf_v = TfidfVectorizer(max_features=5000, ngram_range=(1,3))X = tfidf_v.fit_transform(corpus).toarray()y = df2['label'] Mostly done! Let’s do the last step to split the dataset to train and test! from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) You can try multiple classification algorithms here: Logistic Regression, SVM, XGBoost, CatBoost or Neural Networks. I am using the Online Passive-Aggressive Algorithms. from sklearn.linear_model import PassiveAggressiveClassifierfrom sklearn import metricsimport numpy as npimport itertoolsclassifier = PassiveAggressiveClassifier(max_iter=1000)classifier.fit(X_train, y_train)pred = classifier.predict(X_test)score = metrics.accuracy_score(y_test, pred)print("accuracy: %0.3f" % score) Pretty good result!Let’s print the confusion matrix to have a look at the False Positives and False Negatives. import matplotlib.pyplot as pltdef plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, cm[i, j], horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label')cm = metrics.confusion_matrix(y_test, pred)plot_confusion_matrix(cm, classes=['FAKE', 'REAL']) So, we got 3 False Positives and no False Negatives using the Passive-Aggressive algorithm in a balanced dataset with a TF-IDF vectorizer. Let’s validate using an unseen dataset, say, the 13070th data point from the Fake CSV file. We anticipate the result of the classification model to be 0. # Tokenizationreview = re.sub('[^a-zA-Z]', ' ', fake['text'][13070])review = review.lower()review = review.split() review = [ps.stem(word) for word in review if not word in stopwords.words('english')]review = ' '.join(review)# Vectorizationval = tfidf_v.transform([review]).toarray()# Predict classifier.predict(val) Cool! We got what we want. You can try more unseen data points from the complete dataset. I believe the model would give you a satisfying answer with such high accuracy. Now, time to pickle (save) the model and vectorizer so you can use them elsewhere. import picklepickle.dump(classifier, open('model2.pkl', 'wb'))pickle.dump(tfidf_v, open('tfidfvect2.pkl', 'wb')) Let’s see if we can use this model without training again. # Load model and vectorizerjoblib_model = pickle.load(open('model2.pkl', 'rb'))joblib_vect = pickle.load(open('tfidfvect2.pkl', 'rb'))val_pkl = joblib_vect.transform([review]).toarray()joblib_model.predict(val_pkl) We got the same output! That’s what we expected! Now the model is ready, time for us to deploy it and detect any news on the web application. Flask is a lightweight WSGI web application framework. Compared with Django, Flask is easier to learn, whereas it’s inappropriate for production use because of security concerns. For the purpose of this blog, you will learn Flask. Instead, feel free to follow my other tutorial on how to deploy an app using Django. From the terminal or command line, create a new directory: From the terminal or command line, create a new directory: mkdir myprojectcd myproject 2. Inside the project directory, create a virtual environment for the project. If you don’t have virtualen installed, run the following to install the environment in your terminal. pip install virtualenv After virtualen is installed, run the following to create an env. virtualenv <ENV_NAME> Replace the name of your env in<ENV_NAME> Activate the env by: source <ENV_NAME>/bin/activate You can remove the env when it’s needed using the following command: sudo rm -rf <ENV_NAME> Now your env is ready. Let’s install Flask first. pip install flask It’s time to build the web app! To start, let’s create a new file in the same directory with the following content and name it app.py, and we will add the functionalities in this file. Move the pickled model and vectorizer in the previous step to the same directory. We are going to build four functions: home is for returning to the home page; predict is for getting the classification result, whether the input news is fake or real; webapp is for returning the prediction on the web page; api is to convert the classification result to JSON file to build an external API. You may find the Flask official documentation helpful. from flask import Flask, render_template, request, jsonifyimport nltkimport picklefrom nltk.corpus import stopwordsimport refrom nltk.stem.porter import PorterStemmerapp = Flask(__name__)ps = PorterStemmer()# Load model and vectorizermodel = pickle.load(open('model2.pkl', 'rb'))tfidfvect = pickle.load(open('tfidfvect2.pkl', 'rb'))# Build functionalities@app.route('/', methods=['GET'])def home(): return render_template('index.html')def predict(text): review = re.sub('[^a-zA-Z]', ' ', text) review = review.lower() review = review.split() review = [ps.stem(word) for word in review if not word in stopwords.words('english')] review = ' '.join(review) review_vect = tfidfvect.transform([review]).toarray() prediction = 'FAKE' if model.predict(review_vect) == 0 else 'REAL' return prediction@app.route('/', methods=['POST'])def webapp(): text = request.form['text'] prediction = predict(text) return render_template('index.html', text=text, result=prediction)@app.route('/predict/', methods=['GET','POST'])def api(): text = request.args.get("text") prediction = predict(text) return jsonify(prediction=prediction)if __name__ == "__main__": app.run() You can see an index.html file in the previous section, and it’s the home page of the application. Create a folder named “Templates” in the root folder, and create a file “index.html” inside. Now let’s add some content to the page. <!DOCTYPE HTML><html><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Fake News Prediction</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script></head><body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="/">FAKE NEWS PREDICTION</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="nav navbar-nav navbar-right" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-link" target="_blank" href="https://rapidapi.com/fangyiyu/api/fake-news-detection1/">API</a> <a class="nav-link" target="_blank" href="https://medium.com/@fangyiyu/how-to-build-a-fake-news-detection-web-app-using-flask-c0cfd1d9c2d4?sk=2a752b0d87c759672664232b33543667/">Blog</a> <a class="nav-link" target="_blank" href="https://github.com/fangyiyu/Fake_News_Detection_Flask/blob/main/Fake_news_detection.ipynb">NoteBook</a> <a class="nav-link" target="_blank" href="https://github.com/fangyiyu/Fake_News_Detection_Flask">Code Source</a> </div> </div> </div> </nav><br> <p style=text-align:center>A fake news prediction web application using Machine Learning algorithms, deployed using Django and Heroku. </p> <p style=text-align:center>Enter your text to try it.</p> <br> <div class='container'> <form action="/" method="POST"> <div class="col-three-forth text-center col-md-offset-2"> <div class="form-group"> <textarea class="form-control jTextarea mt-3" id="jTextarea'" rows="5" name="text" placeholder="Write your text here..." required>{{text}}</textarea><br><br> <button class="btn btn-primary btn-outline btn-md" type="submit" name="predict">Predict</button> </div> </div> </form> </div> <br> {% if result %} <p style="text-align:center"><strong>Prediction : {{result}}</strong></p> {% endif %}<script> function growTextarea (i,elem) { var elem = $(elem); var resizeTextarea = function( elem ) { var scrollLeft = window.pageXOffset || (document.documentElement || document.body.parentNode || document.body).scrollLeft; var scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop; elem.css('height', 'auto').css('height', elem.prop('scrollHeight') ); window.scrollTo(scrollLeft, scrollTop); }; elem.on('input', function() { resizeTextarea( $(this) ); }); resizeTextarea( $(elem) ); } $('.jTextarea').each(growTextarea);</script></body></html> The above script creates a web page like this: Now you can run your app by typing the following command in your terminal: python3 app.py You will be able to run your app locally and have a test on the model. In this tutorial, you built a machine learning model to detect fake news from real ones from scratch and saved the model to build a web application using Flask. The web application is running in your local machine, and you can try to make it public using cloud services such as Heroku, AWS or DigitalOcean. I have deployed mine on Heroku. Feel free to have a try. I hope you enjoy this journey. Welcome to leave a comment and connect with me on Linkedin.
[ { "code": null, "e": 382, "s": 171, "text": "The spread of fake news is unstoppable with the adoption of different social networks. On Twitter, Facebook, Reddit, people take advantage of fake news to spread rumours, win political benefits and click rates." }, { "code": null, "e": 709, "s": 382, "text": "Detecting fake news is critical for a healthy society, and there are multiple different approaches to detect fake news. From a machine learning standpoint, fake news detection is a binary classification problem; hence we can use traditional classification methods or state-of-the-art Neural Networks to deal with this problem." }, { "code": null, "e": 922, "s": 709, "text": "This tutorial will create a natural language processing application from scratch and deploy it on Flask. In the end, you will have a Fake news detection web app running on your local machine. See the teaser here." }, { "code": null, "e": 976, "s": 922, "text": "The tutorial is organized in the following structure:" }, { "code": null, "e": 1022, "s": 976, "text": "Step1: Load data from Kaggle to Google Colab." }, { "code": null, "e": 1049, "s": 1022, "text": "Step2: Text preprocessing." }, { "code": null, "e": 1087, "s": 1049, "text": "Step3: Model training and validation." }, { "code": null, "e": 1117, "s": 1087, "text": "Step4: Pickle and load model." }, { "code": null, "e": 1170, "s": 1117, "text": "Step5: Create a Flask APP and a virtual environment." }, { "code": null, "e": 1198, "s": 1170, "text": "Step6: Add functionalities." }, { "code": null, "e": 1210, "s": 1198, "text": "Conclusion." }, { "code": null, "e": 1252, "s": 1210, "text": "Note: The complete notebook is on GitHub." }, { "code": null, "e": 1415, "s": 1252, "text": "Well, the most fundamental part of a machine learning project is data. We will use the Fake and real news dataset from Kaggle to build our machine learning model." }, { "code": null, "e": 1531, "s": 1415, "text": "I wrote a blog about how to download data from Kaggle to Google Colab before. Feel free to follow the steps inside." }, { "code": null, "e": 1678, "s": 1531, "text": "There are two separate CSV files in the folder, True and False, corresponding to Real and Fake news. Let’s have a look at what the data look like:" }, { "code": null, "e": 1751, "s": 1678, "text": "true = pd.read_csv('True.csv')fake = pd.read_csv('Fake.csv')true.head(3)" }, { "code": null, "e": 1882, "s": 1751, "text": "The datasets have four columns, but they have no label yet, let’s create labels first. Fake news as label 0 and Real news label 1." }, { "code": null, "e": 1917, "s": 1882, "text": "true['label'] = 1fake['label'] = 0" }, { "code": null, "e": 2150, "s": 1917, "text": "The datasets are relatively clean and organized. For the sake of training speed, we are using the first 5000 data points in both datasets to build the model. You can also use the complete datasets to get a more comprehensive result." }, { "code": null, "e": 2265, "s": 2150, "text": "# Combine the sub-datasets in one.frames = [true.loc[:5000][:], fake.loc[:5000][:]]df = pd.concat(frames)df.tail()" }, { "code": null, "e": 2365, "s": 2265, "text": "Let’s also separate features and labels as well as make a copy of the DataFrame for later training." }, { "code": null, "e": 2491, "s": 2365, "text": "X = df.drop('label', axis=1) y = df['label']# Delete missing datadf = df.dropna()df2 = df.copy()df2.reset_index(inplace=True)" }, { "code": null, "e": 2703, "s": 2491, "text": "Cool! Time for the real text preprocessing, which includes deleting punctuations, lowering all capitalized characters, deleting all stopwords, and stemming, most of the time we call this process as tokenization." }, { "code": null, "e": 3138, "s": 2703, "text": "from nltk.corpus import stopwordsfrom nltk.stem.porter import PorterStemmerimport reimport nltknltk.download('stopwords')ps = PorterStemmer()corpus = []for i in range(0, len(df2)): review = re.sub('[^a-zA-Z]', ' ', df2['text'][i]) review = review.lower() review = review.split() review = [ps.stem(word) for word in review if not word in stopwords.words('english')] review = ' '.join(review) corpus.append(review)" }, { "code": null, "e": 3424, "s": 3138, "text": "Next, let’s use the TF-IDF vectorizer to convert each token to a vector, aka, vectorize tokens or word embedding. You can play with this dataset with other word embedding techniques, such as Word2Vec, Glove, and even BERT, but I found TF-IDF good enough to generate an accurate result." }, { "code": null, "e": 3643, "s": 3424, "text": "A concise explanation for TF-IDF (Term Frequency — Inverse Document Frequency): it calculates how important a word is by considering both the frequency of that word in a document and other documents in the same corpus." }, { "code": null, "e": 3911, "s": 3643, "text": "For example, the word “detection” appears quite a lot in this article but not in other articles in the MEDIUM corpus; hence “detection” is a critical word in this post, but the word “term” exists almost in any document with a high frequency, so it’s not so important." }, { "code": null, "e": 3987, "s": 3911, "text": "A more detailed introduction about TF-IDF can be found in this Medium blog." }, { "code": null, "e": 4169, "s": 3987, "text": "from sklearn.feature_extraction.text import TfidfVectorizertfidf_v = TfidfVectorizer(max_features=5000, ngram_range=(1,3))X = tfidf_v.fit_transform(corpus).toarray()y = df2['label']" }, { "code": null, "e": 4245, "s": 4169, "text": "Mostly done! Let’s do the last step to split the dataset to train and test!" }, { "code": null, "e": 4386, "s": 4245, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)" }, { "code": null, "e": 4556, "s": 4386, "text": "You can try multiple classification algorithms here: Logistic Regression, SVM, XGBoost, CatBoost or Neural Networks. I am using the Online Passive-Aggressive Algorithms." }, { "code": null, "e": 4876, "s": 4556, "text": "from sklearn.linear_model import PassiveAggressiveClassifierfrom sklearn import metricsimport numpy as npimport itertoolsclassifier = PassiveAggressiveClassifier(max_iter=1000)classifier.fit(X_train, y_train)pred = classifier.predict(X_test)score = metrics.accuracy_score(y_test, pred)print(\"accuracy: %0.3f\" % score)" }, { "code": null, "e": 4987, "s": 4876, "text": "Pretty good result!Let’s print the confusion matrix to have a look at the False Positives and False Negatives." }, { "code": null, "e": 6021, "s": 4987, "text": "import matplotlib.pyplot as pltdef plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print(\"Normalized confusion matrix\") else: print('Confusion matrix, without normalization') thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, cm[i, j], horizontalalignment=\"center\", color=\"white\" if cm[i, j] > thresh else \"black\") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label')cm = metrics.confusion_matrix(y_test, pred)plot_confusion_matrix(cm, classes=['FAKE', 'REAL'])" }, { "code": null, "e": 6160, "s": 6021, "text": "So, we got 3 False Positives and no False Negatives using the Passive-Aggressive algorithm in a balanced dataset with a TF-IDF vectorizer." }, { "code": null, "e": 6314, "s": 6160, "text": "Let’s validate using an unseen dataset, say, the 13070th data point from the Fake CSV file. We anticipate the result of the classification model to be 0." }, { "code": null, "e": 6631, "s": 6314, "text": "# Tokenizationreview = re.sub('[^a-zA-Z]', ' ', fake['text'][13070])review = review.lower()review = review.split() review = [ps.stem(word) for word in review if not word in stopwords.words('english')]review = ' '.join(review)# Vectorizationval = tfidf_v.transform([review]).toarray()# Predict classifier.predict(val)" }, { "code": null, "e": 6801, "s": 6631, "text": "Cool! We got what we want. You can try more unseen data points from the complete dataset. I believe the model would give you a satisfying answer with such high accuracy." }, { "code": null, "e": 6884, "s": 6801, "text": "Now, time to pickle (save) the model and vectorizer so you can use them elsewhere." }, { "code": null, "e": 6997, "s": 6884, "text": "import picklepickle.dump(classifier, open('model2.pkl', 'wb'))pickle.dump(tfidf_v, open('tfidfvect2.pkl', 'wb'))" }, { "code": null, "e": 7056, "s": 6997, "text": "Let’s see if we can use this model without training again." }, { "code": null, "e": 7271, "s": 7056, "text": "# Load model and vectorizerjoblib_model = pickle.load(open('model2.pkl', 'rb'))joblib_vect = pickle.load(open('tfidfvect2.pkl', 'rb'))val_pkl = joblib_vect.transform([review]).toarray()joblib_model.predict(val_pkl)" }, { "code": null, "e": 7320, "s": 7271, "text": "We got the same output! That’s what we expected!" }, { "code": null, "e": 7413, "s": 7320, "text": "Now the model is ready, time for us to deploy it and detect any news on the web application." }, { "code": null, "e": 7729, "s": 7413, "text": "Flask is a lightweight WSGI web application framework. Compared with Django, Flask is easier to learn, whereas it’s inappropriate for production use because of security concerns. For the purpose of this blog, you will learn Flask. Instead, feel free to follow my other tutorial on how to deploy an app using Django." }, { "code": null, "e": 7788, "s": 7729, "text": "From the terminal or command line, create a new directory:" }, { "code": null, "e": 7847, "s": 7788, "text": "From the terminal or command line, create a new directory:" }, { "code": null, "e": 7875, "s": 7847, "text": "mkdir myprojectcd myproject" }, { "code": null, "e": 7954, "s": 7875, "text": "2. Inside the project directory, create a virtual environment for the project." }, { "code": null, "e": 8056, "s": 7954, "text": "If you don’t have virtualen installed, run the following to install the environment in your terminal." }, { "code": null, "e": 8079, "s": 8056, "text": "pip install virtualenv" }, { "code": null, "e": 8145, "s": 8079, "text": "After virtualen is installed, run the following to create an env." }, { "code": null, "e": 8167, "s": 8145, "text": "virtualenv <ENV_NAME>" }, { "code": null, "e": 8209, "s": 8167, "text": "Replace the name of your env in<ENV_NAME>" }, { "code": null, "e": 8230, "s": 8209, "text": "Activate the env by:" }, { "code": null, "e": 8261, "s": 8230, "text": "source <ENV_NAME>/bin/activate" }, { "code": null, "e": 8330, "s": 8261, "text": "You can remove the env when it’s needed using the following command:" }, { "code": null, "e": 8353, "s": 8330, "text": "sudo rm -rf <ENV_NAME>" }, { "code": null, "e": 8403, "s": 8353, "text": "Now your env is ready. Let’s install Flask first." }, { "code": null, "e": 8421, "s": 8403, "text": "pip install flask" }, { "code": null, "e": 8453, "s": 8421, "text": "It’s time to build the web app!" }, { "code": null, "e": 8688, "s": 8453, "text": "To start, let’s create a new file in the same directory with the following content and name it app.py, and we will add the functionalities in this file. Move the pickled model and vectorizer in the previous step to the same directory." }, { "code": null, "e": 8995, "s": 8688, "text": "We are going to build four functions: home is for returning to the home page; predict is for getting the classification result, whether the input news is fake or real; webapp is for returning the prediction on the web page; api is to convert the classification result to JSON file to build an external API." }, { "code": null, "e": 9050, "s": 8995, "text": "You may find the Flask official documentation helpful." }, { "code": null, "e": 10249, "s": 9050, "text": "from flask import Flask, render_template, request, jsonifyimport nltkimport picklefrom nltk.corpus import stopwordsimport refrom nltk.stem.porter import PorterStemmerapp = Flask(__name__)ps = PorterStemmer()# Load model and vectorizermodel = pickle.load(open('model2.pkl', 'rb'))tfidfvect = pickle.load(open('tfidfvect2.pkl', 'rb'))# Build functionalities@app.route('/', methods=['GET'])def home(): return render_template('index.html')def predict(text): review = re.sub('[^a-zA-Z]', ' ', text) review = review.lower() review = review.split() review = [ps.stem(word) for word in review if not word in stopwords.words('english')] review = ' '.join(review) review_vect = tfidfvect.transform([review]).toarray() prediction = 'FAKE' if model.predict(review_vect) == 0 else 'REAL' return prediction@app.route('/', methods=['POST'])def webapp(): text = request.form['text'] prediction = predict(text) return render_template('index.html', text=text, result=prediction)@app.route('/predict/', methods=['GET','POST'])def api(): text = request.args.get(\"text\") prediction = predict(text) return jsonify(prediction=prediction)if __name__ == \"__main__\": app.run()" }, { "code": null, "e": 10481, "s": 10249, "text": "You can see an index.html file in the previous section, and it’s the home page of the application. Create a folder named “Templates” in the root folder, and create a file “index.html” inside. Now let’s add some content to the page." }, { "code": null, "e": 13714, "s": 10481, "text": "<!DOCTYPE HTML><html><head> <meta charset=\"utf-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <title>Fake News Prediction</title> <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC\" crossorigin=\"anonymous\"> <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js\" integrity=\"sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js\"></script></head><body> <nav class=\"navbar navbar-expand-lg navbar-light bg-light\"> <div class=\"container-fluid\"> <a class=\"navbar-brand\" href=\"/\">FAKE NEWS PREDICTION</a> <button class=\"navbar-toggler\" type=\"button\" data-bs-toggle=\"collapse\" data-bs-target=\"#navbarNavAltMarkup\" aria-controls=\"navbarNavAltMarkup\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> <span class=\"navbar-toggler-icon\"></span> </button> <div class=\"nav navbar-nav navbar-right\" id=\"navbarNavAltMarkup\"> <div class=\"navbar-nav\"> <a class=\"nav-link\" target=\"_blank\" href=\"https://rapidapi.com/fangyiyu/api/fake-news-detection1/\">API</a> <a class=\"nav-link\" target=\"_blank\" href=\"https://medium.com/@fangyiyu/how-to-build-a-fake-news-detection-web-app-using-flask-c0cfd1d9c2d4?sk=2a752b0d87c759672664232b33543667/\">Blog</a> <a class=\"nav-link\" target=\"_blank\" href=\"https://github.com/fangyiyu/Fake_News_Detection_Flask/blob/main/Fake_news_detection.ipynb\">NoteBook</a> <a class=\"nav-link\" target=\"_blank\" href=\"https://github.com/fangyiyu/Fake_News_Detection_Flask\">Code Source</a> </div> </div> </div> </nav><br> <p style=text-align:center>A fake news prediction web application using Machine Learning algorithms, deployed using Django and Heroku. </p> <p style=text-align:center>Enter your text to try it.</p> <br> <div class='container'> <form action=\"/\" method=\"POST\"> <div class=\"col-three-forth text-center col-md-offset-2\"> <div class=\"form-group\"> <textarea class=\"form-control jTextarea mt-3\" id=\"jTextarea'\" rows=\"5\" name=\"text\" placeholder=\"Write your text here...\" required>{{text}}</textarea><br><br> <button class=\"btn btn-primary btn-outline btn-md\" type=\"submit\" name=\"predict\">Predict</button> </div> </div> </form> </div> <br> {% if result %} <p style=\"text-align:center\"><strong>Prediction : {{result}}</strong></p> {% endif %}<script> function growTextarea (i,elem) { var elem = $(elem); var resizeTextarea = function( elem ) { var scrollLeft = window.pageXOffset || (document.documentElement || document.body.parentNode || document.body).scrollLeft; var scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop; elem.css('height', 'auto').css('height', elem.prop('scrollHeight') ); window.scrollTo(scrollLeft, scrollTop); }; elem.on('input', function() { resizeTextarea( $(this) ); }); resizeTextarea( $(elem) ); } $('.jTextarea').each(growTextarea);</script></body></html>" }, { "code": null, "e": 13761, "s": 13714, "text": "The above script creates a web page like this:" }, { "code": null, "e": 13836, "s": 13761, "text": "Now you can run your app by typing the following command in your terminal:" }, { "code": null, "e": 13851, "s": 13836, "text": "python3 app.py" }, { "code": null, "e": 13922, "s": 13851, "text": "You will be able to run your app locally and have a test on the model." }, { "code": null, "e": 14286, "s": 13922, "text": "In this tutorial, you built a machine learning model to detect fake news from real ones from scratch and saved the model to build a web application using Flask. The web application is running in your local machine, and you can try to make it public using cloud services such as Heroku, AWS or DigitalOcean. I have deployed mine on Heroku. Feel free to have a try." } ]
Write a power (pow) function using C++
The power function is used to find the power given two numbers that are the base and exponent. The result is the base raised to the power of the exponent. An example that demonstrates this is as follows − Base = 2 Exponent = 5 2^5 = 32 Hence, 2 raised to the power 5 is 32. A program that demonstrates the power function in C++ is given as follows − Live Demo #include using namespace std; int main(){ int x, y, ans = 1; cout << "Enter the base value: \n"; cin >> x; cout << "Enter the exponent value: \n"; cin >> y; for(int i=0; i<y; i++) ans *= x; cout << x <<" raised to the power "<< y <<" is "<&;lt;ans; return 0; } The output of the above program is as follows − Enter the base value: 3 Enter the exponent value: 4 3 raised to the power 4 is 81 Now let us understand the above program. The values of base and exponent are obtained from the user. The code snippet that shows this is as follows − cout << "Enter the base value: \n"; cin >> x; cout << "Enter the exponent value: \n"; cin >> y; The power is calculated using the for loop that runs till the value of the exponent. In each pass, the base value is multiplied with ans. After the completion of the for loop, the final value of power is stored in the variable ans. The code snippet that shows this is as follows − for(int i=0; i<y; i++) ans *= x; Finally, the value of the power is displayed. The code snippet that shows this is as follows − cout << x <<" raised to the power "<< y <<" is "<<ans;
[ { "code": null, "e": 1217, "s": 1062, "text": "The power function is used to find the power given two numbers that are the base and exponent. The result is the base raised to the power of the exponent." }, { "code": null, "e": 1267, "s": 1217, "text": "An example that demonstrates this is as follows −" }, { "code": null, "e": 1338, "s": 1267, "text": "Base = 2\nExponent = 5\n\n2^5 = 32\n\nHence, 2 raised to the power 5 is 32." }, { "code": null, "e": 1414, "s": 1338, "text": "A program that demonstrates the power function in C++ is given as follows −" }, { "code": null, "e": 1425, "s": 1414, "text": " Live Demo" }, { "code": null, "e": 1719, "s": 1425, "text": "#include\nusing namespace std;\n\nint main(){\n int x, y, ans = 1;\n\n cout << \"Enter the base value: \\n\";\n cin >> x;\n\n cout << \"Enter the exponent value: \\n\";\n cin >> y;\n\n for(int i=0; i<y; i++)\n ans *= x;\n\n cout << x <<\" raised to the power \"<< y <<\" is \"<&;lt;ans;\n\n return 0;\n}" }, { "code": null, "e": 1767, "s": 1719, "text": "The output of the above program is as follows −" }, { "code": null, "e": 1849, "s": 1767, "text": "Enter the base value: 3\nEnter the exponent value: 4\n3 raised to the power 4 is 81" }, { "code": null, "e": 1890, "s": 1849, "text": "Now let us understand the above program." }, { "code": null, "e": 1999, "s": 1890, "text": "The values of base and exponent are obtained from the user. The code snippet that shows this is as follows −" }, { "code": null, "e": 2096, "s": 1999, "text": "cout << \"Enter the base value: \\n\";\ncin >> x;\n\ncout << \"Enter the exponent value: \\n\";\ncin >> y;" }, { "code": null, "e": 2377, "s": 2096, "text": "The power is calculated using the for loop that runs till the value of the exponent. In each pass, the base value is multiplied with ans. After the completion of the for loop, the final value of power is stored in the variable ans. The code snippet that shows this is as follows −" }, { "code": null, "e": 2410, "s": 2377, "text": "for(int i=0; i<y; i++)\nans *= x;" }, { "code": null, "e": 2505, "s": 2410, "text": "Finally, the value of the power is displayed. The code snippet that shows this is as follows −" }, { "code": null, "e": 2560, "s": 2505, "text": "cout << x <<\" raised to the power \"<< y <<\" is \"<<ans;" } ]
jsoup - Working with URLs
Following example will showcase methods which can provide relative as well as absolute URLs present in the html page. String url = "http://www.tutorialspoint.com/"; Document document = Jsoup.connect(url).get(); Element link = document.select("a").first(); System.out.println("Relative Link: " + link.attr("href")); System.out.println("Absolute Link: " + link.attr("abs:href")); System.out.println("Absolute Link: " + link.absUrl("href")); Where document − document object represents the HTML DOM. document − document object represents the HTML DOM. Jsoup − main class to connect to a url and get the html content. Jsoup − main class to connect to a url and get the html content. link − Element object represent the html node element representing anchor tag. link − Element object represent the html node element representing anchor tag. link.attr("href") − provides the value of href present in anchor tag. It may be relative or absolute. link.attr("href") − provides the value of href present in anchor tag. It may be relative or absolute. link.attr("abs:href") − provides the absolute url after resolving against the document's base URI. link.attr("abs:href") − provides the absolute url after resolving against the document's base URI. link.absUrl("href") − provides the absolute url after resolving against the document's base URI. link.absUrl("href") − provides the absolute url after resolving against the document's base URI. Element object represent a dom elment and provides methods to get relative as well as absolute URLs present in the html page. Create the following java program using any editor of your choice in say C:/> jsoup. JsoupTester.java import java.io.IOException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; public class JsoupTester { public static void main(String[] args) throws IOException { String url = "http://www.tutorialspoint.com/"; Document document = Jsoup.connect(url).get(); Element link = document.select("a").first(); System.out.println("Relative Link: " + link.attr("href")); System.out.println("Absolute Link: " + link.attr("abs:href")); System.out.println("Absolute Link: " + link.absUrl("href")); } } Compile the class using javac compiler as follows: C:\jsoup>javac JsoupTester.java Now run the JsoupTester to see the result. C:\jsoup>java JsoupTester See the result. Relative Link: index.htm Absolute Link: https://www.tutorialspoint.com/index.htm Absolute Link: https://www.tutorialspoint.com/index.htm Print Add Notes Bookmark this page
[ { "code": null, "e": 2148, "s": 2030, "text": "Following example will showcase methods which can provide relative as well as absolute URLs present in the html page." }, { "code": null, "e": 2480, "s": 2148, "text": "String url = \"http://www.tutorialspoint.com/\";\nDocument document = Jsoup.connect(url).get();\nElement link = document.select(\"a\").first(); \n\nSystem.out.println(\"Relative Link: \" + link.attr(\"href\"));\nSystem.out.println(\"Absolute Link: \" + link.attr(\"abs:href\"));\nSystem.out.println(\"Absolute Link: \" + link.absUrl(\"href\"));\n" }, { "code": null, "e": 2486, "s": 2480, "text": "Where" }, { "code": null, "e": 2538, "s": 2486, "text": "document − document object represents the HTML DOM." }, { "code": null, "e": 2590, "s": 2538, "text": "document − document object represents the HTML DOM." }, { "code": null, "e": 2655, "s": 2590, "text": "Jsoup − main class to connect to a url and get the html content." }, { "code": null, "e": 2720, "s": 2655, "text": "Jsoup − main class to connect to a url and get the html content." }, { "code": null, "e": 2799, "s": 2720, "text": "link − Element object represent the html node element representing anchor tag." }, { "code": null, "e": 2878, "s": 2799, "text": "link − Element object represent the html node element representing anchor tag." }, { "code": null, "e": 2980, "s": 2878, "text": "link.attr(\"href\") − provides the value of href present in anchor tag. It may be relative or absolute." }, { "code": null, "e": 3082, "s": 2980, "text": "link.attr(\"href\") − provides the value of href present in anchor tag. It may be relative or absolute." }, { "code": null, "e": 3181, "s": 3082, "text": "link.attr(\"abs:href\") − provides the absolute url after resolving against the document's base URI." }, { "code": null, "e": 3280, "s": 3181, "text": "link.attr(\"abs:href\") − provides the absolute url after resolving against the document's base URI." }, { "code": null, "e": 3377, "s": 3280, "text": "link.absUrl(\"href\") − provides the absolute url after resolving against the document's base URI." }, { "code": null, "e": 3474, "s": 3377, "text": "link.absUrl(\"href\") − provides the absolute url after resolving against the document's base URI." }, { "code": null, "e": 3600, "s": 3474, "text": "Element object represent a dom elment and provides methods to get relative as well as absolute URLs present in the html page." }, { "code": null, "e": 3685, "s": 3600, "text": "Create the following java program using any editor of your choice in say C:/> jsoup." }, { "code": null, "e": 3702, "s": 3685, "text": "JsoupTester.java" }, { "code": null, "e": 4280, "s": 3702, "text": "import java.io.IOException;\n\nimport org.jsoup.Jsoup;\nimport org.jsoup.nodes.Document;\nimport org.jsoup.nodes.Element;\n\npublic class JsoupTester {\n public static void main(String[] args) throws IOException {\n \n String url = \"http://www.tutorialspoint.com/\";\n Document document = Jsoup.connect(url).get();\n\n Element link = document.select(\"a\").first();\n System.out.println(\"Relative Link: \" + link.attr(\"href\"));\n System.out.println(\"Absolute Link: \" + link.attr(\"abs:href\"));\n System.out.println(\"Absolute Link: \" + link.absUrl(\"href\"));\n }\n}" }, { "code": null, "e": 4331, "s": 4280, "text": "Compile the class using javac compiler as follows:" }, { "code": null, "e": 4364, "s": 4331, "text": "C:\\jsoup>javac JsoupTester.java\n" }, { "code": null, "e": 4407, "s": 4364, "text": "Now run the JsoupTester to see the result." }, { "code": null, "e": 4434, "s": 4407, "text": "C:\\jsoup>java JsoupTester\n" }, { "code": null, "e": 4450, "s": 4434, "text": "See the result." }, { "code": null, "e": 4588, "s": 4450, "text": "Relative Link: index.htm\nAbsolute Link: https://www.tutorialspoint.com/index.htm\nAbsolute Link: https://www.tutorialspoint.com/index.htm\n" }, { "code": null, "e": 4595, "s": 4588, "text": " Print" }, { "code": null, "e": 4606, "s": 4595, "text": " Add Notes" } ]
HTML | <textarea> name Attribute - GeeksforGeeks
27 May, 2019 The HTML <textarea> name Attribute is used to specify a name of the <Textarea> Element. It is used to reference the form-data after submitting the form or to reference the element in a JavaScript. Syntax: <Textarea name="text"> Attribute Values: It contains the value i.e name which specify the name for the <Textarea> element. Example: <!DOCTYPE html><html> <head> <title> HTML Textarea name Attribute </title></head> <body> <center> <h1 style="color: green;"> GeeksforGeeks </h1> <h2> HTML Textarea name Attribute </h2> <textarea id="GFG" name="GFG_text"> A computer science portal for geeks. </textarea> <br> </center></body> </html> Output: Supported Browsers: Google Chrome Firefox Edge Opera Apple Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments REST API (Introduction) Design a web page using HTML and CSS Form validation using jQuery How to place text on image using HTML and CSS? How to auto-resize an image to fit a div container using CSS? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript
[ { "code": null, "e": 24503, "s": 24475, "text": "\n27 May, 2019" }, { "code": null, "e": 24700, "s": 24503, "text": "The HTML <textarea> name Attribute is used to specify a name of the <Textarea> Element. It is used to reference the form-data after submitting the form or to reference the element in a JavaScript." }, { "code": null, "e": 24708, "s": 24700, "text": "Syntax:" }, { "code": null, "e": 24732, "s": 24708, "text": "<Textarea name=\"text\"> " }, { "code": null, "e": 24832, "s": 24732, "text": "Attribute Values: It contains the value i.e name which specify the name for the <Textarea> element." }, { "code": null, "e": 24841, "s": 24832, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML Textarea name Attribute </title></head> <body> <center> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h2> HTML Textarea name Attribute </h2> <textarea id=\"GFG\" name=\"GFG_text\"> A computer science portal for geeks. </textarea> <br> </center></body> </html>", "e": 25227, "s": 24841, "text": null }, { "code": null, "e": 25235, "s": 25227, "text": "Output:" }, { "code": null, "e": 25255, "s": 25235, "text": "Supported Browsers:" }, { "code": null, "e": 25269, "s": 25255, "text": "Google Chrome" }, { "code": null, "e": 25277, "s": 25269, "text": "Firefox" }, { "code": null, "e": 25282, "s": 25277, "text": "Edge" }, { "code": null, "e": 25288, "s": 25282, "text": "Opera" }, { "code": null, "e": 25301, "s": 25288, "text": "Apple Safari" }, { "code": null, "e": 25438, "s": 25301, "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": 25454, "s": 25438, "text": "HTML-Attributes" }, { "code": null, "e": 25459, "s": 25454, "text": "HTML" }, { "code": null, "e": 25476, "s": 25459, "text": "Web Technologies" }, { "code": null, "e": 25481, "s": 25476, "text": "HTML" }, { "code": null, "e": 25579, "s": 25481, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25588, "s": 25579, "text": "Comments" }, { "code": null, "e": 25601, "s": 25588, "text": "Old Comments" }, { "code": null, "e": 25625, "s": 25601, "text": "REST API (Introduction)" }, { "code": null, "e": 25662, "s": 25625, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 25691, "s": 25662, "text": "Form validation using jQuery" }, { "code": null, "e": 25738, "s": 25691, "text": "How to place text on image using HTML and CSS?" }, { "code": null, "e": 25800, "s": 25738, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 25856, "s": 25800, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 25889, "s": 25856, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 25932, "s": 25889, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 25993, "s": 25932, "text": "Difference between var, let and const keywords in JavaScript" } ]
Multilevel inheritance in Java
Multilevel inheritance - A class inherits properties from a class which again has inherits properties. Live Demo class Shape { public void display() { System.out.println("Inside display"); } } class Rectangle extends Shape { public void area() { System.out.println("Inside area"); } } class Cube extends Rectangle { public void volume() { System.out.println("Inside volume"); } } public class Tester { public static void main(String[] arguments) { Cube cube = new Cube(); cube.display(); cube.area(); cube.volume(); } } Inside display Inside area Inside volume
[ { "code": null, "e": 1165, "s": 1062, "text": "Multilevel inheritance - A class inherits properties from a class which again has inherits properties." }, { "code": null, "e": 1176, "s": 1165, "text": " Live Demo" }, { "code": null, "e": 1649, "s": 1176, "text": "class Shape {\n public void display() {\n System.out.println(\"Inside display\");\n }\n}\nclass Rectangle extends Shape {\n public void area() {\n System.out.println(\"Inside area\");\n }\n}\nclass Cube extends Rectangle {\n public void volume() {\n System.out.println(\"Inside volume\");\n }\n}\npublic class Tester {\n public static void main(String[] arguments) {\n Cube cube = new Cube();\n cube.display();\n cube.area();\n cube.volume();\n }\n}" }, { "code": null, "e": 1690, "s": 1649, "text": "Inside display\nInside area\nInside volume" } ]
Difference between PX, EM and Percent
The px unit defines a measurement in screen pixels. The following is an example − div { padding: 40px; } The em unit is a relative measurement for the height of a font in em spaces. Because an em unit is equivalent to the size of a given font, if you assign a font to 12pt, each "em" unit would be 12pt; thus, 2em would be 24pt. The following is an example − p { letter-spacing: 4em; } The % unit defines a measurement as a percentage relative to another value, typically an enclosing element. p { font-size: 14pt; line-height: 80%; }
[ { "code": null, "e": 1144, "s": 1062, "text": "The px unit defines a measurement in screen pixels. The following is an example −" }, { "code": null, "e": 1170, "s": 1144, "text": "div {\n padding: 40px;\n}" }, { "code": null, "e": 1394, "s": 1170, "text": "The em unit is a relative measurement for the height of a font in em spaces. Because an em unit is equivalent to the size of a given font, if you assign a font to 12pt, each \"em\" unit would be 12pt; thus, 2em would be 24pt." }, { "code": null, "e": 1424, "s": 1394, "text": "The following is an example −" }, { "code": null, "e": 1454, "s": 1424, "text": "p {\n letter-spacing: 4em;\n}" }, { "code": null, "e": 1562, "s": 1454, "text": "The % unit defines a measurement as a percentage relative to another value, typically an enclosing element." }, { "code": null, "e": 1609, "s": 1562, "text": "p {\n font-size: 14pt;\n line-height: 80%;\n}" } ]
Apriori Algorithm Tutorial. Data mining and association rules over... | by François St-Amant | Towards Data Science
The main goal of association rules is to identify relations between products or variables in a dataset. The idea is to determine which products often come together. It is widely used in market basket analysis for instance, where the analyst, starting from a database containing all transactions, will try to determine which products come together, with what frequency, etc. This information can be useful to optimize location of various products in a store or in planning for sales when a certain product goes on discount. Apriori algorithm is the most popular algorithm for mining association rules. It finds the most frequent combinations in a database and identifies association rules between the items, based on 3 important factors: Support: the probability that X and Y come togetherConfidence: the conditional probability of Y knowing x. In other words, how often does Y happen when X happened first.Lift: the ratio between support and confidence. A lift of 2 means that the likelihood of buying X and Y together is 2 times more than the likelihood of just buying Y. Support: the probability that X and Y come together Confidence: the conditional probability of Y knowing x. In other words, how often does Y happen when X happened first. Lift: the ratio between support and confidence. A lift of 2 means that the likelihood of buying X and Y together is 2 times more than the likelihood of just buying Y. In practice, a lift of at least 1 is necessary for a rule to be considered relevant. Here is the implementation of the apriori algorithm using the mlxtend library. First, let’s import the library and look at the data, which comes from transactions from a restaurant. from mlxtend.frequent_patterns import apriori, association_rulesdf.head(15) This dataset contains more than 30,000 rows and about 9,000 transactions. For every transaction (which can span over multiple rows), what matters to us are the products that were included in the transaction. The first thing we have to do is change the structure of the data, so that every transaction becomes a single row. We will use the unstack function on the product name, so that every possible product in the database becomes a column. tl = df.unstack(level='productName').fillna(0) Then, for every transaction, we want to know if a product is there (1) or not (0). We don’t care about the quantity of a product, only about it’s presence or not in the transaction. #Function def presence(x): if(x<= 0): return 0 if(x>= 1): return 1#Apply function tl_encoded = tl.applymap(presence) We can then build the model with the apriori function and collect all the inferred rules that meet the minimum support of 0.01, using the association_rules function. # Building the model frq_items = apriori(tl_encoded, min_support = 0.01, use_colnames = True) # Collecting the inferred rules in a dataframe rules = association_rules(frq_items, metric ="lift", min_threshold = 1) This code will return frozensets like this: [frozenset({'crpes sucre', 'Jus d'orange,'})] I personally find it much more convenient to work with lists. Here is the code to make the conversion and create a dataframe containing all the association rules that the apriori algorithm created. #Sort the rules rules = rules.sort_values(['lift'], ascending =[False])#From Frozenset to stringrules["antecedents"] = rules["antecedents"].apply(lambda x: list(x)[0]).astype("unicode")rules["consequents"] = rules["consequents"].apply(lambda x: list(x)[0]).astype("unicode")#Table with most relevant rulesprint(rules.sort_values('lift', ascending=False).nlargest(10, 'lift')) Let’s interpret the first rule. It says that when crepes with sugar are in a transaction, orange juice often comes too. The lift of 3.22 means that the likelihood of buying crepes and orange juice together is 3.22 times more than the likelihood of just buying orange juice. The support of 0.01 means that they appear in transactions together in about 1% of all transactions. This information could be useful in creating new offers for customer. For instance, we could have a buy a crepe, get an orange juice 50% off deal. Thanks a lot for reading!
[ { "code": null, "e": 546, "s": 172, "text": "The main goal of association rules is to identify relations between products or variables in a dataset. The idea is to determine which products often come together. It is widely used in market basket analysis for instance, where the analyst, starting from a database containing all transactions, will try to determine which products come together, with what frequency, etc." }, { "code": null, "e": 695, "s": 546, "text": "This information can be useful to optimize location of various products in a store or in planning for sales when a certain product goes on discount." }, { "code": null, "e": 909, "s": 695, "text": "Apriori algorithm is the most popular algorithm for mining association rules. It finds the most frequent combinations in a database and identifies association rules between the items, based on 3 important factors:" }, { "code": null, "e": 1245, "s": 909, "text": "Support: the probability that X and Y come togetherConfidence: the conditional probability of Y knowing x. In other words, how often does Y happen when X happened first.Lift: the ratio between support and confidence. A lift of 2 means that the likelihood of buying X and Y together is 2 times more than the likelihood of just buying Y." }, { "code": null, "e": 1297, "s": 1245, "text": "Support: the probability that X and Y come together" }, { "code": null, "e": 1416, "s": 1297, "text": "Confidence: the conditional probability of Y knowing x. In other words, how often does Y happen when X happened first." }, { "code": null, "e": 1583, "s": 1416, "text": "Lift: the ratio between support and confidence. A lift of 2 means that the likelihood of buying X and Y together is 2 times more than the likelihood of just buying Y." }, { "code": null, "e": 1668, "s": 1583, "text": "In practice, a lift of at least 1 is necessary for a rule to be considered relevant." }, { "code": null, "e": 1850, "s": 1668, "text": "Here is the implementation of the apriori algorithm using the mlxtend library. First, let’s import the library and look at the data, which comes from transactions from a restaurant." }, { "code": null, "e": 1926, "s": 1850, "text": "from mlxtend.frequent_patterns import apriori, association_rulesdf.head(15)" }, { "code": null, "e": 2134, "s": 1926, "text": "This dataset contains more than 30,000 rows and about 9,000 transactions. For every transaction (which can span over multiple rows), what matters to us are the products that were included in the transaction." }, { "code": null, "e": 2368, "s": 2134, "text": "The first thing we have to do is change the structure of the data, so that every transaction becomes a single row. We will use the unstack function on the product name, so that every possible product in the database becomes a column." }, { "code": null, "e": 2415, "s": 2368, "text": "tl = df.unstack(level='productName').fillna(0)" }, { "code": null, "e": 2597, "s": 2415, "text": "Then, for every transaction, we want to know if a product is there (1) or not (0). We don’t care about the quantity of a product, only about it’s presence or not in the transaction." }, { "code": null, "e": 2737, "s": 2597, "text": "#Function def presence(x): if(x<= 0): return 0 if(x>= 1): return 1#Apply function tl_encoded = tl.applymap(presence)" }, { "code": null, "e": 2903, "s": 2737, "text": "We can then build the model with the apriori function and collect all the inferred rules that meet the minimum support of 0.01, using the association_rules function." }, { "code": null, "e": 3119, "s": 2903, "text": "# Building the model frq_items = apriori(tl_encoded, min_support = 0.01, use_colnames = True) # Collecting the inferred rules in a dataframe rules = association_rules(frq_items, metric =\"lift\", min_threshold = 1) " }, { "code": null, "e": 3163, "s": 3119, "text": "This code will return frozensets like this:" }, { "code": null, "e": 3209, "s": 3163, "text": "[frozenset({'crpes sucre', 'Jus d'orange,'})]" }, { "code": null, "e": 3407, "s": 3209, "text": "I personally find it much more convenient to work with lists. Here is the code to make the conversion and create a dataframe containing all the association rules that the apriori algorithm created." }, { "code": null, "e": 3783, "s": 3407, "text": "#Sort the rules rules = rules.sort_values(['lift'], ascending =[False])#From Frozenset to stringrules[\"antecedents\"] = rules[\"antecedents\"].apply(lambda x: list(x)[0]).astype(\"unicode\")rules[\"consequents\"] = rules[\"consequents\"].apply(lambda x: list(x)[0]).astype(\"unicode\")#Table with most relevant rulesprint(rules.sort_values('lift', ascending=False).nlargest(10, 'lift'))" }, { "code": null, "e": 4158, "s": 3783, "text": "Let’s interpret the first rule. It says that when crepes with sugar are in a transaction, orange juice often comes too. The lift of 3.22 means that the likelihood of buying crepes and orange juice together is 3.22 times more than the likelihood of just buying orange juice. The support of 0.01 means that they appear in transactions together in about 1% of all transactions." }, { "code": null, "e": 4305, "s": 4158, "text": "This information could be useful in creating new offers for customer. For instance, we could have a buy a crepe, get an orange juice 50% off deal." } ]
Linux Admin - Backup and Recovery
Before exploring methods particular to CentOS for deploying a standard backup plan, let's first discuss typical considerations for a standard level backup policy. The first thing we want to get accustomed to is the 3-2-1 backup rule. Throughout the industry, you'll often hear the term 3-2-1 backup model. This is a very good approach to live by when implementing a backup plan. 3-2-1 is defined as follows: 3 copies of data; for example, we may have the working copy; a copy put onto the CentOS server designed for redundancy using rsync; and rotated, offsite USB backups are made from data on the backup server. 2 different backup mediums. We would actually have three different backup mediums in this case: the working copy on an SSD of a laptop or workstation, the CentOS server data on a RADI6 Array, and the offsite backups put on USB drives. 1 copy of data offsite; we are rotating the USB drives offsite on a nightly basis. Another modern approach may be a cloud backup provider. A bare metal restore plan is simply a plan laid out by a CentOS administrator to get vital systems online with all data intact. Assuming 100% systems failure and loss of all past system hardware, an administrator must have a plan to achieve uptime with intact user-data costing minimal downtime. The monolithic kernel used in Linux actually makes bare metal restores using system images much easier than Windows. Where Windows uses a micro-kernel architecture. A full data restore and bare metal recovery are usually accomplished through a combination of methods including working, configured production disk-images of key operational servers, redundant backups of user data abiding by the 3-2-1 rule. Even some sensitive files that may be stored in a secure, fireproof safe with limited access to the trusted company personnel. A multiphase bare metal restore and data recovery plan using native CentOS tools may consist of − dd to make and restore production disk-images of configured servers dd to make and restore production disk-images of configured servers rsync to make incremental backups of all user data rsync to make incremental backups of all user data tar & gzip to store encrypted backups of files with passwords and notes from administrators. Commonly, this can be put on a USB drive, encrypted and locked in a safe that a Senior Manager access. Also, this ensures someone else will know vital security credentials if the current administrator wins the lottery and disappears to a sunny island somewhere. tar & gzip to store encrypted backups of files with passwords and notes from administrators. Commonly, this can be put on a USB drive, encrypted and locked in a safe that a Senior Manager access. Also, this ensures someone else will know vital security credentials if the current administrator wins the lottery and disappears to a sunny island somewhere. If a system crashes due to a hardware failure or disaster, following will be the different phases of restoring operations − Build a working server with a configured bare metal image Build a working server with a configured bare metal image Restore data to the working server from backups Restore data to the working server from backups Have physical access to credentials needed to perform the first two operations Have physical access to credentials needed to perform the first two operations rsync is a great utility for syncing directories of files either locally or to another server. rsync has been used for years by System Administrators, hence it is very refined for the purpose of backing up data. In the author's opinion, one of the best features of sync is its ability to be scripted from the command line. In this tutorial, we will discuss rsync in various ways − Explore and talk about some common options Create local backups Create remote backups over SSH Restore local backups rsync is named for its purpose: Remote Sync and is both powerful and flexible in use. Following is a basic rsync remote backup over ssh − MiNi:~ rdc$ rsync -aAvz --progress ./Desktop/ImportantStuff/ rdc@192.168.1.143:home/rdc/ Documents/RemoteStuff/ rdc@192.168.1.143's password: sending incremental file list 6,148 100% 0.00kB/s 0:00:00 (xfr#1, to-chk=23/25) 2017-02-14 16_26_47-002 - Veeam_Architecture001.png 33,144 100% 31.61MB/s 0:00:00 (xfr#2, to-chk=22/25) A Guide to the WordPress REST API | Toptal.pdf 892,406 100% 25.03MB/s 0:00:00 (xfr#3, to-chk=21/25) Rick Cardon Technologies, LLC..webloc 77 100% 2.21kB/s 0:00:00 (xfr#4, to-chk=20/25) backbox-4.5.1-i386.iso 43,188,224 1% 4.26MB/s 0:08:29 sent 2,318,683,608 bytes received 446 bytes 7,302,941.90 bytes/sec total size is 2,327,091,863 speedup is 1.00 MiNi:~ rdc$ The following sync sent nearly 2.3GB of data across our LAN. The beauty of rsync is it works incrementally at the block level on a file-by-file basis. This means, if we change just two characters in a 1MB text file, only one or two blocks will be transferred across the lan on the next sync! Furthermore, the incremental function can be disabled in favor of more network bandwidth used for less CPU utilization. This might prove advisable if constantly copying several 10MB database files every 10 minutes on a 1Gb dedicated Backup-Lan. The reasoning is: these will always be changing and will be transmitting incrementally every 10 minutes and may tax load of the remote CPU. Since the total transfer load will not exceed 5 minutes, we may just wish to sync the database files in their entirety. Following are the most common switches with rsync − rsync syntax: rsync [options] [local path] [[remote host:remote path] or [target path My personal preference for rsync is when backing up files from a source host to a target host. For example, all the home directories for data recovery or even offsite and into the cloud for disaster recovery. We have already seen how to transfer files from one host to another. The same method can be used to sync directories and files locally. Let's make a manual incremental backup of /etc/ in our root user's directory. First, we need to create a directory off ~/root for the synced backup − [root@localhost rdc]# mkdir /root/etc_baks Then, assure there is enough free disk-space. [root@localhost rdc]# du -h --summarize /etc/ 49M /etc/ [root@localhost rdc]# df -h Filesystem Size Used Avail Use% Mounted on /dev/mapper/cl-root 43G 15G 28G 35% / We are good for syncing our entire /etc/ directory − rsync -aAvr /etc/ /root/etc_baks/ Our synced /etc/ directory − [root@localhost etc_baks]# ls -l ./ total 1436 drwxr-xr-x. 3 root root 101 Feb 1 19:40 abrt -rw-r--r--. 1 root root 16 Feb 1 19:51 adjtime -rw-r--r--. 1 root root 1518 Jun 7 2013 aliases -rw-r--r--. 1 root root 12288 Feb 27 19:06 aliases.db drwxr-xr-x. 2 root root 51 Feb 1 19:41 alsa drwxr-xr-x. 2 root root 4096 Feb 27 17:11 alternatives -rw-------. 1 root root 541 Mar 31 2016 anacrontab -rw-r--r--. 1 root root 55 Nov 4 12:29 asound.conf -rw-r--r--. 1 root root 1 Nov 5 14:16 at.deny drwxr-xr-x. 2 root root 32 Feb 1 19:40 at-spi2 --{ condensed output }-- Now let's do an incremental rsync − [root@localhost etc_baks]# rsync -aAvr --progress /etc/ /root/etc_baks/ sending incremental file list test_incremental.txt 0 100% 0.00kB/s 0:00:00 (xfer#1, to-check=1145/1282) sent 204620 bytes received 2321 bytes 413882.00 bytes/sec total size is 80245040 speedup is 387.77 [root@localhost etc_baks]# Only our test_incremental.txt file was copied. Let's do our initial rsync full backup onto a server with a backup plan deployed. This example is actually backing up a folder on a Mac OS X Workstation to a CentOS server. Another great aspect of rsync is that it can be used on any platform rsync has been ported to. MiNi:~ rdc$ rsync -aAvz Desktop/ImportanStuff/ rdc@192.168.1.143:Documents/RemoteStuff rdc@192.168.1.143's password: sending incremental file list ./ A Guide to the WordPress REST API | Toptal.pdf Rick Cardon Tech LLC.webloc VeeamDiagram.png backbox-4.5.1-i386.iso dhcp_admin_script_update.py DDWRT/ DDWRT/.DS_Store DDWRT/ddwrt-linksys-wrt1200acv2-webflash.bin DDWRT/ddwrt_mod_notes.docx DDWRT/factory-to-ddwrt.bin open_ldap_config_notes/ open_ldap_config_notes/ldap_directory_a.png open_ldap_config_notes/open_ldap_notes.txt perl_scripts/ perl_scripts/mysnmp.pl php_scripts/ php_scripts/chunked.php php_scripts/gettingURL.php sent 2,318,281,023 bytes received 336 bytes 9,720,257.27 bytes/sec total size is 2,326,636,892 speedup is 1.00 MiNi:~ rdc$ We have now backed up a folder from a workstation onto a server running a RAID6 volume with rotated disaster recovery media stored offsite. Using rsync has given us standard 3-2-1 backup with only one server having an expensive redundant disk array and rotated differential backups. Now let's do another backup of the same folder using rsync after a single new file named test_file.txt has been added. MiNi:~ rdc$ rsync -aAvz Desktop/ImportanStuff/ rdc@192.168.1.143:Documents/RemoteStuff rdc@192.168.1.143's password: sending incremental file list ./ test_file.txt sent 814 bytes received 61 bytes 134.62 bytes/sec total size is 2,326,636,910 speedup is 2,659,013.61 MiNi:~ rdc$ As you can see, only the new file was delivered to the server via rsync. The differential comparison was made on a file-by-file basis. A few things to note are: This only copies the new file: test_file.txt, since it was the only file with changes. rsync uses ssh. We did not ever need to use our root account on either machine. Simple, powerful and effective, rsync is great for backing up entire folders and directory structures. However, rsync by itself doesn't automate the process. This is where we need to dig into our toolbox and find the best, small, and simple tool for the job. To automate rsync backups with cronjobs, it is essential that SSH users be set up using SSH keys for authentication. This combined with cronjobs enables rsync to be done automatically at timed intervals. DD is a Linux utility that has been around since the dawn of the Linux kernel meeting the GNU Utilities. dd in simplest terms copies an image of a selected disk area. Then provides the ability to copy selected blocks of a physical disk. So unless you have backups, once dd writes over a disk, all blocks are replaced. Loss of previous data exceeds the recovery capabilities for even highly priced professional-level data-recovery. The entire process for making a bootable system image with dd is as follows − Boot from the CentOS server with a bootable linux distribution Find the designation of the bootable disk to be imaged Decide location where the recovery image will be stored Find the block size used on your disk Start the dd image operation In this tutorial, for the sake of time and simplicity, we will be creating an ISO image of the master-boot record from a CentOS virtual machine. We will then store this image offsite. In case our MBR becomes corrupted and needs to be restored, the same process can be applied to an entire bootable disk or partition. However, the time and disk space needed really goes a little overboard for this tutorial. It is encouraged for CentOS admins to become proficient in restoring a fully bootable disk/partition in a test environment and perform a bare metal restore. This will take a lot of pressure off when eventually one needs to complete the practice in a real life situation with Managers and a few dozen end-users counting downtime. In such a case, 10 minutes of figuring things out can seem like an eternity and make one sweat. Note − When using dd make sure to NOT confuse source and target volumes. You can destroy data and bootable servers by copying your backup location to a boot drive. Or possibly worse destroy data forever by copying over data at a very low level with DD. Following are the common command line switches and parameters for dd − Note on block size − The default block size for dd is 512 bytes. This was the standard block size of lower density hard disk drives. Today's higher density HDDs have increased to 4096 byte (4kB) block sizes to allow for disks ranging from 1TB and larger. Thus, we will want to check disk block size before using dd with newer, higher capacity hard disks. For this tutorial, instead of working on a production server with dd, we will be using a CentOS installation running in VMWare. We will also configure VMWare to boot a bootable Linux ISO image instead of working with a bootable USB Stick. First, we will need to download the CentOS image entitled: CentOS Gnome ISO. This is almost 3GB and it is advised to always keep a copy for creating bootable USB thumb-drives and booting into virtual server installations for trouble-shooting and bare metal images. Other bootable Linux distros will work just as well. Linux Mint can be used for bootable ISOs as it has great hardware support and polished GUI disk tools for maintenance. CentOS GNOME Live bootable image can be downloaded from: http://buildlogs.centos.org/rolling/7/isos/x86_64/CentOS-7-x86_64-LiveGNOME.iso Let's configure our VMWare Workstation installation to boot from our Linux bootable image. The steps are for VMWare on OS X. However, they are similar across VMWare Workstation on Linux, Windows, and even Virtual Box. Note − Using a virtual desktop solution like Virtual Box or VMWare Workstation is a great way to set up lab scenarios for learning CentOS Administration tasks. It provides the ability to install several CentOS installations, practically no hardware configuration letting the person focus on administration, and even save the server state before making changes. First let's configure a virtual cd-rom and attach our ISO image to boot instead of the virtual CentOS server installation − Now, set the startup disk − Now when booted, our virtual machine will boot from the CentOS bootable ISO image and allow access to files on the Virtual CentOS server that was previously configured. Let’s check our disks to see where we want to copy the MBR from (condensed output is as follows). MiNt ~ # fdisk -l Disk /dev/sda: 60 GiB, 21474836480 bytes, 41943040 sectors Units: sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disk /dev/sdb: 20 GiB, 21474836480 bytes, 41943040 sectors Units: sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes We have located both our physical disks: sda and sdb. Each has a block size of 512 bytes. So, we will now run the dd command to copy the first 512 bytes for our MBR on SDA1. The best way to do this is − [root@mint rdc]# dd if=/dev/sda bs=512 count=1 | gzip -c > /mnt/sdb/images/mbr.iso.gz 1+0 records in 1+0 records out 512 bytes copied, 0.000171388 s, 3.0 MB/s [root@mint rdc]# ls /mnt/sdb/ mbr-iso.gz [root@mint rdc]# Just like that, we have full image of out master boot record. If we have enough room to image the boot drive, we could just as easily make a full system boot image − dd if=/dev/INPUT/DEVICE-NAME-HERE conv=sync,noerror bs=4K | gzip -c > /mnt/sdb/boot-server-centos-image.iso.gz The conv=sync is used when bytes must be aligned for a physical medium. In this case, dd may get an error if exact 4K alignments are not read (say... a file that is only 3K but needs to take minimum of a single 4K block on disk. Or, there is simply an error reading and the file cannot be read by dd.). Thus, dd with conv=sync,noerror will pad the 3K with trivial, but useful data to physical medium in 4K block alignments. While not presenting an error that may end a large operation. When working with data from disks we always want to include: conv=sync,noerror parameter. This is simply because the disks are not streams like TCP data. They are made up of blocks aligned to a certain size. For example, if we have 512 byte blocks, a file of only 300 bytes still needs a full 512 bytes of disk-space (possibly 2 blocks for inode information like permissions and other filesystem information). gzip and tar are two utilities a CentOS administrator must become accustomed to using. They are used for a lot more than to simply decompress archives. Tar is an archiving utility similar to winrar on Windows. Its name Tape Archive abbreviated as tar pretty much sums up the utility. tar will take files and place them into an archive for logical convenience. Hence, instead of the dozens of files stored in /etc. we could just "tar" them up into an archive for backup and storage convenience. tar has been the standard for storing archived files on Unix and Linux for many years. Hence, using tar along with gzip or bzip is considered as a best practice for archives on each system. Following is a list of common command line switches and options used with tar − Following is the basic syntax for creating a tar archive. tar -cvf [tar archive name] Note on Compression mechanisms with tar − It is advised to stick with one of two common compression schemes when using tar: gzip and bzip2. gzip files consume less CPU resources but are usually larger in size. While bzip2 will take longer to compress, they utilize more CPU resources; but will result in a smaller end filesize. When using file compression, we will always want to use standard file extensions letting everyone including ourselves know (versus guess by trial and error) what compression scheme is needed to extract archives. When needing to possibly extract archives on a Windows box or for use on Windows, it is advised to use the .tar.tbz or .tar.gz as most the three character single extensions will confuse Windows and Windows only Administrators (however, that is sometimes the desired outcome) Let's create a gzipped tar archive from our remote backups copied from the Mac Workstation − [rdc@mint Documents]$ tar -cvz -f RemoteStuff.tgz ./RemoteStuff/ ./RemoteStuff/ ./RemoteStuff/.DS_Store ./RemoteStuff/DDWRT/ ./RemoteStuff/DDWRT/.DS_Store ./RemoteStuff/DDWRT/ddwrt-linksys-wrt1200acv2-webflash.bin ./RemoteStuff/DDWRT/ddwrt_mod_notes.docx ./RemoteStuff/DDWRT/factory-to-ddwrt.bin ./RemoteStuff/open_ldap_config_notes/ ./RemoteStuff/open_ldap_config_notes/ldap_directory_a.png ./RemoteStuff/open_ldap_config_notes/open_ldap_notes.txt ./RemoteStuff/perl_scripts/ ./RemoteStuff/perl_scripts/mysnmp.pl ./RemoteStuff/php_scripts/ ./RemoteStuff/php_scripts/chunked.php ./RemoteStuff/php_scripts/gettingURL.php ./RemoteStuff/A Guide to the WordPress REST API | Toptal.pdf ./RemoteStuff/Rick Cardon Tech LLC.webloc ./RemoteStuff/VeeamDiagram.png ./RemoteStuff/backbox-4.5.1-i386.iso ./RemoteStuff/dhcp_admin_script_update.py ./RemoteStuff/test_file.txt [rdc@mint Documents]$ ls -ld RemoteStuff.tgz -rw-rw-r--. 1 rdc rdc 2317140451 Mar 12 06:10 RemoteStuff.tgz Note − Instead of adding all the files directly to the archive, we archived the entire folder RemoteStuff. This is the easiest method. Simply because when extracted, the entire directory RemoteStuff is extracted with all the files inside the current working directory as ./currentWorkingDirectory/RemoteStuff/ Now let's extract the archive inside the /root/ home directory. [root@centos ~]# tar -zxvf RemoteStuff.tgz ./RemoteStuff/ ./RemoteStuff/.DS_Store ./RemoteStuff/DDWRT/ ./RemoteStuff/DDWRT/.DS_Store ./RemoteStuff/DDWRT/ddwrt-linksys-wrt1200acv2-webflash.bin ./RemoteStuff/DDWRT/ddwrt_mod_notes.docx ./RemoteStuff/DDWRT/factory-to-ddwrt.bin ./RemoteStuff/open_ldap_config_notes/ ./RemoteStuff/open_ldap_config_notes/ldap_directory_a.png ./RemoteStuff/open_ldap_config_notes/open_ldap_notes.txt ./RemoteStuff/perl_scripts/ ./RemoteStuff/perl_scripts/mysnmp.pl ./RemoteStuff/php_scripts/ ./RemoteStuff/php_scripts/chunked.php ./RemoteStuff/php_scripts/gettingURL.php ./RemoteStuff/A Guide to the WordPress REST API | Toptal.pdf ./RemoteStuff/Rick Cardon Tech LLC.webloc ./RemoteStuff/VeeamDiagram.png ./RemoteStuff/backbox-4.5.1-i386.iso ./RemoteStuff/dhcp_admin_script_update.py ./RemoteStuff/test_file.txt [root@mint ~]# ping www.google.com As seen above, all the files were simply extracted into the containing directory within our current working directory. [root@centos ~]# ls -l total 2262872 -rw-------. 1 root root 1752 Feb 1 19:52 anaconda-ks.cfg drwxr-xr-x. 137 root root 8192 Mar 9 04:42 etc_baks -rw-r--r--. 1 root root 1800 Feb 2 03:14 initial-setup-ks.cfg drwxr-xr-x. 6 rdc rdc 4096 Mar 10 22:20 RemoteStuff -rw-r--r--. 1 root root 2317140451 Mar 12 07:12 RemoteStuff.tgz -rw-r--r--. 1 root root 9446 Feb 25 05:09 ssl.conf [root@centos ~]# As noted earlier, we can use either bzip2 or gzip from tar with the -j or -z command line switches. We can also use gzip to compress individual files. However, using bzip or gzip alone does not offer as many features as when combined with tar. When using gzip, the default action is to remove the original files, replacing each with a compressed version adding the .gz extension. Some common command line switches for gzip are − gzip more or less works on a file-by-file basis and not on an archive basis like some Windows O/S zip utilities. The main reason for this is that tar already provides advanced archiving features. gzip is designed to provide only a compression mechanism. Hence, when thinking of gzip, think of a single file. When thinking of multiple files, think of tar archives. Let's now explore this with our previous tar archive. Note − Seasoned Linux professionals will often refer to a tarred archive as a tarball. Let's make another tar archive from our rsync backup. [root@centos Documents]# tar -cvf RemoteStuff.tar ./RemoteStuff/ [root@centos Documents]# ls RemoteStuff.tar RemoteStuff/ For demonstration purposes, let's gzip the newly created tarball, and tell gzip to keep the old file. By default, without the -c option, gzip will replace the entire tar archive with a .gz file. [root@centos Documents]# gzip -c RemoteStuff.tar > RemoteStuff.tar.gz [root@centos Documents]# ls RemoteStuff RemoteStuff.tar RemoteStuff.tar.gz We now have our original directory, our tarred directory and finally our gziped tarball. Let's try to test the -l switch with gzip. [root@centos Documents]# gzip -l RemoteStuff.tar.gz compressed uncompressed ratio uncompressed_name 2317140467 2326661120 0.4% RemoteStuff.tar [root@centos Documents]# To demonstrate how gzip differs from Windows Zip Utilities, let's run gzip on a folder of text files. [root@centos Documents]# ls text_files/ file1.txt file2.txt file3.txt file4.txt file5.txt [root@centos Documents]# Now let's use the -r option to recursively compress all the text files in the directory. [root@centos Documents]# gzip -9 -r text_files/ [root@centos Documents]# ls ./text_files/ file1.txt.gz file2.txt.gz file3.txt.gz file4.txt.gz file5.txt.gz [root@centos Documents]# See? Not what some may have anticipated. All the original text files were removed and each was compressed individually. Because of this behavior, it is best to think of gzip alone when needing to work in single files. Working with tarballs, let's extract our rsynced tarball into a new directory. [root@centos Documents]# tar -C /tmp -zxvf RemoteStuff.tar.gz ./RemoteStuff/ ./RemoteStuff/.DS_Store ./RemoteStuff/DDWRT/ ./RemoteStuff/DDWRT/.DS_Store ./RemoteStuff/DDWRT/ddwrt-linksys-wrt1200acv2-webflash.bin ./RemoteStuff/DDWRT/ddwrt_mod_notes.docx ./RemoteStuff/DDWRT/factory-to-ddwrt.bin ./RemoteStuff/open_ldap_config_notes/ ./RemoteStuff/open_ldap_config_notes/ldap_directory_a.png ./RemoteStuff/open_ldap_config_notes/open_ldap_notes.txt ./RemoteStuff/perl_scripts/ ./RemoteStuff/perl_scripts/mysnmp.pl ./RemoteStuff/php_scripts/ ./RemoteStuff/php_scripts/chunked.php As seen above, we extracted and decompressed our tarball into the /tmp directory. [root@centos Documents]# ls /tmp hsperfdata_root RemoteStuff Encrypting tarball archives for storing secure documents that may need to be accessed by other employees of the organization, in case of disaster recovery, can be a tricky concept. There are basically three ways to do this: either use GnuPG, or use openssl, or use a third part utility. GnuPG is primarily designed for asymmetric encryption and has an identity-association in mind rather than a passphrase. True, it can be used with symmetrical encryption, but this is not the main strength of GnuPG. Thus, I would discount GnuPG for storing archives with physical security when more people than the original person may need access (like maybe a corporate manager who wants to protect against an Administrator holding all the keys to the kingdom as leverage). Openssl like GnuPG can do what we want and ships with CentOS. But again, is not specifically designed to do what we want and encryption has been questioned in the security community. Our choice is a utility called 7zip. 7zip is a compression utility like gzip but with many more features. Like Gnu Gzip, 7zip and its standards are in the open-source community. We just need to install 7zip from our EHEL Repository (the next chapter will cover installing the Extended Enterprise Repositories in detail). 7zip is a simple install once our EHEL repositories have been loaded and configured in CentOS. [root@centos Documents]# yum -y install p7zip.x86_64 p7zip-plugins.x86_64 Loaded plugins: fastestmirror, langpacks base | 3.6 kB 00:00:00 epel/x86_64/metalink | 13 kB 00:00:00 epel | 4.3 kB 00:00:00 extras | 3.4 kB 00:00:00 updates | 3.4 kB 00:00:00 (1/2): epel/x86_64/updateinfo | 756 kB 00:00:04 (2/2): epel/x86_64/primary_db | 4.6 MB 00:00:18 Loading mirror speeds from cached hostfile --> Running transaction check ---> Package p7zip.x86_64 0:16.02-2.el7 will be installed ---> Package p7zip-plugins.x86_64 0:16.02-2.el7 will be installed --> Finished Dependency Resolution Dependencies Resolved Simple as that, 7zip is installed and ready be used with 256-bit AES encryption for our tarball archives. Now let's use 7z to encrypt our gzipped archive with a password. The syntax for doing so is pretty simple − 7z a -p <output filename><input filename> Where, a: add to archive, and -p: encrypt and prompt for passphrase [root@centos Documents]# 7z a -p RemoteStuff.tgz.7z RemoteStuff.tar.gz 7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21 p7zip Version 16.02 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,64 bits,1 CPU Intel(R) Core(TM) i5-4278U CPU @ 2.60GHz (40651),ASM,AES-NI) Scanning the drive: 1 file, 2317140467 bytes (2210 MiB) Creating archive: RemoteStuff.tgz.7z Items to compress: 1 Enter password (will not be echoed): Verify password (will not be echoed) : Files read from disk: 1 Archive size: 2280453410 bytes (2175 MiB) Everything is Ok [root@centos Documents]# ls RemoteStuff RemoteStuff.tar RemoteStuff.tar.gz RemoteStuff.tgz.7z slapD text_files [root@centos Documents]# Now, we have our .7z archive that encrypts the gzipped tarball with 256-bit AES. Note − 7zip uses AES 256-bit encryption with an SHA-256 hash of the password and counter, repeated up to 512K times for key derivation. This should be secure enough if a complex key is used. The process of encrypting and recompressing the archive further can take some time with larger archives. 7zip is an advanced offering with more features than gzip or bzip2. However, it is not as standard with CentOS or amongst the Linux world. Thus, the other utilities should be used often as possible. 57 Lectures 7.5 hours Mamta Tripathi 25 Lectures 3 hours Lets Kode It 14 Lectures 1.5 hours Abhilash Nelson 58 Lectures 2.5 hours Frahaan Hussain 129 Lectures 23 hours Eduonix Learning Solutions 23 Lectures 5 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2491, "s": 2257, "text": "Before exploring methods particular to CentOS for deploying a standard backup plan, let's first discuss typical considerations for a standard level backup policy. The first thing we want to get accustomed to is the 3-2-1 backup rule." }, { "code": null, "e": 3245, "s": 2491, "text": "Throughout the industry, you'll often hear the term 3-2-1 backup model. This is a very good approach to live by when implementing a backup plan. 3-2-1 is defined as follows: 3 copies of data; for example, we may have the working copy; a copy put onto the CentOS server designed for redundancy using rsync; and rotated, offsite USB backups are made from data on the backup server. 2 different backup mediums. We would actually have three different backup mediums in this case: the working copy on an SSD of a laptop or workstation, the CentOS server data on a RADI6 Array, and the offsite backups put on USB drives. 1 copy of data offsite; we are rotating the USB drives offsite on a nightly basis. Another modern approach may be a cloud backup provider." }, { "code": null, "e": 3707, "s": 3245, "text": "A bare metal restore plan is simply a plan laid out by a CentOS administrator to get vital systems online with all data intact. Assuming 100% systems failure and loss of all past system hardware, an administrator must have a plan to achieve uptime with intact user-data costing minimal downtime. The monolithic kernel used in Linux actually makes bare metal restores using system images much easier than Windows. Where Windows uses a micro-kernel architecture." }, { "code": null, "e": 4075, "s": 3707, "text": "A full data restore and bare metal recovery are usually accomplished through a combination of methods including working, configured production disk-images of key operational servers, redundant backups of user data abiding by the 3-2-1 rule. Even some sensitive files that may be stored in a secure, fireproof safe with limited access to the trusted company personnel." }, { "code": null, "e": 4173, "s": 4075, "text": "A multiphase bare metal restore and data recovery plan using native CentOS tools may consist of −" }, { "code": null, "e": 4241, "s": 4173, "text": "dd to make and restore production disk-images of configured servers" }, { "code": null, "e": 4309, "s": 4241, "text": "dd to make and restore production disk-images of configured servers" }, { "code": null, "e": 4360, "s": 4309, "text": "rsync to make incremental backups of all user data" }, { "code": null, "e": 4411, "s": 4360, "text": "rsync to make incremental backups of all user data" }, { "code": null, "e": 4766, "s": 4411, "text": "tar & gzip to store encrypted backups of files with passwords and notes from administrators. Commonly, this can be put on a USB drive, encrypted and locked in a safe that a Senior Manager access. Also, this ensures someone else will know vital security credentials if the current administrator wins the lottery and disappears to a sunny island somewhere." }, { "code": null, "e": 5121, "s": 4766, "text": "tar & gzip to store encrypted backups of files with passwords and notes from administrators. Commonly, this can be put on a USB drive, encrypted and locked in a safe that a Senior Manager access. Also, this ensures someone else will know vital security credentials if the current administrator wins the lottery and disappears to a sunny island somewhere." }, { "code": null, "e": 5245, "s": 5121, "text": "If a system crashes due to a hardware failure or disaster, following will be the different phases of restoring operations −" }, { "code": null, "e": 5303, "s": 5245, "text": "Build a working server with a configured bare metal image" }, { "code": null, "e": 5361, "s": 5303, "text": "Build a working server with a configured bare metal image" }, { "code": null, "e": 5409, "s": 5361, "text": "Restore data to the working server from backups" }, { "code": null, "e": 5457, "s": 5409, "text": "Restore data to the working server from backups" }, { "code": null, "e": 5536, "s": 5457, "text": "Have physical access to credentials needed to perform the first two operations" }, { "code": null, "e": 5615, "s": 5536, "text": "Have physical access to credentials needed to perform the first two operations" }, { "code": null, "e": 5938, "s": 5615, "text": "rsync is a great utility for syncing directories of files either locally or to another server. rsync has been used for years by System Administrators, hence it is very refined for the purpose of backing up data. In the author's opinion, one of the best features of sync is its ability to be scripted from the command line." }, { "code": null, "e": 5996, "s": 5938, "text": "In this tutorial, we will discuss rsync in various ways −" }, { "code": null, "e": 6039, "s": 5996, "text": "Explore and talk about some common options" }, { "code": null, "e": 6060, "s": 6039, "text": "Create local backups" }, { "code": null, "e": 6091, "s": 6060, "text": "Create remote backups over SSH" }, { "code": null, "e": 6113, "s": 6091, "text": "Restore local backups" }, { "code": null, "e": 6199, "s": 6113, "text": "rsync is named for its purpose: Remote Sync and is both powerful and flexible in use." }, { "code": null, "e": 6251, "s": 6199, "text": "Following is a basic rsync remote backup over ssh −" }, { "code": null, "e": 6989, "s": 6251, "text": "MiNi:~ rdc$ rsync -aAvz --progress ./Desktop/ImportantStuff/ \nrdc@192.168.1.143:home/rdc/ Documents/RemoteStuff/\nrdc@192.168.1.143's password:\nsending incremental file list\n 6,148 100% 0.00kB/s 0:00:00 (xfr#1, to-chk=23/25)\n2017-02-14 16_26_47-002 - Veeam_Architecture001.png\n 33,144 100% 31.61MB/s 0:00:00 (xfr#2, to-chk=22/25)\nA Guide to the WordPress REST API | Toptal.pdf\n 892,406 100% 25.03MB/s 0:00:00 (xfr#3, to-chk=21/25)\nRick Cardon Technologies, LLC..webloc\n 77 100% 2.21kB/s 0:00:00 (xfr#4, to-chk=20/25)\nbackbox-4.5.1-i386.iso\n 43,188,224 1% 4.26MB/s 0:08:29\nsent 2,318,683,608 bytes received 446 bytes 7,302,941.90 bytes/sec\ntotal size is 2,327,091,863 speedup is 1.00\nMiNi:~ rdc$\n" }, { "code": null, "e": 7281, "s": 6989, "text": "The following sync sent nearly 2.3GB of data across our LAN. The beauty of rsync is it works incrementally at the block level on a file-by-file basis. This means, if we change just two characters in a 1MB text file, only one or two blocks will be transferred across the lan on the next sync!" }, { "code": null, "e": 7786, "s": 7281, "text": "Furthermore, the incremental function can be disabled in favor of more network bandwidth used for less CPU utilization. This might prove advisable if constantly copying several 10MB database files every 10 minutes on a 1Gb dedicated Backup-Lan. The reasoning is: these will always be changing and will be transmitting incrementally every 10 minutes and may tax load of the remote CPU. Since the total transfer load will not exceed 5 minutes, we may just wish to sync the database files in their entirety." }, { "code": null, "e": 7838, "s": 7786, "text": "Following are the most common switches with rsync −" }, { "code": null, "e": 7925, "s": 7838, "text": "rsync syntax:\nrsync [options] [local path] [[remote host:remote path] or [target path\n" }, { "code": null, "e": 8134, "s": 7925, "text": "My personal preference for rsync is when backing up files from a source host to a target host. For example, all the home directories for data recovery or even offsite and into the cloud for disaster recovery." }, { "code": null, "e": 8270, "s": 8134, "text": "We have already seen how to transfer files from one host to another. The same method can be used to sync directories and files locally." }, { "code": null, "e": 8348, "s": 8270, "text": "Let's make a manual incremental backup of /etc/ in our root user's directory." }, { "code": null, "e": 8420, "s": 8348, "text": "First, we need to create a directory off ~/root for the synced backup −" }, { "code": null, "e": 8464, "s": 8420, "text": "[root@localhost rdc]# mkdir /root/etc_baks\n" }, { "code": null, "e": 8510, "s": 8464, "text": "Then, assure there is enough free disk-space." }, { "code": null, "e": 8734, "s": 8510, "text": "[root@localhost rdc]# du -h --summarize /etc/ \n49M /etc/\n \n[root@localhost rdc]# df -h \nFilesystem Size Used Avail Use% Mounted on \n/dev/mapper/cl-root 43G 15G 28G 35% /\n" }, { "code": null, "e": 8787, "s": 8734, "text": "We are good for syncing our entire /etc/ directory −" }, { "code": null, "e": 8822, "s": 8787, "text": "rsync -aAvr /etc/ /root/etc_baks/\n" }, { "code": null, "e": 8851, "s": 8822, "text": "Our synced /etc/ directory −" }, { "code": null, "e": 9493, "s": 8851, "text": "[root@localhost etc_baks]# ls -l ./\ntotal 1436\ndrwxr-xr-x. 3 root root 101 Feb 1 19:40 abrt\n-rw-r--r--. 1 root root 16 Feb 1 19:51 adjtime\n-rw-r--r--. 1 root root 1518 Jun 7 2013 aliases\n-rw-r--r--. 1 root root 12288 Feb 27 19:06 aliases.db\ndrwxr-xr-x. 2 root root 51 Feb 1 19:41 alsa\ndrwxr-xr-x. 2 root root 4096 Feb 27 17:11 alternatives\n-rw-------. 1 root root 541 Mar 31 2016 anacrontab\n-rw-r--r--. 1 root root 55 Nov 4 12:29 asound.conf\n-rw-r--r--. 1 root root 1 Nov 5 14:16 at.deny\ndrwxr-xr-x. 2 root root 32 Feb 1 19:40 at-spi2\n--{ condensed output }--\n" }, { "code": null, "e": 9529, "s": 9493, "text": "Now let's do an incremental rsync −" }, { "code": null, "e": 9852, "s": 9529, "text": "[root@localhost etc_baks]# rsync -aAvr --progress /etc/ /root/etc_baks/\nsending incremental file list\n\ntest_incremental.txt \n 0 100% 0.00kB/s 0:00:00 (xfer#1, to-check=1145/1282)\n \nsent 204620 bytes received 2321 bytes 413882.00 bytes/sec\ntotal size is 80245040 speedup is 387.77\n\n[root@localhost etc_baks]#\n" }, { "code": null, "e": 9899, "s": 9852, "text": "Only our test_incremental.txt file was copied." }, { "code": null, "e": 10167, "s": 9899, "text": "Let's do our initial rsync full backup onto a server with a backup plan deployed. This example is actually backing up a folder on a Mac OS X Workstation to a CentOS server. Another great aspect of rsync is that it can be used on any platform rsync has been ported to." }, { "code": null, "e": 10921, "s": 10167, "text": "MiNi:~ rdc$ rsync -aAvz Desktop/ImportanStuff/\nrdc@192.168.1.143:Documents/RemoteStuff\nrdc@192.168.1.143's password:\nsending incremental file list\n./\nA Guide to the WordPress REST API | Toptal.pdf\nRick Cardon Tech LLC.webloc\nVeeamDiagram.png\nbackbox-4.5.1-i386.iso\ndhcp_admin_script_update.py\nDDWRT/\nDDWRT/.DS_Store\nDDWRT/ddwrt-linksys-wrt1200acv2-webflash.bin\nDDWRT/ddwrt_mod_notes.docx\nDDWRT/factory-to-ddwrt.bin\nopen_ldap_config_notes/\nopen_ldap_config_notes/ldap_directory_a.png\nopen_ldap_config_notes/open_ldap_notes.txt\nperl_scripts/\nperl_scripts/mysnmp.pl\nphp_scripts/\nphp_scripts/chunked.php\nphp_scripts/gettingURL.php\nsent 2,318,281,023 bytes received 336 bytes 9,720,257.27 bytes/sec\ntotal size is 2,326,636,892 speedup is 1.00\nMiNi:~ rdc$\n" }, { "code": null, "e": 11204, "s": 10921, "text": "We have now backed up a folder from a workstation onto a server running a RAID6 volume with rotated disaster recovery media stored offsite. Using rsync has given us standard 3-2-1 backup with only one server having an expensive redundant disk array and rotated differential backups." }, { "code": null, "e": 11323, "s": 11204, "text": "Now let's do another backup of the same folder using rsync after a single new file named test_file.txt has been added." }, { "code": null, "e": 11612, "s": 11323, "text": "MiNi:~ rdc$ rsync -aAvz Desktop/ImportanStuff/\nrdc@192.168.1.143:Documents/RemoteStuff \nrdc@192.168.1.143's password: \nsending incremental file list \n ./ \ntest_file.txt\n\nsent 814 bytes received 61 bytes 134.62 bytes/sec\ntotal size is 2,326,636,910 speedup is 2,659,013.61\nMiNi:~ rdc$\n" }, { "code": null, "e": 11747, "s": 11612, "text": "As you can see, only the new file was delivered to the server via rsync. The differential comparison was made on a file-by-file basis." }, { "code": null, "e": 11940, "s": 11747, "text": "A few things to note are: This only copies the new file: test_file.txt, since it was the only file with changes. rsync uses ssh. We did not ever need to use our root account on either machine." }, { "code": null, "e": 12199, "s": 11940, "text": "Simple, powerful and effective, rsync is great for backing up entire folders and directory structures. However, rsync by itself doesn't automate the process. This is where we need to dig into our toolbox and find the best, small, and simple tool for the job." }, { "code": null, "e": 12403, "s": 12199, "text": "To automate rsync backups with cronjobs, it is essential that SSH users be set up using SSH keys for authentication. This combined with cronjobs enables rsync to be done automatically at timed intervals." }, { "code": null, "e": 12508, "s": 12403, "text": "DD is a Linux utility that has been around since the dawn of the Linux kernel meeting the GNU Utilities." }, { "code": null, "e": 12834, "s": 12508, "text": "dd in simplest terms copies an image of a selected disk area. Then provides the ability to copy selected blocks of a physical disk. So unless you have backups, once dd writes over a disk, all blocks are replaced. Loss of previous data exceeds the recovery capabilities for even highly priced professional-level data-recovery." }, { "code": null, "e": 12912, "s": 12834, "text": "The entire process for making a bootable system image with dd is as follows −" }, { "code": null, "e": 12975, "s": 12912, "text": "Boot from the CentOS server with a bootable linux distribution" }, { "code": null, "e": 13030, "s": 12975, "text": "Find the designation of the bootable disk to be imaged" }, { "code": null, "e": 13086, "s": 13030, "text": "Decide location where the recovery image will be stored" }, { "code": null, "e": 13124, "s": 13086, "text": "Find the block size used on your disk" }, { "code": null, "e": 13153, "s": 13124, "text": "Start the dd image operation" }, { "code": null, "e": 13560, "s": 13153, "text": "In this tutorial, for the sake of time and simplicity, we will be creating an ISO image of the master-boot record from a CentOS virtual machine. We will then store this image offsite. In case our MBR becomes corrupted and needs to be restored, the same process can be applied to an entire bootable disk or partition. However, the time and disk space needed really goes a little overboard for this tutorial." }, { "code": null, "e": 13985, "s": 13560, "text": "It is encouraged for CentOS admins to become proficient in restoring a fully bootable disk/partition in a test environment and perform a bare metal restore. This will take a lot of pressure off when eventually one needs to complete the practice in a real life situation with Managers and a few dozen end-users counting downtime. In such a case, 10 minutes of figuring things out can seem like an eternity and make one sweat." }, { "code": null, "e": 14238, "s": 13985, "text": "Note − When using dd make sure to NOT confuse source and target volumes. You can destroy data and bootable servers by copying your backup location to a boot drive. Or possibly worse destroy data forever by copying over data at a very low level with DD." }, { "code": null, "e": 14309, "s": 14238, "text": "Following are the common command line switches and parameters for dd −" }, { "code": null, "e": 14664, "s": 14309, "text": "Note on block size − The default block size for dd is 512 bytes. This was the standard block size of lower density hard disk drives. Today's higher density HDDs have increased to 4096 byte (4kB) block sizes to allow for disks ranging from 1TB and larger. Thus, we will want to check disk block size before using dd with newer, higher capacity hard disks." }, { "code": null, "e": 14903, "s": 14664, "text": "For this tutorial, instead of working on a production server with dd, we will be using a CentOS installation running in VMWare. We will also configure VMWare to boot a bootable Linux ISO image instead of working with a bootable USB Stick." }, { "code": null, "e": 15168, "s": 14903, "text": "First, we will need to download the CentOS image entitled: CentOS Gnome ISO. This is almost 3GB and it is advised to always keep a copy for creating bootable USB thumb-drives and booting into virtual server installations for trouble-shooting and bare metal images." }, { "code": null, "e": 15340, "s": 15168, "text": "Other bootable Linux distros will work just as well. Linux Mint can be used for bootable ISOs as it has great hardware support and polished GUI disk tools for maintenance." }, { "code": null, "e": 15477, "s": 15340, "text": "CentOS GNOME Live bootable image can be downloaded from: http://buildlogs.centos.org/rolling/7/isos/x86_64/CentOS-7-x86_64-LiveGNOME.iso" }, { "code": null, "e": 15695, "s": 15477, "text": "Let's configure our VMWare Workstation installation to boot from our Linux bootable image. The steps are for VMWare on OS X. However, they are similar across VMWare Workstation on Linux, Windows, and even Virtual Box." }, { "code": null, "e": 16056, "s": 15695, "text": "Note − Using a virtual desktop solution like Virtual Box or VMWare Workstation is a great way to set up lab scenarios for learning CentOS Administration tasks. It provides the ability to install several CentOS installations, practically no hardware configuration letting the person focus on administration, and even save the server state before making changes." }, { "code": null, "e": 16180, "s": 16056, "text": "First let's configure a virtual cd-rom and attach our ISO image to boot instead of the virtual CentOS server installation −" }, { "code": null, "e": 16208, "s": 16180, "text": "Now, set the startup disk −" }, { "code": null, "e": 16377, "s": 16208, "text": "Now when booted, our virtual machine will boot from the CentOS bootable ISO image and allow access to files on the Virtual CentOS server that was previously configured." }, { "code": null, "e": 16475, "s": 16377, "text": "Let’s check our disks to see where we want to copy the MBR from (condensed output is as follows)." }, { "code": null, "e": 16897, "s": 16475, "text": "MiNt ~ # fdisk -l\nDisk /dev/sda: 60 GiB, 21474836480 bytes, 41943040 sectors\nUnits: sectors of 1 * 512 = 512 bytes\nSector size (logical/physical): 512 bytes / 512 bytes\nI/O size (minimum/optimal): 512 bytes / 512 bytes\n\nDisk /dev/sdb: 20 GiB, 21474836480 bytes, 41943040 sectors\nUnits: sectors of 1 * 512 = 512 bytes\nSector size (logical/physical): 512 bytes / 512 bytes\nI/O size (minimum/optimal): 512 bytes / 512 bytes\n" }, { "code": null, "e": 17071, "s": 16897, "text": "We have located both our physical disks: sda and sdb. Each has a block size of 512 bytes. So, we will now run the dd command to copy the first 512 bytes for our MBR on SDA1." }, { "code": null, "e": 17100, "s": 17071, "text": "The best way to do this is −" }, { "code": null, "e": 17331, "s": 17100, "text": "[root@mint rdc]# dd if=/dev/sda bs=512 count=1 | gzip -c >\n/mnt/sdb/images/mbr.iso.gz \n1+0 records in \n1+0 records out \n512 bytes copied, 0.000171388 s, 3.0 MB/s\n\n[root@mint rdc]# ls /mnt/sdb/ \n mbr-iso.gz\n \n[root@mint rdc]#\n" }, { "code": null, "e": 17497, "s": 17331, "text": "Just like that, we have full image of out master boot record. If we have enough room to image the boot drive, we could just as easily make a full system boot image −" }, { "code": null, "e": 17609, "s": 17497, "text": "dd if=/dev/INPUT/DEVICE-NAME-HERE conv=sync,noerror bs=4K | gzip -c >\n/mnt/sdb/boot-server-centos-image.iso.gz\n" }, { "code": null, "e": 18095, "s": 17609, "text": "The conv=sync is used when bytes must be aligned for a physical medium. In this case, dd may get an error if exact 4K alignments are not read (say... a file that is only 3K but needs to take minimum of a single 4K block on disk. Or, there is simply an error reading and the file cannot be read by dd.). Thus, dd with conv=sync,noerror will pad the 3K with trivial, but useful data to physical medium in 4K block alignments. While not presenting an error that may end a large operation." }, { "code": null, "e": 18185, "s": 18095, "text": "When working with data from disks we always want to include: conv=sync,noerror parameter." }, { "code": null, "e": 18505, "s": 18185, "text": "This is simply because the disks are not streams like TCP data. They are made up of blocks aligned to a certain size. For example, if we have 512 byte blocks, a file of only 300 bytes still needs a full 512 bytes of disk-space (possibly 2 blocks for inode information like permissions and other filesystem information)." }, { "code": null, "e": 18657, "s": 18505, "text": "gzip and tar are two utilities a CentOS administrator must become accustomed to using. They are used for a lot more than to simply decompress archives." }, { "code": null, "e": 18999, "s": 18657, "text": "Tar is an archiving utility similar to winrar on Windows. Its name Tape Archive abbreviated as tar pretty much sums up the utility. tar will take files and place them into an archive for logical convenience. Hence, instead of the dozens of files stored in /etc. we could just \"tar\" them up into an archive for backup and storage convenience." }, { "code": null, "e": 19189, "s": 18999, "text": "tar has been the standard for storing archived files on Unix and Linux for many years. Hence, using tar along with gzip or bzip is considered as a best practice for archives on each system." }, { "code": null, "e": 19269, "s": 19189, "text": "Following is a list of common command line switches and options used with tar −" }, { "code": null, "e": 19327, "s": 19269, "text": "Following is the basic syntax for creating a tar archive." }, { "code": null, "e": 19356, "s": 19327, "text": "tar -cvf [tar archive name]\n" }, { "code": null, "e": 19684, "s": 19356, "text": "Note on Compression mechanisms with tar − It is advised to stick with one of two common compression schemes when using tar: gzip and bzip2. gzip files consume less CPU resources but are usually larger in size. While bzip2 will take longer to compress, they utilize more CPU resources; but will result in a smaller end filesize." }, { "code": null, "e": 19896, "s": 19684, "text": "When using file compression, we will always want to use standard file extensions letting everyone including ourselves know (versus guess by trial and error) what compression scheme is needed to extract archives." }, { "code": null, "e": 20171, "s": 19896, "text": "When needing to possibly extract archives on a Windows box or for use on Windows, it is advised to use the .tar.tbz or .tar.gz as most the three character single extensions will confuse Windows and Windows only Administrators (however, that is sometimes the desired outcome)" }, { "code": null, "e": 20264, "s": 20171, "text": "Let's create a gzipped tar archive from our remote backups copied from the Mac Workstation −" }, { "code": null, "e": 21234, "s": 20264, "text": "[rdc@mint Documents]$ tar -cvz -f RemoteStuff.tgz ./RemoteStuff/ \n./RemoteStuff/\n./RemoteStuff/.DS_Store\n./RemoteStuff/DDWRT/\n./RemoteStuff/DDWRT/.DS_Store\n./RemoteStuff/DDWRT/ddwrt-linksys-wrt1200acv2-webflash.bin\n./RemoteStuff/DDWRT/ddwrt_mod_notes.docx\n./RemoteStuff/DDWRT/factory-to-ddwrt.bin\n./RemoteStuff/open_ldap_config_notes/\n./RemoteStuff/open_ldap_config_notes/ldap_directory_a.png\n./RemoteStuff/open_ldap_config_notes/open_ldap_notes.txt\n./RemoteStuff/perl_scripts/\n./RemoteStuff/perl_scripts/mysnmp.pl\n./RemoteStuff/php_scripts/\n./RemoteStuff/php_scripts/chunked.php\n./RemoteStuff/php_scripts/gettingURL.php\n./RemoteStuff/A Guide to the WordPress REST API | Toptal.pdf\n./RemoteStuff/Rick Cardon Tech LLC.webloc\n./RemoteStuff/VeeamDiagram.png\n./RemoteStuff/backbox-4.5.1-i386.iso\n./RemoteStuff/dhcp_admin_script_update.py\n./RemoteStuff/test_file.txt\n[rdc@mint Documents]$ ls -ld RemoteStuff.tgz\n-rw-rw-r--. 1 rdc rdc 2317140451 Mar 12 06:10 RemoteStuff.tgz\n" }, { "code": null, "e": 21544, "s": 21234, "text": "Note − Instead of adding all the files directly to the archive, we archived the entire folder RemoteStuff. This is the easiest method. Simply because when extracted, the entire directory RemoteStuff is extracted with all the files inside the current working directory as ./currentWorkingDirectory/RemoteStuff/" }, { "code": null, "e": 21608, "s": 21544, "text": "Now let's extract the archive inside the /root/ home directory." }, { "code": null, "e": 22483, "s": 21608, "text": "[root@centos ~]# tar -zxvf RemoteStuff.tgz\n./RemoteStuff/\n./RemoteStuff/.DS_Store\n./RemoteStuff/DDWRT/\n./RemoteStuff/DDWRT/.DS_Store\n./RemoteStuff/DDWRT/ddwrt-linksys-wrt1200acv2-webflash.bin\n./RemoteStuff/DDWRT/ddwrt_mod_notes.docx\n./RemoteStuff/DDWRT/factory-to-ddwrt.bin\n./RemoteStuff/open_ldap_config_notes/\n./RemoteStuff/open_ldap_config_notes/ldap_directory_a.png\n./RemoteStuff/open_ldap_config_notes/open_ldap_notes.txt\n./RemoteStuff/perl_scripts/\n./RemoteStuff/perl_scripts/mysnmp.pl\n./RemoteStuff/php_scripts/\n./RemoteStuff/php_scripts/chunked.php\n./RemoteStuff/php_scripts/gettingURL.php\n./RemoteStuff/A Guide to the WordPress REST API | Toptal.pdf\n./RemoteStuff/Rick Cardon Tech LLC.webloc\n./RemoteStuff/VeeamDiagram.png\n./RemoteStuff/backbox-4.5.1-i386.iso\n./RemoteStuff/dhcp_admin_script_update.py\n./RemoteStuff/test_file.txt\n[root@mint ~]# ping www.google.com\n" }, { "code": null, "e": 22602, "s": 22483, "text": "As seen above, all the files were simply extracted into the containing directory within our current working directory." }, { "code": null, "e": 23113, "s": 22602, "text": "[root@centos ~]# ls -l \ntotal 2262872 \n-rw-------. 1 root root 1752 Feb 1 19:52 anaconda-ks.cfg \ndrwxr-xr-x. 137 root root 8192 Mar 9 04:42 etc_baks \n-rw-r--r--. 1 root root 1800 Feb 2 03:14 initial-setup-ks.cfg \ndrwxr-xr-x. 6 rdc rdc 4096 Mar 10 22:20 RemoteStuff \n-rw-r--r--. 1 root root 2317140451 Mar 12 07:12 RemoteStuff.tgz \n-rw-r--r--. 1 root root 9446 Feb 25 05:09 ssl.conf [root@centos ~]#\n" }, { "code": null, "e": 23357, "s": 23113, "text": "As noted earlier, we can use either bzip2 or gzip from tar with the -j or -z command line switches. We can also use gzip to compress individual files. However, using bzip or gzip alone does not offer as many features as when combined with tar." }, { "code": null, "e": 23493, "s": 23357, "text": "When using gzip, the default action is to remove the original files, replacing each with a compressed version adding the .gz extension." }, { "code": null, "e": 23542, "s": 23493, "text": "Some common command line switches for gzip are −" }, { "code": null, "e": 23796, "s": 23542, "text": "gzip more or less works on a file-by-file basis and not on an archive basis like some Windows O/S zip utilities. The main reason for this is that tar already provides advanced archiving features. gzip is designed to provide only a compression mechanism." }, { "code": null, "e": 23960, "s": 23796, "text": "Hence, when thinking of gzip, think of a single file. When thinking of multiple files, think of tar archives. Let's now explore this with our previous tar archive." }, { "code": null, "e": 24047, "s": 23960, "text": "Note − Seasoned Linux professionals will often refer to a tarred archive as a tarball." }, { "code": null, "e": 24101, "s": 24047, "text": "Let's make another tar archive from our rsync backup." }, { "code": null, "e": 24224, "s": 24101, "text": "[root@centos Documents]# tar -cvf RemoteStuff.tar ./RemoteStuff/\n[root@centos Documents]# ls\nRemoteStuff.tar RemoteStuff/\n" }, { "code": null, "e": 24419, "s": 24224, "text": "For demonstration purposes, let's gzip the newly created tarball, and tell gzip to keep the old file. By default, without the -c option, gzip will replace the entire tar archive with a .gz file." }, { "code": null, "e": 24656, "s": 24419, "text": "[root@centos Documents]# gzip -c RemoteStuff.tar > RemoteStuff.tar.gz\n[root@centos Documents]# ls\nRemoteStuff RemoteStuff.tar RemoteStuff.tar.gz\nWe now have our original directory, our tarred directory and finally our gziped tarball.\n" }, { "code": null, "e": 24699, "s": 24656, "text": "Let's try to test the -l switch with gzip." }, { "code": null, "e": 24917, "s": 24699, "text": "[root@centos Documents]# gzip -l RemoteStuff.tar.gz \n compressed uncompressed ratio uncompressed_name \n 2317140467 2326661120 0.4% RemoteStuff.tar\n \n[root@centos Documents]#\n" }, { "code": null, "e": 25019, "s": 24917, "text": "To demonstrate how gzip differs from Windows Zip Utilities, let's run gzip on a folder of text files." }, { "code": null, "e": 25140, "s": 25019, "text": "[root@centos Documents]# ls text_files/\n file1.txt file2.txt file3.txt file4.txt file5.txt\n[root@centos Documents]#\n" }, { "code": null, "e": 25229, "s": 25140, "text": "Now let's use the -r option to recursively compress all the text files in the directory." }, { "code": null, "e": 25417, "s": 25229, "text": "[root@centos Documents]# gzip -9 -r text_files/\n\n[root@centos Documents]# ls ./text_files/\nfile1.txt.gz file2.txt.gz file3.txt.gz file4.txt.gz file5.txt.gz\n \n[root@centos Documents]#\n" }, { "code": null, "e": 25635, "s": 25417, "text": "See? Not what some may have anticipated. All the original text files were removed and each was compressed individually. Because of this behavior, it is best to think of gzip alone when needing to work in single files." }, { "code": null, "e": 25714, "s": 25635, "text": "Working with tarballs, let's extract our rsynced tarball into a new directory." }, { "code": null, "e": 26291, "s": 25714, "text": "[root@centos Documents]# tar -C /tmp -zxvf RemoteStuff.tar.gz\n./RemoteStuff/\n./RemoteStuff/.DS_Store\n./RemoteStuff/DDWRT/\n./RemoteStuff/DDWRT/.DS_Store\n./RemoteStuff/DDWRT/ddwrt-linksys-wrt1200acv2-webflash.bin\n./RemoteStuff/DDWRT/ddwrt_mod_notes.docx\n./RemoteStuff/DDWRT/factory-to-ddwrt.bin\n./RemoteStuff/open_ldap_config_notes/\n./RemoteStuff/open_ldap_config_notes/ldap_directory_a.png\n./RemoteStuff/open_ldap_config_notes/open_ldap_notes.txt\n./RemoteStuff/perl_scripts/\n./RemoteStuff/perl_scripts/mysnmp.pl\n./RemoteStuff/php_scripts/\n./RemoteStuff/php_scripts/chunked.php\n" }, { "code": null, "e": 26373, "s": 26291, "text": "As seen above, we extracted and decompressed our tarball into the /tmp directory." }, { "code": null, "e": 26436, "s": 26373, "text": "[root@centos Documents]# ls /tmp \nhsperfdata_root\nRemoteStuff\n" }, { "code": null, "e": 26723, "s": 26436, "text": "Encrypting tarball archives for storing secure documents that may need to be accessed by other employees of the organization, in case of disaster recovery, can be a tricky concept. There are basically three ways to do this: either use GnuPG, or use openssl, or use a third part utility." }, { "code": null, "e": 27196, "s": 26723, "text": "GnuPG is primarily designed for asymmetric encryption and has an identity-association in mind rather than a passphrase. True, it can be used with symmetrical encryption, but this is not the main strength of GnuPG. Thus, I would discount GnuPG for storing archives with physical security when more people than the original person may need access (like maybe a corporate manager who wants to protect against an Administrator holding all the keys to the kingdom as leverage)." }, { "code": null, "e": 27379, "s": 27196, "text": "Openssl like GnuPG can do what we want and ships with CentOS. But again, is not specifically designed to do what we want and encryption has been questioned in the security community." }, { "code": null, "e": 27700, "s": 27379, "text": "Our choice is a utility called 7zip. 7zip is a compression utility like gzip but with many more features. Like Gnu Gzip, 7zip and its standards are in the open-source community. We just need to install 7zip from our EHEL Repository (the next chapter will cover installing the Extended Enterprise Repositories in detail)." }, { "code": null, "e": 27795, "s": 27700, "text": "7zip is a simple install once our EHEL repositories have been loaded and configured in CentOS." }, { "code": null, "e": 28410, "s": 27795, "text": "[root@centos Documents]# yum -y install p7zip.x86_64 p7zip-plugins.x86_64\nLoaded plugins: fastestmirror, langpacks\nbase\n| 3.6 kB 00:00:00\nepel/x86_64/metalink\n| 13 kB 00:00:00\nepel\n| 4.3 kB 00:00:00\nextras\n| 3.4 kB 00:00:00\nupdates\n| 3.4 kB 00:00:00\n(1/2): epel/x86_64/updateinfo\n| 756 kB 00:00:04 \n(2/2):\nepel/x86_64/primary_db\n| 4.6 MB 00:00:18\nLoading mirror speeds from cached hostfile\n--> Running transaction check\n---> Package p7zip.x86_64 0:16.02-2.el7 will be installed\n---> Package p7zip-plugins.x86_64 0:16.02-2.el7 will be installed\n--> Finished Dependency Resolution\nDependencies Resolved\n" }, { "code": null, "e": 28516, "s": 28410, "text": "Simple as that, 7zip is installed and ready be used with 256-bit AES encryption for our tarball archives." }, { "code": null, "e": 28624, "s": 28516, "text": "Now let's use 7z to encrypt our gzipped archive with a password. The syntax for doing so is pretty simple −" }, { "code": null, "e": 28667, "s": 28624, "text": "7z a -p <output filename><input filename>\n" }, { "code": null, "e": 28735, "s": 28667, "text": "Where, a: add to archive, and -p: encrypt and prompt for passphrase" }, { "code": null, "e": 29431, "s": 28735, "text": "[root@centos Documents]# 7z a -p RemoteStuff.tgz.7z RemoteStuff.tar.gz\n\n7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21\np7zip Version 16.02 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,64 bits,1 CPU Intel(R)\nCore(TM) i5-4278U CPU @ 2.60GHz (40651),ASM,AES-NI)\nScanning the drive:\n1 file, 2317140467 bytes (2210 MiB)\n\nCreating archive: RemoteStuff.tgz.7z\n\nItems to compress: 1\n\nEnter password (will not be echoed):\nVerify password (will not be echoed) :\n\nFiles read from disk: 1\nArchive size: 2280453410 bytes (2175 MiB)\nEverything is Ok\n[root@centos Documents]# ls\nRemoteStuff RemoteStuff.tar RemoteStuff.tar.gz RemoteStuff.tgz.7z slapD\ntext_files\n\n[root@centos Documents]#\n" }, { "code": null, "e": 29512, "s": 29431, "text": "Now, we have our .7z archive that encrypts the gzipped tarball with 256-bit AES." }, { "code": null, "e": 29703, "s": 29512, "text": "Note − 7zip uses AES 256-bit encryption with an SHA-256 hash of the password and counter, repeated up to 512K times for key derivation. This should be secure enough if a complex key is used." }, { "code": null, "e": 29808, "s": 29703, "text": "The process of encrypting and recompressing the archive further can take some time with larger archives." }, { "code": null, "e": 30007, "s": 29808, "text": "7zip is an advanced offering with more features than gzip or bzip2. However, it is not as standard with CentOS or amongst the Linux world. Thus, the other utilities should be used often as possible." }, { "code": null, "e": 30042, "s": 30007, "text": "\n 57 Lectures \n 7.5 hours \n" }, { "code": null, "e": 30058, "s": 30042, "text": " Mamta Tripathi" }, { "code": null, "e": 30091, "s": 30058, "text": "\n 25 Lectures \n 3 hours \n" }, { "code": null, "e": 30105, "s": 30091, "text": " Lets Kode It" }, { "code": null, "e": 30140, "s": 30105, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 30157, "s": 30140, "text": " Abhilash Nelson" }, { "code": null, "e": 30192, "s": 30157, "text": "\n 58 Lectures \n 2.5 hours \n" }, { "code": null, "e": 30209, "s": 30192, "text": " Frahaan Hussain" }, { "code": null, "e": 30244, "s": 30209, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 30272, "s": 30244, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 30305, "s": 30272, "text": "\n 23 Lectures \n 5 hours \n" }, { "code": null, "e": 30345, "s": 30305, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 30352, "s": 30345, "text": " Print" }, { "code": null, "e": 30363, "s": 30352, "text": " Add Notes" } ]
Add new field to every document in a MongoDB collection?
To add new field to every document in a MongoDB collection, you can use $set operator. The syntax is as follows: db.yourCollectionName.update({}, { $set: {"yourFieldName": yourValue} }, false, true); To understand the above syntax, let us create a collection with some documents. The query to create a collection with documents is as follows: >db.addNewFieldToEveryDocument.insertOne({"StudentName":"John","StudentAddress":"US "}); { "acknowledged" : true, "insertedId" : ObjectId("5c6efc0b6fd07954a48906ae") } >db.addNewFieldToEveryDocument.insertOne({"StudentName":"David","StudentAddress":"U K"}); { "acknowledged" : true, "insertedId" : ObjectId("5c6efc0b6fd07954a48906af") } >db.addNewFieldToEveryDocument.insertOne({"StudentName":"Carol","StudentAddress":"U K"}); { "acknowledged" : true, "insertedId" : ObjectId("5c6efc0b6fd07954a48906b0") } >db.addNewFieldToEveryDocument.insertOne({"StudentName":"Bob","StudentAddress":"US" }); { "acknowledged" : true, "insertedId" : ObjectId("5c6efc0b6fd07954a48906b1") } Display all documents from a collection with the help of find() method. The query is as follows: > db.addNewFieldToEveryDocument.find().pretty(); The following is the output: { "_id" : ObjectId("5c6efc0b6fd07954a48906ae"), "StudentName" : "John", "StudentAddress" : "US" } { "_id" : ObjectId("5c6efc0b6fd07954a48906af"), "StudentName" : "David", "StudentAddress" : "UK" } { "_id" : ObjectId("5c6efc0b6fd07954a48906b0"), "StudentName" : "Carol", "StudentAddress" : "UK" } { "_id" : ObjectId("5c6efc0b6fd07954a48906b1"), "StudentName" : "Bob", "StudentAddress" : "US" } The following is the query to add a new field to every document: > db.addNewFieldToEveryDocument.update({}, { $set: {"StudentAge": 24} }, false, true); WriteResult({ "nMatched" : 4, "nUpserted" : 0, "nModified" : 4 }) Above, we have added a new field “StudentAge”:24 in every document. Let us check the field “StudentAge”:24 is successfully added to every document or not. The query is as follows: > db.addNewFieldToEveryDocument.find().pretty(); The following is the output: { "_id" : ObjectId("5c6efc0b6fd07954a48906ae"), "StudentName" : "John", "StudentAddress" : "US", "StudentAge" : 24 } { "_id" : ObjectId("5c6efc0b6fd07954a48906af"), "StudentName" : "David", "StudentAddress" : "UK", "StudentAge" : 24 } { "_id" : ObjectId("5c6efc0b6fd07954a48906b0"), "StudentName" : "Carol", "StudentAddress" : "UK", "StudentAge" : 24 } { "_id" : ObjectId("5c6efc0b6fd07954a48906b1"), "StudentName" : "Bob", "StudentAddress" : "US", "StudentAge" : 24 }
[ { "code": null, "e": 1175, "s": 1062, "text": "To add new field to every document in a MongoDB collection, you can use $set operator. The syntax is as follows:" }, { "code": null, "e": 1262, "s": 1175, "text": "db.yourCollectionName.update({}, { $set: {\"yourFieldName\": yourValue} }, false, true);" }, { "code": null, "e": 1405, "s": 1262, "text": "To understand the above syntax, let us create a collection with some documents. The query to create a collection with documents is as follows:" }, { "code": null, "e": 2102, "s": 1405, "text": ">db.addNewFieldToEveryDocument.insertOne({\"StudentName\":\"John\",\"StudentAddress\":\"US\n\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6efc0b6fd07954a48906ae\")\n}\n>db.addNewFieldToEveryDocument.insertOne({\"StudentName\":\"David\",\"StudentAddress\":\"U\nK\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6efc0b6fd07954a48906af\")\n}\n>db.addNewFieldToEveryDocument.insertOne({\"StudentName\":\"Carol\",\"StudentAddress\":\"U\nK\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6efc0b6fd07954a48906b0\")\n}\n>db.addNewFieldToEveryDocument.insertOne({\"StudentName\":\"Bob\",\"StudentAddress\":\"US\"\n});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6efc0b6fd07954a48906b1\")\n}" }, { "code": null, "e": 2199, "s": 2102, "text": "Display all documents from a collection with the help of find() method. The query is as follows:" }, { "code": null, "e": 2248, "s": 2199, "text": "> db.addNewFieldToEveryDocument.find().pretty();" }, { "code": null, "e": 2277, "s": 2248, "text": "The following is the output:" }, { "code": null, "e": 2706, "s": 2277, "text": "{\n \"_id\" : ObjectId(\"5c6efc0b6fd07954a48906ae\"),\n \"StudentName\" : \"John\",\n \"StudentAddress\" : \"US\"\n}\n{\n \"_id\" : ObjectId(\"5c6efc0b6fd07954a48906af\"),\n \"StudentName\" : \"David\",\n \"StudentAddress\" : \"UK\"\n}\n{\n \"_id\" : ObjectId(\"5c6efc0b6fd07954a48906b0\"),\n \"StudentName\" : \"Carol\",\n \"StudentAddress\" : \"UK\"\n}\n{\n \"_id\" : ObjectId(\"5c6efc0b6fd07954a48906b1\"),\n \"StudentName\" : \"Bob\",\n \"StudentAddress\" : \"US\"\n}" }, { "code": null, "e": 2771, "s": 2706, "text": "The following is the query to add a new field to every document:" }, { "code": null, "e": 2924, "s": 2771, "text": "> db.addNewFieldToEveryDocument.update({}, { $set: {\"StudentAge\": 24} }, false, true);\nWriteResult({ \"nMatched\" : 4, \"nUpserted\" : 0, \"nModified\" : 4 })" }, { "code": null, "e": 3104, "s": 2924, "text": "Above, we have added a new field “StudentAge”:24 in every document. Let us check the field “StudentAge”:24 is successfully added to every document or not. The query is as follows:" }, { "code": null, "e": 3153, "s": 3104, "text": "> db.addNewFieldToEveryDocument.find().pretty();" }, { "code": null, "e": 3182, "s": 3153, "text": "The following is the output:" }, { "code": null, "e": 3699, "s": 3182, "text": "{\n \"_id\" : ObjectId(\"5c6efc0b6fd07954a48906ae\"),\n \"StudentName\" : \"John\",\n \"StudentAddress\" : \"US\",\n \"StudentAge\" : 24\n}\n{\n \"_id\" : ObjectId(\"5c6efc0b6fd07954a48906af\"),\n \"StudentName\" : \"David\",\n \"StudentAddress\" : \"UK\",\n \"StudentAge\" : 24\n}\n{\n \"_id\" : ObjectId(\"5c6efc0b6fd07954a48906b0\"),\n \"StudentName\" : \"Carol\",\n \"StudentAddress\" : \"UK\",\n \"StudentAge\" : 24\n}\n{\n \"_id\" : ObjectId(\"5c6efc0b6fd07954a48906b1\"),\n \"StudentName\" : \"Bob\",\n \"StudentAddress\" : \"US\",\n \"StudentAge\" : 24\n}" } ]
Check if a large number is divisible by 9 or not - GeeksforGeeks
09 Apr, 2021 Given a number, the task is to find if the number is divisible by 9 or not. The input number may be large and it may not be possible to store even if we use long long int. Examples: Input : n = 69354 Output : Yes Input : n = 234567876799333 Output : No Input : n = 3635883959606670431112222 Output : No Since input number may be very large, we cannot use n % 9 to check if a number is divisible by 9 or not, especially in languages like C/C++. The idea is based on following fact. A number is divisible by 9 if sum of its digits is divisible by 9. Illustration: For example n = 9432 Sum of digits = 9 + 4 + 3 + 2 = 18 Since sum is divisible by 9, answer is Yes. How does this work? Let us consider 1332, we can write it as 1332 = 1*1000 + 3*100 + 3*10 + 2 The proof is based on below observation: Remainder of 10i divided by 9 is 1 So powers of 10 only results in remainder 1 when divided by 9. Remainder of "1*1000 + 3*100 + 3*10 + 2" divided by 9 can be written as : 1*1 + 3*1 + 3*1 + 2 = 9 The above expression is basically sum of all digits. Since 9 is divisible by 9, answer is yes. Below is the implementation of above idea. C++ Java Python3 C# PHP Javascript // C++ program to find if a number is divisible by// 9 or not#include<bits/stdc++.h>using namespace std; // Function to find that number divisible by 9 or notint check(string str){ // Compute sum of digits int n = str.length(); int digitSum = 0; for (int i=0; i<n; i++) digitSum += (str[i]-'0'); // Check if sum of digits is divisible by 9. return (digitSum % 9 == 0);} // Driver codeint main(){ string str = "99333"; check(str)? cout << "Yes" : cout << "No "; return 0;} // Java program to find if a number is// divisible by 9 or notclass IsDivisible{ // Function to find that number // is divisible by 9 or not static boolean check(String str) { // Compute sum of digits int n = str.length(); int digitSum = 0; for (int i=0; i<n; i++) digitSum += (str.charAt(i)-'0'); // Check if sum of digits is divisible by 9. return (digitSum % 9 == 0); } // main function public static void main (String[] args) { String str = "99333"; if(check(str)) System.out.println("Yes"); else System.out.println("No"); }} # Python 3 program to# find if a number is# divisible by# 9 or not # Function to find that# number divisible by 9# or notdef check(st) : # Compute sum of digits n = len(st) digitSum = 0 for i in range(0,n) : digitSum = digitSum + (int)(st[i]) # Check if sum of digits # is divisible by 9. return (digitSum % 9 == 0) # Driver codest = "99333" if(check(st)) : print("Yes")else : print("No") # This code is contributed by Nikita Tiwari. // C# program to find if a number is// divisible by 9 or not.using System; class GFG { // Function to find that number // is divisible by 9 or not static bool check(String str) { // Compute sum of digits int n = str.Length; int digitSum = 0; for (int i = 0; i < n; i++) digitSum += (str[i] - '0'); // Check if sum of digits is // divisible by 9. return (digitSum % 9 == 0); } // main function public static void Main () { String str = "99333"; if(check(str)) Console.Write("Yes"); else Console.Write("No"); }} // This code is Contributed by// nitin mittal. <?php// PHP program to find if a number// is divisible by 9 or not // Function to find that// number divisible by 9 or notfunction check($str){ // Compute sum of digits $n = strlen($str); $digitSum = 0; for ($i = 0; $i < $n; $i++) $digitSum += ($str[$i] - '0'); // Check if sum of digits // is divisible by 9. return ($digitSum % 9 == 0);} // Driver code$str = "99333";$x = check($str) ? "Yes" : "No ";echo($x); // This code is contributed by Ajit.?> <script> // Javascript program to find if a number// is divisible by 9 or not // Function to find that// number divisible by 9 or notfunction check(str){ // Compute sum of digits let n = str.length; let digitSum = 0; for(let i = 0; i < n; i++) digitSum += (str[i] - '0'); // Check if sum of digits // is divisible by 9. return (digitSum % 9 == 0);} // Driver codelet str = "99333";let x = check(str) ? "Yes" : "No "; document.write(x); // This code is contributed by _saurabh_jaiswal. </script> Output: Yes This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal jit_t ManasChhabra2 _saurabh_jaiswal divisibility large-numbers number-digits Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Sieve of Eratosthenes Print all possible combinations of r elements in a given array of size n Operators in C / C++ The Knight's tour problem | Backtracking-1 Program for factorial of a number Program for Decimal to Binary Conversion
[ { "code": null, "e": 26610, "s": 26582, "text": "\n09 Apr, 2021" }, { "code": null, "e": 26782, "s": 26610, "text": "Given a number, the task is to find if the number is divisible by 9 or not. The input number may be large and it may not be possible to store even if we use long long int." }, { "code": null, "e": 26793, "s": 26782, "text": "Examples: " }, { "code": null, "e": 26919, "s": 26793, "text": "Input : n = 69354\nOutput : Yes\n\nInput : n = 234567876799333\nOutput : No\n\nInput : n = 3635883959606670431112222\nOutput : No" }, { "code": null, "e": 27097, "s": 26919, "text": "Since input number may be very large, we cannot use n % 9 to check if a number is divisible by 9 or not, especially in languages like C/C++. The idea is based on following fact." }, { "code": null, "e": 27164, "s": 27097, "text": "A number is divisible by 9 if sum of its digits is divisible by 9." }, { "code": null, "e": 27180, "s": 27164, "text": "Illustration: " }, { "code": null, "e": 27293, "s": 27180, "text": "For example n = 9432\nSum of digits = 9 + 4 + 3 + 2\n = 18\nSince sum is divisible by 9,\nanswer is Yes." }, { "code": null, "e": 27315, "s": 27293, "text": "How does this work? " }, { "code": null, "e": 27726, "s": 27315, "text": "Let us consider 1332, we can write it as\n1332 = 1*1000 + 3*100 + 3*10 + 2\n\nThe proof is based on below observation:\nRemainder of 10i divided by 9 is 1\nSo powers of 10 only results in remainder 1 \nwhen divided by 9.\n\nRemainder of \"1*1000 + 3*100 + 3*10 + 2\"\ndivided by 9 can be written as : \n1*1 + 3*1 + 3*1 + 2 = 9\nThe above expression is basically sum of\nall digits.\n\nSince 9 is divisible by 9, answer is yes." }, { "code": null, "e": 27769, "s": 27726, "text": "Below is the implementation of above idea." }, { "code": null, "e": 27773, "s": 27769, "text": "C++" }, { "code": null, "e": 27778, "s": 27773, "text": "Java" }, { "code": null, "e": 27786, "s": 27778, "text": "Python3" }, { "code": null, "e": 27789, "s": 27786, "text": "C#" }, { "code": null, "e": 27793, "s": 27789, "text": "PHP" }, { "code": null, "e": 27804, "s": 27793, "text": "Javascript" }, { "code": "// C++ program to find if a number is divisible by// 9 or not#include<bits/stdc++.h>using namespace std; // Function to find that number divisible by 9 or notint check(string str){ // Compute sum of digits int n = str.length(); int digitSum = 0; for (int i=0; i<n; i++) digitSum += (str[i]-'0'); // Check if sum of digits is divisible by 9. return (digitSum % 9 == 0);} // Driver codeint main(){ string str = \"99333\"; check(str)? cout << \"Yes\" : cout << \"No \"; return 0;}", "e": 28312, "s": 27804, "text": null }, { "code": "// Java program to find if a number is// divisible by 9 or notclass IsDivisible{ // Function to find that number // is divisible by 9 or not static boolean check(String str) { // Compute sum of digits int n = str.length(); int digitSum = 0; for (int i=0; i<n; i++) digitSum += (str.charAt(i)-'0'); // Check if sum of digits is divisible by 9. return (digitSum % 9 == 0); } // main function public static void main (String[] args) { String str = \"99333\"; if(check(str)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}", "e": 28972, "s": 28312, "text": null }, { "code": "# Python 3 program to# find if a number is# divisible by# 9 or not # Function to find that# number divisible by 9# or notdef check(st) : # Compute sum of digits n = len(st) digitSum = 0 for i in range(0,n) : digitSum = digitSum + (int)(st[i]) # Check if sum of digits # is divisible by 9. return (digitSum % 9 == 0) # Driver codest = \"99333\" if(check(st)) : print(\"Yes\")else : print(\"No\") # This code is contributed by Nikita Tiwari.", "e": 29451, "s": 28972, "text": null }, { "code": "// C# program to find if a number is// divisible by 9 or not.using System; class GFG { // Function to find that number // is divisible by 9 or not static bool check(String str) { // Compute sum of digits int n = str.Length; int digitSum = 0; for (int i = 0; i < n; i++) digitSum += (str[i] - '0'); // Check if sum of digits is // divisible by 9. return (digitSum % 9 == 0); } // main function public static void Main () { String str = \"99333\"; if(check(str)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is Contributed by// nitin mittal.", "e": 30158, "s": 29451, "text": null }, { "code": "<?php// PHP program to find if a number// is divisible by 9 or not // Function to find that// number divisible by 9 or notfunction check($str){ // Compute sum of digits $n = strlen($str); $digitSum = 0; for ($i = 0; $i < $n; $i++) $digitSum += ($str[$i] - '0'); // Check if sum of digits // is divisible by 9. return ($digitSum % 9 == 0);} // Driver code$str = \"99333\";$x = check($str) ? \"Yes\" : \"No \";echo($x); // This code is contributed by Ajit.?>", "e": 30643, "s": 30158, "text": null }, { "code": "<script> // Javascript program to find if a number// is divisible by 9 or not // Function to find that// number divisible by 9 or notfunction check(str){ // Compute sum of digits let n = str.length; let digitSum = 0; for(let i = 0; i < n; i++) digitSum += (str[i] - '0'); // Check if sum of digits // is divisible by 9. return (digitSum % 9 == 0);} // Driver codelet str = \"99333\";let x = check(str) ? \"Yes\" : \"No \"; document.write(x); // This code is contributed by _saurabh_jaiswal. </script>", "e": 31181, "s": 30643, "text": null }, { "code": null, "e": 31190, "s": 31181, "text": "Output: " }, { "code": null, "e": 31194, "s": 31190, "text": "Yes" }, { "code": null, "e": 31619, "s": 31194, "text": "This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 31632, "s": 31619, "text": "nitin mittal" }, { "code": null, "e": 31638, "s": 31632, "text": "jit_t" }, { "code": null, "e": 31652, "s": 31638, "text": "ManasChhabra2" }, { "code": null, "e": 31669, "s": 31652, "text": "_saurabh_jaiswal" }, { "code": null, "e": 31682, "s": 31669, "text": "divisibility" }, { "code": null, "e": 31696, "s": 31682, "text": "large-numbers" }, { "code": null, "e": 31710, "s": 31696, "text": "number-digits" }, { "code": null, "e": 31723, "s": 31710, "text": "Mathematical" }, { "code": null, "e": 31736, "s": 31723, "text": "Mathematical" }, { "code": null, "e": 31834, "s": 31736, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31858, "s": 31834, "text": "Merge two sorted arrays" }, { "code": null, "e": 31901, "s": 31858, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 31915, "s": 31901, "text": "Prime Numbers" }, { "code": null, "e": 31957, "s": 31915, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 31979, "s": 31957, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 32052, "s": 31979, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 32073, "s": 32052, "text": "Operators in C / C++" }, { "code": null, "e": 32116, "s": 32073, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 32150, "s": 32116, "text": "Program for factorial of a number" } ]
Count total number of digits from 1 to n - GeeksforGeeks
22 May, 2021 Given a number n, count the total number of digits required to write all numbers from 1 to n. Examples: Input : 13 Output : 17 Numbers from 1 to 13 are 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13. So 1 - 9 require 9 digits and 10 - 13 require 8 digits. Hence 9 + 8 = 17 digits are required. Input : 4 Output : 4 Numbers are 1, 2, 3, 4 . Hence 4 digits are required. Naive Recursive Method – Naive approach to the above problem is to calculate the length of each number from 1 to n, then calculate the sum of the length of each of them. Recursive implementation of the same is – C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; int findDigits(int n){ if (n == 1) { return 1; } // Changing number to String string s = to_string(n); // Add length of number to total_sum return s.length() + findDigits(n - 1);} // Driver code int main(){ int n = 13; cout << findDigits(n) << endl; return 0;} // This code is contributed by divyeshrabadiya07 public class Main { static int findDigits(int n) { if (n == 1) { return 1; } // Changing number to String String s = String.valueOf(n); // add length of number to total_sum return s.length() + findDigits(n - 1); } public static void main(String[] args) { int n = 13; System.out.println(findDigits(n)); }} def findDigits(N): if N == 1: return 1 # Changing number to string s = str(N) # Add length of number to total_sum return len(s) + findDigits(N - 1) # Driver Code # Given NN = 13 # Function callprint(findDigits(N)) # This code is contributed by vishu2908 using System;using System.Collections;class GFG{ static int findDigits(int n){ if (n == 1) { return 1; } // Changing number to String string s = n.ToString(); // add length of number to total_sum return s.Length + findDigits(n - 1);} // Driver Codepublic static void Main(string[] args){ int n = 13; Console.Write(findDigits(n));}} // This code is contributed by rutvik_56 <script> function findDigits(n){ if (n == 1) { return 1; } // Changing number to String let s = n.toString(); // Add length of number to total_sum return (s.length + findDigits(n - 1));} // Driver code let n = 13; document.write( findDigits(n) + "<br>"); //This code is contributed by Mayank Tyagi</script> Output: 17 Iterative Method – (Optimized) To calculate the number of digits, we have to calculate the total number of digits required to write at ones, tens, hundredths .... places of the number . Consider n = 13, so digits at ones place are 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3 and digits at tens place are 1, 1, 1, 1 . So, total ones place digits from 1 to 13 is basically 13 ( 13 – 0 ) and tens place digits is 4 ( 13 – 9 ) . Let’s take another example n = 234, so digits at unit place are 1 ( 24 times ), 2 ( 24 times ), 3 ( 24 times ), 4 ( 24 times ), 5 ( 23 times ), 6 ( 23 times ), 7 (23 times), 8 ( 23 times ), 9 ( 23 times ), 0 ( 23 times ) hence 23 * 6 + 24 * 4 = 234 . Digits at tens place are 234 – 9 = 225 as from 1 to 234 only 1 – 9 are single digit numbers . And lastly at hundredths place digits are 234 – 99 = 135 as only 1 – 99 are two digit numbers . Hence, total number of digits we have to write are 234 ( 234 – 1 + 1 ) + 225 ( 234 – 10 + 1 ) + 135 ( 234 – 100 + 1 ) = 594 . So, basically we have to decrease 0, 9, 99, 999 ... from n to get the number of digits at ones, tens, hundredths, thousandths ... places and sum them to get the required result. Below is the implementation of this approach. C++ Java Python3 C# PHP Javascript // C++ program to count total number// of digits we have to write// from 1 to n#include <bits/stdc++.h>using namespace std; int totalDigits(int n){ // number_of_digits store total // digits we have to write int number_of_digits = 0; // In the loop we are decreasing // 0, 9, 99 ... from n till // ( n - i + 1 ) is greater than 0 // and sum them to number_of_digits // to get the required sum for(int i = 1; i <= n; i *= 10) number_of_digits += (n - i + 1); return number_of_digits;} // Driver codeint main(){ int n = 13; cout << totalDigits(n) << endl; return 0;} // Java program to count total number of digits// we have to write from 1 to n public class GFG { static int totalDigits(int n) { // number_of_digits store total // digits we have to write int number_of_digits = 0; // In the loop we are decreasing // 0, 9, 99 ... from n till // ( n - i + 1 ) is greater than 0 // and sum them to number_of_digits // to get the required sum for (int i = 1; i <= n; i *= 10) number_of_digits += (n - i + 1); return number_of_digits; } // Driver Method public static void main(String[] args) { int n = 13; System.out.println(totalDigits(n)); }} # Python3 program to count total number# of digits we have to write from 1 to n def totalDigits(n): # number_of_digits store total # digits we have to write number_of_digits = 0; # In the loop we are decreasing # 0, 9, 99 ... from n till #( n - i + 1 ) is greater than 0 # and sum them to number_of_digits # to get the required sum for i in range(1, n, 10): number_of_digits = (number_of_digits + (n - i + 1)); return number_of_digits; # Driver coden = 13;s = totalDigits(n) + 1;print(s); # This code is contributed# by Shivi_Aggarwal // C# program to count total number of// digits we have to write from 1 to nusing System; public class GFG { static int totalDigits(int n) { // number_of_digits store total // digits we have to write int number_of_digits = 0; // In the loop we are decreasing // 0, 9, 99 ... from n till // ( n - i + 1 ) is greater than 0 // and sum them to number_of_digits // to get the required sum for (int i = 1; i <= n; i *= 10) number_of_digits += (n - i + 1); return number_of_digits; } // Driver Method public static void Main() { int n = 13; Console.WriteLine(totalDigits(n)); }} // This code is contributed by vt_m. <?php// PHP program to count// total number of digits// we have to write from// 1 to n // Function that return// total number of digitsfunction totalDigits($n){ // number_of_digits store total // digits we have to write $number_of_digits = 0; // In the loop we are decreasing // 0, 9, 99 ... from n till // ( n - i + 1 ) is greater than 0 // and sum them to number_of_digits // to get the required sum for ($i = 1; $i <= $n; $i *= 10) $number_of_digits += ($n - $i + 1); return $number_of_digits;} // Driver Code $n = 13; echo totalDigits($n); // This code is contributed by vt_m.?> <script> // Javascript program to count total number// of digits we have to write// from 1 to nfunction totalDigits(n){ // number_of_digits store total // digits we have to write var number_of_digits = 0; // In the loop we are decreasing // 0, 9, 99 ... from n till // ( n - i + 1 ) is greater than 0 // and sum them to number_of_digits // to get the required sum for(var i = 1; i <= n; i *= 10) number_of_digits += (n - i + 1); return number_of_digits;} // Driver codevar n = 13;document.write(totalDigits(n)); </script> Output: 17 Time Complexity : O(Logn) This article is contributed by Surya Priy. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m Shivi_Aggarwal NikhilGundala vishu2908 rutvik_56 divyeshrabadiya07 noob2000 mayanktyagi1709 number-digits Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Print all possible combinations of r elements in a given array of size n Operators in C / C++ The Knight's tour problem | Backtracking-1 Program for factorial of a number Program for Decimal to Binary Conversion Find minimum number of coins that make a given value Program to find sum of elements in a given array
[ { "code": null, "e": 26345, "s": 26317, "text": "\n22 May, 2021" }, { "code": null, "e": 26439, "s": 26345, "text": "Given a number n, count the total number of digits required to write all numbers from 1 to n." }, { "code": null, "e": 26450, "s": 26439, "text": "Examples: " }, { "code": null, "e": 26713, "s": 26450, "text": "Input : 13\nOutput : 17\nNumbers from 1 to 13 are 1, 2, 3, 4, 5, \n6, 7, 8, 9, 10, 11, 12, 13.\nSo 1 - 9 require 9 digits and 10 - 13 require 8\ndigits. Hence 9 + 8 = 17 digits are required. \n\nInput : 4\nOutput : 4\nNumbers are 1, 2, 3, 4 . Hence 4 digits are required." }, { "code": null, "e": 26926, "s": 26713, "text": "Naive Recursive Method – Naive approach to the above problem is to calculate the length of each number from 1 to n, then calculate the sum of the length of each of them. Recursive implementation of the same is – " }, { "code": null, "e": 26930, "s": 26926, "text": "C++" }, { "code": null, "e": 26935, "s": 26930, "text": "Java" }, { "code": null, "e": 26943, "s": 26935, "text": "Python3" }, { "code": null, "e": 26946, "s": 26943, "text": "C#" }, { "code": null, "e": 26957, "s": 26946, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; int findDigits(int n){ if (n == 1) { return 1; } // Changing number to String string s = to_string(n); // Add length of number to total_sum return s.length() + findDigits(n - 1);} // Driver code int main(){ int n = 13; cout << findDigits(n) << endl; return 0;} // This code is contributed by divyeshrabadiya07", "e": 27367, "s": 26957, "text": null }, { "code": "public class Main { static int findDigits(int n) { if (n == 1) { return 1; } // Changing number to String String s = String.valueOf(n); // add length of number to total_sum return s.length() + findDigits(n - 1); } public static void main(String[] args) { int n = 13; System.out.println(findDigits(n)); }}", "e": 27768, "s": 27367, "text": null }, { "code": "def findDigits(N): if N == 1: return 1 # Changing number to string s = str(N) # Add length of number to total_sum return len(s) + findDigits(N - 1) # Driver Code # Given NN = 13 # Function callprint(findDigits(N)) # This code is contributed by vishu2908", "e": 28047, "s": 27768, "text": null }, { "code": "using System;using System.Collections;class GFG{ static int findDigits(int n){ if (n == 1) { return 1; } // Changing number to String string s = n.ToString(); // add length of number to total_sum return s.Length + findDigits(n - 1);} // Driver Codepublic static void Main(string[] args){ int n = 13; Console.Write(findDigits(n));}} // This code is contributed by rutvik_56", "e": 28439, "s": 28047, "text": null }, { "code": "<script> function findDigits(n){ if (n == 1) { return 1; } // Changing number to String let s = n.toString(); // Add length of number to total_sum return (s.length + findDigits(n - 1));} // Driver code let n = 13; document.write( findDigits(n) + \"<br>\"); //This code is contributed by Mayank Tyagi</script>", "e": 28796, "s": 28439, "text": null }, { "code": null, "e": 28805, "s": 28796, "text": "Output: " }, { "code": null, "e": 28809, "s": 28805, "text": " 17" }, { "code": null, "e": 29973, "s": 28809, "text": "Iterative Method – (Optimized) To calculate the number of digits, we have to calculate the total number of digits required to write at ones, tens, hundredths .... places of the number . Consider n = 13, so digits at ones place are 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3 and digits at tens place are 1, 1, 1, 1 . So, total ones place digits from 1 to 13 is basically 13 ( 13 – 0 ) and tens place digits is 4 ( 13 – 9 ) . Let’s take another example n = 234, so digits at unit place are 1 ( 24 times ), 2 ( 24 times ), 3 ( 24 times ), 4 ( 24 times ), 5 ( 23 times ), 6 ( 23 times ), 7 (23 times), 8 ( 23 times ), 9 ( 23 times ), 0 ( 23 times ) hence 23 * 6 + 24 * 4 = 234 . Digits at tens place are 234 – 9 = 225 as from 1 to 234 only 1 – 9 are single digit numbers . And lastly at hundredths place digits are 234 – 99 = 135 as only 1 – 99 are two digit numbers . Hence, total number of digits we have to write are 234 ( 234 – 1 + 1 ) + 225 ( 234 – 10 + 1 ) + 135 ( 234 – 100 + 1 ) = 594 . So, basically we have to decrease 0, 9, 99, 999 ... from n to get the number of digits at ones, tens, hundredths, thousandths ... places and sum them to get the required result." }, { "code": null, "e": 30019, "s": 29973, "text": "Below is the implementation of this approach." }, { "code": null, "e": 30023, "s": 30019, "text": "C++" }, { "code": null, "e": 30028, "s": 30023, "text": "Java" }, { "code": null, "e": 30036, "s": 30028, "text": "Python3" }, { "code": null, "e": 30039, "s": 30036, "text": "C#" }, { "code": null, "e": 30043, "s": 30039, "text": "PHP" }, { "code": null, "e": 30054, "s": 30043, "text": "Javascript" }, { "code": "// C++ program to count total number// of digits we have to write// from 1 to n#include <bits/stdc++.h>using namespace std; int totalDigits(int n){ // number_of_digits store total // digits we have to write int number_of_digits = 0; // In the loop we are decreasing // 0, 9, 99 ... from n till // ( n - i + 1 ) is greater than 0 // and sum them to number_of_digits // to get the required sum for(int i = 1; i <= n; i *= 10) number_of_digits += (n - i + 1); return number_of_digits;} // Driver codeint main(){ int n = 13; cout << totalDigits(n) << endl; return 0;}", "e": 30675, "s": 30054, "text": null }, { "code": "// Java program to count total number of digits// we have to write from 1 to n public class GFG { static int totalDigits(int n) { // number_of_digits store total // digits we have to write int number_of_digits = 0; // In the loop we are decreasing // 0, 9, 99 ... from n till // ( n - i + 1 ) is greater than 0 // and sum them to number_of_digits // to get the required sum for (int i = 1; i <= n; i *= 10) number_of_digits += (n - i + 1); return number_of_digits; } // Driver Method public static void main(String[] args) { int n = 13; System.out.println(totalDigits(n)); }}", "e": 31370, "s": 30675, "text": null }, { "code": "# Python3 program to count total number# of digits we have to write from 1 to n def totalDigits(n): # number_of_digits store total # digits we have to write number_of_digits = 0; # In the loop we are decreasing # 0, 9, 99 ... from n till #( n - i + 1 ) is greater than 0 # and sum them to number_of_digits # to get the required sum for i in range(1, n, 10): number_of_digits = (number_of_digits + (n - i + 1)); return number_of_digits; # Driver coden = 13;s = totalDigits(n) + 1;print(s); # This code is contributed# by Shivi_Aggarwal", "e": 31990, "s": 31370, "text": null }, { "code": "// C# program to count total number of// digits we have to write from 1 to nusing System; public class GFG { static int totalDigits(int n) { // number_of_digits store total // digits we have to write int number_of_digits = 0; // In the loop we are decreasing // 0, 9, 99 ... from n till // ( n - i + 1 ) is greater than 0 // and sum them to number_of_digits // to get the required sum for (int i = 1; i <= n; i *= 10) number_of_digits += (n - i + 1); return number_of_digits; } // Driver Method public static void Main() { int n = 13; Console.WriteLine(totalDigits(n)); }} // This code is contributed by vt_m.", "e": 32722, "s": 31990, "text": null }, { "code": "<?php// PHP program to count// total number of digits// we have to write from// 1 to n // Function that return// total number of digitsfunction totalDigits($n){ // number_of_digits store total // digits we have to write $number_of_digits = 0; // In the loop we are decreasing // 0, 9, 99 ... from n till // ( n - i + 1 ) is greater than 0 // and sum them to number_of_digits // to get the required sum for ($i = 1; $i <= $n; $i *= 10) $number_of_digits += ($n - $i + 1); return $number_of_digits;} // Driver Code $n = 13; echo totalDigits($n); // This code is contributed by vt_m.?>", "e": 33363, "s": 32722, "text": null }, { "code": "<script> // Javascript program to count total number// of digits we have to write// from 1 to nfunction totalDigits(n){ // number_of_digits store total // digits we have to write var number_of_digits = 0; // In the loop we are decreasing // 0, 9, 99 ... from n till // ( n - i + 1 ) is greater than 0 // and sum them to number_of_digits // to get the required sum for(var i = 1; i <= n; i *= 10) number_of_digits += (n - i + 1); return number_of_digits;} // Driver codevar n = 13;document.write(totalDigits(n)); </script>", "e": 33926, "s": 33363, "text": null }, { "code": null, "e": 33935, "s": 33926, "text": "Output: " }, { "code": null, "e": 33939, "s": 33935, "text": " 17" }, { "code": null, "e": 33965, "s": 33939, "text": "Time Complexity : O(Logn)" }, { "code": null, "e": 34384, "s": 33965, "text": "This article is contributed by Surya Priy. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 34389, "s": 34384, "text": "vt_m" }, { "code": null, "e": 34404, "s": 34389, "text": "Shivi_Aggarwal" }, { "code": null, "e": 34418, "s": 34404, "text": "NikhilGundala" }, { "code": null, "e": 34428, "s": 34418, "text": "vishu2908" }, { "code": null, "e": 34438, "s": 34428, "text": "rutvik_56" }, { "code": null, "e": 34456, "s": 34438, "text": "divyeshrabadiya07" }, { "code": null, "e": 34465, "s": 34456, "text": "noob2000" }, { "code": null, "e": 34481, "s": 34465, "text": "mayanktyagi1709" }, { "code": null, "e": 34495, "s": 34481, "text": "number-digits" }, { "code": null, "e": 34508, "s": 34495, "text": "Mathematical" }, { "code": null, "e": 34521, "s": 34508, "text": "Mathematical" }, { "code": null, "e": 34619, "s": 34521, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34643, "s": 34619, "text": "Merge two sorted arrays" }, { "code": null, "e": 34686, "s": 34643, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 34700, "s": 34686, "text": "Prime Numbers" }, { "code": null, "e": 34773, "s": 34700, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 34794, "s": 34773, "text": "Operators in C / C++" }, { "code": null, "e": 34837, "s": 34794, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 34871, "s": 34837, "text": "Program for factorial of a number" }, { "code": null, "e": 34912, "s": 34871, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 34965, "s": 34912, "text": "Find minimum number of coins that make a given value" } ]
Python Program for Comb Sort - GeeksforGeeks
27 Jan, 2022 Comb Sort is mainly an improvement over Bubble Sort. Bubble sort always compares adjacent values. So all inversions are removed one by one. Comb Sort improves on Bubble Sort by using gap of size more than 1. The gap starts with a large value and shrinks by a factor of 1.3 in every iteration until it reaches the value 1. Thus Comb Sort removes more than one inversion counts with one swap and performs better than Bubble Sort.The shrink factor has been empirically found to be 1.3 (by testing Combsort on over 200,000 random lists) [Source: Wiki]Although, it works better than Bubble Sort on average, worst case remains O(n2). Python # Python program for implementation of CombSort # To find next gap from currentdef getNextGap(gap): # Shrink gap by Shrink factor gap = (gap * 10)/13 if gap < 1: return 1 return gap # Function to sort arr[] using Comb Sortdef combSort(arr): n = len(arr) # Initialize gap gap = n # Initialize swapped as true to make sure that # loop runs swapped = True # Keep running while gap is more than 1 and last # iteration caused a swap while gap !=1 or swapped == 1: # Find next gap gap = getNextGap(gap) # Initialize swapped as false so that we can # check if swap happened or not swapped = False # Compare all elements with current gap for i in range(0, n-gap): if arr[i] > arr[i + gap]: arr[i], arr[i + gap]=arr[i + gap], arr[i] swapped = True # Driver code to test abovearr = [ 8, 4, 1, 3, -44, 23, -6, 28, 0]combSort(arr) print ("Sorted array:")for i in range(len(arr)): print (arr[i]), # This code is contributed by Mohit Kumra Output : Sorted array: -44 -6 0 1 3 4 8 23 28 56 Please refer complete article on Comb Sort for more details! sumitgumber28 python sorting-exercises Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Appending to list in Python dictionary Python program to interchange first and last elements in a list How to inverse a matrix using NumPy Differences and Applications of List, Tuple, Set and Dictionary in Python Python | Get the first key in dictionary Python Program for Merge Sort Python | Find most frequent element in a list Python | Difference between two dates (in minutes) using datetime.timedelta() method Python program to find smallest number in a list Python - Convert JSON to string
[ { "code": null, "e": 26097, "s": 26069, "text": "\n27 Jan, 2022" }, { "code": null, "e": 26727, "s": 26097, "text": "Comb Sort is mainly an improvement over Bubble Sort. Bubble sort always compares adjacent values. So all inversions are removed one by one. Comb Sort improves on Bubble Sort by using gap of size more than 1. The gap starts with a large value and shrinks by a factor of 1.3 in every iteration until it reaches the value 1. Thus Comb Sort removes more than one inversion counts with one swap and performs better than Bubble Sort.The shrink factor has been empirically found to be 1.3 (by testing Combsort on over 200,000 random lists) [Source: Wiki]Although, it works better than Bubble Sort on average, worst case remains O(n2). " }, { "code": null, "e": 26734, "s": 26727, "text": "Python" }, { "code": "# Python program for implementation of CombSort # To find next gap from currentdef getNextGap(gap): # Shrink gap by Shrink factor gap = (gap * 10)/13 if gap < 1: return 1 return gap # Function to sort arr[] using Comb Sortdef combSort(arr): n = len(arr) # Initialize gap gap = n # Initialize swapped as true to make sure that # loop runs swapped = True # Keep running while gap is more than 1 and last # iteration caused a swap while gap !=1 or swapped == 1: # Find next gap gap = getNextGap(gap) # Initialize swapped as false so that we can # check if swap happened or not swapped = False # Compare all elements with current gap for i in range(0, n-gap): if arr[i] > arr[i + gap]: arr[i], arr[i + gap]=arr[i + gap], arr[i] swapped = True # Driver code to test abovearr = [ 8, 4, 1, 3, -44, 23, -6, 28, 0]combSort(arr) print (\"Sorted array:\")for i in range(len(arr)): print (arr[i]), # This code is contributed by Mohit Kumra", "e": 27808, "s": 26734, "text": null }, { "code": null, "e": 27819, "s": 27808, "text": "Output : " }, { "code": null, "e": 27861, "s": 27819, "text": "Sorted array: \n-44 -6 0 1 3 4 8 23 28 56 " }, { "code": null, "e": 27923, "s": 27861, "text": "Please refer complete article on Comb Sort for more details! " }, { "code": null, "e": 27937, "s": 27923, "text": "sumitgumber28" }, { "code": null, "e": 27962, "s": 27937, "text": "python sorting-exercises" }, { "code": null, "e": 27978, "s": 27962, "text": "Python Programs" }, { "code": null, "e": 28076, "s": 27978, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28115, "s": 28076, "text": "Appending to list in Python dictionary" }, { "code": null, "e": 28179, "s": 28115, "text": "Python program to interchange first and last elements in a list" }, { "code": null, "e": 28215, "s": 28179, "text": "How to inverse a matrix using NumPy" }, { "code": null, "e": 28289, "s": 28215, "text": "Differences and Applications of List, Tuple, Set and Dictionary in Python" }, { "code": null, "e": 28330, "s": 28289, "text": "Python | Get the first key in dictionary" }, { "code": null, "e": 28360, "s": 28330, "text": "Python Program for Merge Sort" }, { "code": null, "e": 28406, "s": 28360, "text": "Python | Find most frequent element in a list" }, { "code": null, "e": 28491, "s": 28406, "text": "Python | Difference between two dates (in minutes) using datetime.timedelta() method" }, { "code": null, "e": 28540, "s": 28491, "text": "Python program to find smallest number in a list" } ]
jQWidgets - GeeksforGeeks
13 Dec, 2021 jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful and optimized framework, platform-independent, and widely supported. It has more than 60 UI widget that helps to create attractive UI design. Download and Installation: Download jQWidget file in zip format from the https://www.jqwidgets.com/download/ link. After downloading the zip file, extract the files and save them into the folder. After that create a new HTML file and add the jQWidget code into the file and include the widget link inside the head section. Installing jQWidgets using npm: Open Node.js command prompt and run the following command –npm install jqwidgets-framework - demos & scripts or npm install jqwidgets-scripts - scripts or npm install jqwidgets-ng - angular modules npm install jqwidgets-framework - demos & scripts or npm install jqwidgets-scripts - scripts or npm install jqwidgets-ng - angular modules To get the information of jQWidget npm package, use the following command –npm info jqwidgets-framework npm info jqwidgets-framework Installing the jQWidgets Bower Package: Open Node.js command prompt and run the following command –bower install jqwidgets bower install jqwidgets To get the information of jQWidget bower package, use the following command –bower info jqwidgets bower info jqwidgets Example: This example describe the basic example. In this example, we will use jqxCalendar widget to create a calendar and added the back text on it using backText Property. Output: jQWidgets Complete References: jQWidget jqxBarGauge jQWidget jqxBulletChart jQWidget jqxButton jQWidget jqxCalendar jQWidget jqxChart jQWidget jqxCheckBox jQWidget jqxColorPicker jQWidget jqxComboBox jQWidget jqxComplexInput jQWidget jqxDataTable jQWidget jqxDateTimeInput jQWidget jqxDocking jQWidget jqxDragDrop jQWidget jqxDropDownList jQWidget jqxEditor jQWidget jqxExpander jQWidget jqxFileUpload jQWidget jqxForm jQWidget jqxFormattedInput jQWidget jqxGauge jQWidget jqxGrid jQWidget jqxHeatMap jQWidget jqxInput jQWidget jqxKnob jQWidget jqxListBox jQWidget jqxListMenu jQWidget jqxLoader jQWidget jqxMaskedInput jQWidget jqxMenu jQWidget jqxNavBar jQWidget jqxNavigationBar jQWidget jqxNotification jQWidget jqxNumberInput jQWidget jqxPasswordInput jQWidget jqxPopover jQWidget jqxProgressBar jQWidget jqxRadioButton jQWidget jqxRangeSelector jQWidget jqxRating jQWidget jqxResponsivePanel jQWidget jqxRibbon jQWidget jqxScheduler jQWidget jqxScrollBar jQWidget jqxScrollView jQWidget jqxSlider jQWidget jqxSortable jQWidget jqxSplitter jQWidget jqxTabs jQWidget jqxTagCloud jQWidget jqxTextArea jQWidget jqxTimePicker jQWidget jqxToolBar jQWidget jqxTooltip jQWidget jqxTouch jQWidget jqxTree jQWidget jqxTreeGrid jQWidget jqxTreeMap jQWidget jqxValidator jQWidget jqxWindow Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Program for Breadth First Search or BFS for a Graph Best Time to Buy and Sell Stock Web Development Using Java Technology For Beginners Must Do Coding Questions for Product Based Companies Converting Epsilon-NFA to DFA using Python and Graphviz Python Program to Rotate Matrix Elements Minimum edges to be removed from given undirected graph to remove any existing path between nodes A and B 50 Common Ports You Should Know Python Program for Rotate a Matrix by 180 degree C++ Program to multiply two matrices
[ { "code": null, "e": 89901, "s": 89873, "text": "\n13 Dec, 2021" }, { "code": null, "e": 90162, "s": 89901, "text": "jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful and optimized framework, platform-independent, and widely supported. It has more than 60 UI widget that helps to create attractive UI design." }, { "code": null, "e": 90189, "s": 90162, "text": "Download and Installation:" }, { "code": null, "e": 90485, "s": 90189, "text": "Download jQWidget file in zip format from the https://www.jqwidgets.com/download/ link. After downloading the zip file, extract the files and save them into the folder. After that create a new HTML file and add the jQWidget code into the file and include the widget link inside the head section." }, { "code": null, "e": 90517, "s": 90485, "text": "Installing jQWidgets using npm:" }, { "code": null, "e": 90715, "s": 90517, "text": "Open Node.js command prompt and run the following command –npm install jqwidgets-framework - demos & scripts\nor\nnpm install jqwidgets-scripts - scripts\nor\nnpm install jqwidgets-ng - angular modules" }, { "code": null, "e": 90854, "s": 90715, "text": "npm install jqwidgets-framework - demos & scripts\nor\nnpm install jqwidgets-scripts - scripts\nor\nnpm install jqwidgets-ng - angular modules" }, { "code": null, "e": 90958, "s": 90854, "text": "To get the information of jQWidget npm package, use the following command –npm info jqwidgets-framework" }, { "code": null, "e": 90987, "s": 90958, "text": "npm info jqwidgets-framework" }, { "code": null, "e": 91029, "s": 90989, "text": "Installing the jQWidgets Bower Package:" }, { "code": null, "e": 91112, "s": 91029, "text": "Open Node.js command prompt and run the following command –bower install jqwidgets" }, { "code": null, "e": 91136, "s": 91112, "text": "bower install jqwidgets" }, { "code": null, "e": 91234, "s": 91136, "text": "To get the information of jQWidget bower package, use the following command –bower info jqwidgets" }, { "code": null, "e": 91255, "s": 91234, "text": "bower info jqwidgets" }, { "code": null, "e": 91429, "s": 91255, "text": "Example: This example describe the basic example. In this example, we will use jqxCalendar widget to create a calendar and added the back text on it using backText Property." }, { "code": null, "e": 91437, "s": 91429, "text": "Output:" }, { "code": null, "e": 91468, "s": 91437, "text": "jQWidgets Complete References:" }, { "code": null, "e": 91489, "s": 91468, "text": "jQWidget jqxBarGauge" }, { "code": null, "e": 91513, "s": 91489, "text": "jQWidget jqxBulletChart" }, { "code": null, "e": 91532, "s": 91513, "text": "jQWidget jqxButton" }, { "code": null, "e": 91553, "s": 91532, "text": "jQWidget jqxCalendar" }, { "code": null, "e": 91571, "s": 91553, "text": "jQWidget jqxChart" }, { "code": null, "e": 91592, "s": 91571, "text": "jQWidget jqxCheckBox" }, { "code": null, "e": 91616, "s": 91592, "text": "jQWidget jqxColorPicker" }, { "code": null, "e": 91637, "s": 91616, "text": "jQWidget jqxComboBox" }, { "code": null, "e": 91662, "s": 91637, "text": "jQWidget jqxComplexInput" }, { "code": null, "e": 91684, "s": 91662, "text": "jQWidget jqxDataTable" }, { "code": null, "e": 91710, "s": 91684, "text": "jQWidget jqxDateTimeInput" }, { "code": null, "e": 91730, "s": 91710, "text": "jQWidget jqxDocking" }, { "code": null, "e": 91751, "s": 91730, "text": "jQWidget jqxDragDrop" }, { "code": null, "e": 91776, "s": 91751, "text": "jQWidget jqxDropDownList" }, { "code": null, "e": 91795, "s": 91776, "text": "jQWidget jqxEditor" }, { "code": null, "e": 91816, "s": 91795, "text": "jQWidget jqxExpander" }, { "code": null, "e": 91839, "s": 91816, "text": "jQWidget jqxFileUpload" }, { "code": null, "e": 91856, "s": 91839, "text": "jQWidget jqxForm" }, { "code": null, "e": 91883, "s": 91856, "text": "jQWidget jqxFormattedInput" }, { "code": null, "e": 91901, "s": 91883, "text": "jQWidget jqxGauge" }, { "code": null, "e": 91918, "s": 91901, "text": "jQWidget jqxGrid" }, { "code": null, "e": 91938, "s": 91918, "text": "jQWidget jqxHeatMap" }, { "code": null, "e": 91956, "s": 91938, "text": "jQWidget jqxInput" }, { "code": null, "e": 91973, "s": 91956, "text": "jQWidget jqxKnob" }, { "code": null, "e": 91993, "s": 91973, "text": "jQWidget jqxListBox" }, { "code": null, "e": 92014, "s": 91993, "text": "jQWidget jqxListMenu" }, { "code": null, "e": 92033, "s": 92014, "text": "jQWidget jqxLoader" }, { "code": null, "e": 92057, "s": 92033, "text": "jQWidget jqxMaskedInput" }, { "code": null, "e": 92074, "s": 92057, "text": "jQWidget jqxMenu" }, { "code": null, "e": 92093, "s": 92074, "text": "jQWidget jqxNavBar" }, { "code": null, "e": 92119, "s": 92093, "text": "jQWidget jqxNavigationBar" }, { "code": null, "e": 92144, "s": 92119, "text": "jQWidget jqxNotification" }, { "code": null, "e": 92168, "s": 92144, "text": "jQWidget jqxNumberInput" }, { "code": null, "e": 92194, "s": 92168, "text": "jQWidget jqxPasswordInput" }, { "code": null, "e": 92214, "s": 92194, "text": "jQWidget jqxPopover" }, { "code": null, "e": 92238, "s": 92214, "text": "jQWidget jqxProgressBar" }, { "code": null, "e": 92262, "s": 92238, "text": "jQWidget jqxRadioButton" }, { "code": null, "e": 92288, "s": 92262, "text": "jQWidget jqxRangeSelector" }, { "code": null, "e": 92307, "s": 92288, "text": "jQWidget jqxRating" }, { "code": null, "e": 92335, "s": 92307, "text": "jQWidget jqxResponsivePanel" }, { "code": null, "e": 92354, "s": 92335, "text": "jQWidget jqxRibbon" }, { "code": null, "e": 92376, "s": 92354, "text": "jQWidget jqxScheduler" }, { "code": null, "e": 92398, "s": 92376, "text": "jQWidget jqxScrollBar" }, { "code": null, "e": 92421, "s": 92398, "text": "jQWidget jqxScrollView" }, { "code": null, "e": 92440, "s": 92421, "text": "jQWidget jqxSlider" }, { "code": null, "e": 92461, "s": 92440, "text": "jQWidget jqxSortable" }, { "code": null, "e": 92482, "s": 92461, "text": "jQWidget jqxSplitter" }, { "code": null, "e": 92499, "s": 92482, "text": "jQWidget jqxTabs" }, { "code": null, "e": 92520, "s": 92499, "text": "jQWidget jqxTagCloud" }, { "code": null, "e": 92541, "s": 92520, "text": "jQWidget jqxTextArea" }, { "code": null, "e": 92564, "s": 92541, "text": "jQWidget jqxTimePicker" }, { "code": null, "e": 92584, "s": 92564, "text": "jQWidget jqxToolBar" }, { "code": null, "e": 92604, "s": 92584, "text": "jQWidget jqxTooltip" }, { "code": null, "e": 92622, "s": 92604, "text": "jQWidget jqxTouch" }, { "code": null, "e": 92639, "s": 92622, "text": "jQWidget jqxTree" }, { "code": null, "e": 92660, "s": 92639, "text": "jQWidget jqxTreeGrid" }, { "code": null, "e": 92680, "s": 92660, "text": "jQWidget jqxTreeMap" }, { "code": null, "e": 92702, "s": 92680, "text": "jQWidget jqxValidator" }, { "code": null, "e": 92721, "s": 92702, "text": "jQWidget jqxWindow" }, { "code": null, "e": 92847, "s": 92723, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 92945, "s": 92847, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 93004, "s": 92945, "text": "Python Program for Breadth First Search or BFS for a Graph" }, { "code": null, "e": 93036, "s": 93004, "text": "Best Time to Buy and Sell Stock" }, { "code": null, "e": 93088, "s": 93036, "text": "Web Development Using Java Technology For Beginners" }, { "code": null, "e": 93141, "s": 93088, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 93197, "s": 93141, "text": "Converting Epsilon-NFA to DFA using Python and Graphviz" }, { "code": null, "e": 93238, "s": 93197, "text": "Python Program to Rotate Matrix Elements" }, { "code": null, "e": 93344, "s": 93238, "text": "Minimum edges to be removed from given undirected graph to remove any existing path between nodes A and B" }, { "code": null, "e": 93376, "s": 93344, "text": "50 Common Ports You Should Know" }, { "code": null, "e": 93425, "s": 93376, "text": "Python Program for Rotate a Matrix by 180 degree" } ]
Multimethods in Python - GeeksforGeeks
21 Apr, 2020 Multimethod basically means a function that has multiple versions, distinguished by the type of the arguments. For better understanding consider the below example. @multimethod def sum(x: int, y: int): return x + y @multimethod def sum(x: str, y: str): return x+" "+y The above example is similar to def sum(x, y): if isinstance(x, int) and isinstance(y, int): return x + y elif isinstance(x, str) and isinstance(y, str): return x + ' ' + y At syntactical level, Python does not support multiple dispatch but it is possible to add multiple dispatch using a library extension multimethod. To install this library type the below command in the terminal. pip install multimethod Example 1: # Python program to demonstrate# multimethods from multimethod import multimethod # Function that will be called# for integer addition@multimethoddef sum(x: int, y: int): return x + y # Function that will be called# for string addition@multimethoddef sum(x: str, y: str): return x+" "+y # Driver's codeprint(sum(2, 3))print(sum("Hello", "World")) Output: 5 Hello World Example 2: # Python program to demonstrate# multimethods from multimethod import multimethod class GFG(object): @multimethod def double(self, x: int): print(2 * x) @multimethod def double(self, x: complex): print("sorry, I don't like complex numbers") # Driver Codeobj = GFG()obj.double(3)obj.double(6j) Output: 6 sorry, I don't like complex numbers Python Decorators python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25563, "s": 25535, "text": "\n21 Apr, 2020" }, { "code": null, "e": 25727, "s": 25563, "text": "Multimethod basically means a function that has multiple versions, distinguished by the type of the arguments. For better understanding consider the below example." }, { "code": null, "e": 26050, "s": 25727, "text": "@multimethod\ndef sum(x: int, y: int):\n return x + y\n\n@multimethod\ndef sum(x: str, y: str):\n return x+\" \"+y\n\nThe above example is similar to\n\ndef sum(x, y):\n \n if isinstance(x, int) and isinstance(y, int):\n return x + y\n \n elif isinstance(x, str) and isinstance(y, str):\n return x + ' ' + y\n" }, { "code": null, "e": 26261, "s": 26050, "text": "At syntactical level, Python does not support multiple dispatch but it is possible to add multiple dispatch using a library extension multimethod. To install this library type the below command in the terminal." }, { "code": null, "e": 26285, "s": 26261, "text": "pip install multimethod" }, { "code": null, "e": 26296, "s": 26285, "text": "Example 1:" }, { "code": "# Python program to demonstrate# multimethods from multimethod import multimethod # Function that will be called# for integer addition@multimethoddef sum(x: int, y: int): return x + y # Function that will be called# for string addition@multimethoddef sum(x: str, y: str): return x+\" \"+y # Driver's codeprint(sum(2, 3))print(sum(\"Hello\", \"World\"))", "e": 26657, "s": 26296, "text": null }, { "code": null, "e": 26665, "s": 26657, "text": "Output:" }, { "code": null, "e": 26679, "s": 26665, "text": "5\nHello World" }, { "code": null, "e": 26690, "s": 26679, "text": "Example 2:" }, { "code": "# Python program to demonstrate# multimethods from multimethod import multimethod class GFG(object): @multimethod def double(self, x: int): print(2 * x) @multimethod def double(self, x: complex): print(\"sorry, I don't like complex numbers\") # Driver Codeobj = GFG()obj.double(3)obj.double(6j)", "e": 27032, "s": 26690, "text": null }, { "code": null, "e": 27040, "s": 27032, "text": "Output:" }, { "code": null, "e": 27078, "s": 27040, "text": "6\nsorry, I don't like complex numbers" }, { "code": null, "e": 27096, "s": 27078, "text": "Python Decorators" }, { "code": null, "e": 27111, "s": 27096, "text": "python-modules" }, { "code": null, "e": 27118, "s": 27111, "text": "Python" }, { "code": null, "e": 27216, "s": 27118, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27248, "s": 27216, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27290, "s": 27248, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27332, "s": 27290, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27388, "s": 27332, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27415, "s": 27388, "text": "Python Classes and Objects" }, { "code": null, "e": 27454, "s": 27415, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27485, "s": 27454, "text": "Python | os.path.join() method" }, { "code": null, "e": 27514, "s": 27485, "text": "Create a directory in Python" }, { "code": null, "e": 27536, "s": 27514, "text": "Defaultdict in Python" } ]
Python | Pandas Series.hasnans - GeeksforGeeks
28 Jan, 2019 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 series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.hasnans attribute returns a boolean value. It return True if the given Series object has missing values in it else it return False. Syntax:Series.hasnans Parameter : None Returns : boolean Example #1: Use Series.hasnans attribute to check if the given Series object has any missing values in it. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4'] # Print the seriesprint(sr) Output : Now we will use Series.hasnans attribute to check for the missing values in sr object. # check for missing values.sr.hasnans Output : As we can see in the output, the Series.hasnans attribute has returned False indicating that there is no missing values in the given series object. Example #2 : Use Series.hasnans attribute to check if the given Series object has any missing values in it. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([1000, 'Calgarry', 5000, None]) # Print the seriesprint(sr) Output : Now we will use Series.hasnans attribute to check for the missing values in sr object. # check for missing values.sr.hasnans Output :As we can see in the output, the Series.hasnans attribute has returned True indicating that there is at least one missing value in the given series object. 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 Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n28 Jan, 2019" }, { "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": 26008, "s": 25751, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 26154, "s": 26008, "text": "Pandas Series.hasnans attribute returns a boolean value. It return True if the given Series object has missing values in it else it return False." }, { "code": null, "e": 26176, "s": 26154, "text": "Syntax:Series.hasnans" }, { "code": null, "e": 26193, "s": 26176, "text": "Parameter : None" }, { "code": null, "e": 26211, "s": 26193, "text": "Returns : boolean" }, { "code": null, "e": 26318, "s": 26211, "text": "Example #1: Use Series.hasnans attribute to check if the given Series object has any missing values in it." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4'] # Print the seriesprint(sr)", "e": 26558, "s": 26318, "text": null }, { "code": null, "e": 26567, "s": 26558, "text": "Output :" }, { "code": null, "e": 26654, "s": 26567, "text": "Now we will use Series.hasnans attribute to check for the missing values in sr object." }, { "code": "# check for missing values.sr.hasnans", "e": 26692, "s": 26654, "text": null }, { "code": null, "e": 26701, "s": 26692, "text": "Output :" }, { "code": null, "e": 26957, "s": 26701, "text": "As we can see in the output, the Series.hasnans attribute has returned False indicating that there is no missing values in the given series object. Example #2 : Use Series.hasnans attribute to check if the given Series object has any missing values in it." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([1000, 'Calgarry', 5000, None]) # Print the seriesprint(sr)", "e": 27099, "s": 26957, "text": null }, { "code": null, "e": 27108, "s": 27099, "text": "Output :" }, { "code": null, "e": 27195, "s": 27108, "text": "Now we will use Series.hasnans attribute to check for the missing values in sr object." }, { "code": "# check for missing values.sr.hasnans", "e": 27233, "s": 27195, "text": null }, { "code": null, "e": 27397, "s": 27233, "text": "Output :As we can see in the output, the Series.hasnans attribute has returned True indicating that there is at least one missing value in the given series object." }, { "code": null, "e": 27418, "s": 27397, "text": "Python pandas-series" }, { "code": null, "e": 27447, "s": 27418, "text": "Python pandas-series-methods" }, { "code": null, "e": 27461, "s": 27447, "text": "Python-pandas" }, { "code": null, "e": 27468, "s": 27461, "text": "Python" }, { "code": null, "e": 27566, "s": 27468, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27598, "s": 27566, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27640, "s": 27598, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27682, "s": 27640, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27709, "s": 27682, "text": "Python Classes and Objects" }, { "code": null, "e": 27765, "s": 27709, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27804, "s": 27765, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27826, "s": 27804, "text": "Defaultdict in Python" }, { "code": null, "e": 27857, "s": 27826, "text": "Python | os.path.join() method" }, { "code": null, "e": 27886, "s": 27857, "text": "Create a directory in Python" } ]
Angular10 NgFor Directive - GeeksforGeeks
03 Jun, 2021 In this article, we are going to see what is NgFor in Angular 10 and how to use it. NgFor is used as a structural directive that renders each element for the given collection each element can be displayed on the page. Syntax: <li *ngFor='condition'></li> NgModule: Module used by NgForOf is: CommonModule Selectors: [ngFor] Approach: Create the angular app to be used There is no need for any import for the NgFor to be used In app.component.ts define the array to be used with ngFor directive. In app.component.html use NgFor directive with list element to display array elements. serve the angular app using ng serve to see the output Example 1: app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html',})export class AppComponent { a=['gfg1', 'gfg2', 'gfg3', 'gfg4']} app.component.html <ul> <li *ngFor='let i of a'> {{i}} </li></ul> Output: Example 2: app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html',})export class AppComponent { a=['gfg1', 'gfg2', 'gfg3', 'gfg4']} app.component.html <ol> <li *ngFor='let i of a'> {{i}} </li></ol> Output: Reference: https://angular.io/api/common/NgForOf Angular10 AngularJS-Directives Misc Web Technologies Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Activation Functions Characteristics of Internet of Things Advantages and Disadvantages of OOP Sensors in Internet of Things(IoT) Challenges in Internet of things (IoT) Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25895, "s": 25867, "text": "\n03 Jun, 2021" }, { "code": null, "e": 25979, "s": 25895, "text": "In this article, we are going to see what is NgFor in Angular 10 and how to use it." }, { "code": null, "e": 26113, "s": 25979, "text": "NgFor is used as a structural directive that renders each element for the given collection each element can be displayed on the page." }, { "code": null, "e": 26121, "s": 26113, "text": "Syntax:" }, { "code": null, "e": 26150, "s": 26121, "text": "<li *ngFor='condition'></li>" }, { "code": null, "e": 26187, "s": 26150, "text": "NgModule: Module used by NgForOf is:" }, { "code": null, "e": 26200, "s": 26187, "text": "CommonModule" }, { "code": null, "e": 26213, "s": 26202, "text": "Selectors:" }, { "code": null, "e": 26221, "s": 26213, "text": "[ngFor]" }, { "code": null, "e": 26232, "s": 26221, "text": "Approach: " }, { "code": null, "e": 26266, "s": 26232, "text": "Create the angular app to be used" }, { "code": null, "e": 26323, "s": 26266, "text": "There is no need for any import for the NgFor to be used" }, { "code": null, "e": 26393, "s": 26323, "text": "In app.component.ts define the array to be used with ngFor directive." }, { "code": null, "e": 26480, "s": 26393, "text": "In app.component.html use NgFor directive with list element to display array elements." }, { "code": null, "e": 26535, "s": 26480, "text": "serve the angular app using ng serve to see the output" }, { "code": null, "e": 26546, "s": 26535, "text": "Example 1:" }, { "code": null, "e": 26563, "s": 26546, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html',})export class AppComponent { a=['gfg1', 'gfg2', 'gfg3', 'gfg4']}", "e": 26748, "s": 26563, "text": null }, { "code": null, "e": 26767, "s": 26748, "text": "app.component.html" }, { "code": "<ul> <li *ngFor='let i of a'> {{i}} </li></ul>", "e": 26815, "s": 26767, "text": null }, { "code": null, "e": 26823, "s": 26815, "text": "Output:" }, { "code": null, "e": 26834, "s": 26823, "text": "Example 2:" }, { "code": null, "e": 26851, "s": 26834, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html',})export class AppComponent { a=['gfg1', 'gfg2', 'gfg3', 'gfg4']}", "e": 27036, "s": 26851, "text": null }, { "code": null, "e": 27055, "s": 27036, "text": "app.component.html" }, { "code": "<ol> <li *ngFor='let i of a'> {{i}} </li></ol>", "e": 27105, "s": 27055, "text": null }, { "code": null, "e": 27113, "s": 27105, "text": "Output:" }, { "code": null, "e": 27162, "s": 27113, "text": "Reference: https://angular.io/api/common/NgForOf" }, { "code": null, "e": 27172, "s": 27162, "text": "Angular10" }, { "code": null, "e": 27193, "s": 27172, "text": "AngularJS-Directives" }, { "code": null, "e": 27198, "s": 27193, "text": "Misc" }, { "code": null, "e": 27215, "s": 27198, "text": "Web Technologies" }, { "code": null, "e": 27220, "s": 27215, "text": "Misc" }, { "code": null, "e": 27225, "s": 27220, "text": "Misc" }, { "code": null, "e": 27323, "s": 27225, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27344, "s": 27323, "text": "Activation Functions" }, { "code": null, "e": 27382, "s": 27344, "text": "Characteristics of Internet of Things" }, { "code": null, "e": 27418, "s": 27382, "text": "Advantages and Disadvantages of OOP" }, { "code": null, "e": 27453, "s": 27418, "text": "Sensors in Internet of Things(IoT)" }, { "code": null, "e": 27492, "s": 27453, "text": "Challenges in Internet of things (IoT)" }, { "code": null, "e": 27532, "s": 27492, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27565, "s": 27532, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27610, "s": 27565, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27653, "s": 27610, "text": "How to fetch data from an API in ReactJS ?" } ]
Matching of patterns in a String in R Programming - agrep() Function - GeeksforGeeks
14 Apr, 2021 agrep() function in R Language is used to search for approximate matches to pattern within each element of the given string. Syntax: agrep(pattern, x, ignore.case=FALSE, value=FALSE)Parameters:pattern: Specified pattern which is going to be matched with given elements of the string. x: Specified string vector. ignore.case: If its value is TRUE, it ignore case. value: If its value is TRUE, it return the matching elements vector, else return the indices vector. Example 1: Python3 # R program to illustrate# agrep function # Creating string vectorx <- c("GFG", "gfg", "Geeks", "GEEKS") # Calling agrep() functionagrep("gfg", x)agrep("Geeks", x)agrep("gfg", x, ignore.case = TRUE)agrep("Geeks", x, ignore.case = TRUE) Output : [1] 2 [1] 3 [1] 1 2 [1] 3 4 Example 2: Python3 # R program to illustrate# agrep function # Creating string vectorx <- c("GFG", "gfg", "Geeks", "GEEKS") # Calling agrep() functionagrep("gfg", x, ignore.case = TRUE, value = TRUE)agrep("G", x, ignore.case = TRUE, value = TRUE)agrep("Geeks", x, ignore.case = FALSE, value = FALSE)agrep("GEEKS", x, ignore.case = FALSE, value = FALSE) Output: [1] "GFG" "gfg" [1] "GFG" "gfg" "Geeks" "GEEKS" [1] 3 [1] 4 arorakashish0911 R String-Functions R-strings 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 filter R DataFrame by values in a column? How to import an Excel File into R ? Time Series Analysis in R R - if statement How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n14 Apr, 2021" }, { "code": null, "e": 26613, "s": 26487, "text": "agrep() function in R Language is used to search for approximate matches to pattern within each element of the given string. " }, { "code": null, "e": 26954, "s": 26613, "text": "Syntax: agrep(pattern, x, ignore.case=FALSE, value=FALSE)Parameters:pattern: Specified pattern which is going to be matched with given elements of the string. x: Specified string vector. ignore.case: If its value is TRUE, it ignore case. value: If its value is TRUE, it return the matching elements vector, else return the indices vector. " }, { "code": null, "e": 26967, "s": 26954, "text": "Example 1: " }, { "code": null, "e": 26975, "s": 26967, "text": "Python3" }, { "code": "# R program to illustrate# agrep function # Creating string vectorx <- c(\"GFG\", \"gfg\", \"Geeks\", \"GEEKS\") # Calling agrep() functionagrep(\"gfg\", x)agrep(\"Geeks\", x)agrep(\"gfg\", x, ignore.case = TRUE)agrep(\"Geeks\", x, ignore.case = TRUE)", "e": 27211, "s": 26975, "text": null }, { "code": null, "e": 27222, "s": 27211, "text": "Output : " }, { "code": null, "e": 27250, "s": 27222, "text": "[1] 2\n[1] 3\n[1] 1 2\n[1] 3 4" }, { "code": null, "e": 27263, "s": 27250, "text": "Example 2: " }, { "code": null, "e": 27271, "s": 27263, "text": "Python3" }, { "code": "# R program to illustrate# agrep function # Creating string vectorx <- c(\"GFG\", \"gfg\", \"Geeks\", \"GEEKS\") # Calling agrep() functionagrep(\"gfg\", x, ignore.case = TRUE, value = TRUE)agrep(\"G\", x, ignore.case = TRUE, value = TRUE)agrep(\"Geeks\", x, ignore.case = FALSE, value = FALSE)agrep(\"GEEKS\", x, ignore.case = FALSE, value = FALSE) ", "e": 27615, "s": 27271, "text": null }, { "code": null, "e": 27625, "s": 27615, "text": "Output: " }, { "code": null, "e": 27689, "s": 27625, "text": "[1] \"GFG\" \"gfg\"\n[1] \"GFG\" \"gfg\" \"Geeks\" \"GEEKS\"\n[1] 3\n[1] 4" }, { "code": null, "e": 27708, "s": 27691, "text": "arorakashish0911" }, { "code": null, "e": 27727, "s": 27708, "text": "R String-Functions" }, { "code": null, "e": 27737, "s": 27727, "text": "R-strings" }, { "code": null, "e": 27748, "s": 27737, "text": "R Language" }, { "code": null, "e": 27846, "s": 27748, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27898, "s": 27846, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27933, "s": 27898, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27971, "s": 27933, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28029, "s": 27971, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28072, "s": 28029, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28121, "s": 28072, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28158, "s": 28121, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 28184, "s": 28158, "text": "Time Series Analysis in R" }, { "code": null, "e": 28201, "s": 28184, "text": "R - if statement" } ]
Difference Between C Structures and C++ Structures - GeeksforGeeks
02 Mar, 2022 Let’s discuss what are the differences between structures in C and structures in C++? In C++, structures are similar to classes. C Structures C++ Structures Similarities Between the C and C++ Structures Both in C and C++, members of the structure have public visibility by default. Lets discuss some of the above mentioned differences and similarities one by one: 1. Member functions inside the structure: Structures in C cannot have member functions inside a structure but Structures in C++ can have member functions along with data members. C // C Program to Implement Member// functions inside structure #include <stdio.h> struct marks { int num; // Member function inside Structure to // take input and store it in "num" void Set(int temp) { num = temp; } // function used to display the values void display() { printf("%d", num); }}; // Driver Programint main(){ struct marks m1; // calling function inside Struct to // initialize value to num m1.Set(9); // calling function inside struct to // display value of Num m1.display();} Output This will generate an error in C but no error in C++. C++ // C++ Program to Implement Member functions inside// structure #include <iostream>using namespace std; struct marks { int num; // Member function inside Structure to // take input and store it in "num" void Set(int temp) { num = temp; } // function used to display the values void display() { cout << "num=" << num; }}; // Driver Programint main(){ marks m1; // calling function inside Struct to // initialize value to num m1.Set(9); // calling function inside struct to // display value of Num m1.display();} num=9 2. Static Members: C structures cannot have static members but are allowed in C++. C C++ // C program with structure static member struct Record { static int x;}; // Driver programint main() { return 0; } // C++ program with structure static member struct Record { static int x;}; // Driver programint main() { return 0; } This will generate an error in C but not in C++. 3. Constructor creation in structure: Structures in C cannot have a constructor inside a structure but Structures in C++ can have Constructor creation. C C++ // C program to demonstrate that// Constructor is not allowed #include <stdio.h> struct Student { int roll; Student(int x) { roll = x; }}; // Driver Programint main(){ struct Student s(2); printf("%d", s.x); return 0;} // CPP program to initialize data member in c++#include <iostream>using namespace std; struct Student { int roll; Student(int x) { roll = x; }}; // Driver Programint main(){ struct Student s(2); cout << s.roll; return 0;} This will generate an error in C. Output in C++: 2 4. Direct Initialization: We cannot directly initialize structure data members in C but we can do it in C++. C C++ // C program to demonstrate that direct// member initialization is not possible in C #include <stdio.h> struct Record { int x = 7;}; // Driver Programint main(){ struct Record s; printf("%d", s.x); return 0;} // CPP program to initialize data member in c++#include <iostream>using namespace std; struct Record { int x = 7;}; // Driver Programint main(){ Record s; cout << s.x << endl; return 0;} This will generate an error in C. Output in C++: 7 5. Using struct keyword: In C, we need to use a struct to declare a struct variable. In C++, a struct is not necessary. For example, let there be a structure for Record. In C, we must use “struct Record” for Record variables. In C++, we need not use struct, and using ‘Record‘ only would work. 6. Access Modifiers: C structures do not have access modifiers as these modifiers are not supported by the language. C++ structures can have this concept as it is inbuilt in the language. 7. Pointers and References: In C++, there can be both pointers and references to a struct in C++, but only pointers to structs are allowed in C. 8. sizeof operator: This operator will generate 0 for an empty structure in C whereas 1 for an empty structure in C++. C C++ // C program to illustrate empty structure #include <stdio.h> // empty structurestruct Record {}; // Driver Codeint main(){ struct Record s; printf("%lu\n", sizeof(s)); return 0;} // C++ program to illustrate empty structure#include <iostream>using namespace std; // empty structurestruct Record {}; // Driver programint main(){ struct Record s; cout << sizeof(s); return 0;} // This code is contributed by Shubham Sharma Output in C: 0 Output in C++: 1 NOTE: The default type of sizeof is long unsigned int , that’s why “%lu” is used instead of “%d” in printf function. 9. Data Hiding: C structures do not allow the concept of Data hiding but are permitted in C++ as it is an object-oriented language whereas C is not. Related Article: Structure vs Class in C++This article is contributed by Shubham Chaudhary. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. gyanendra371 iamsamyak shubhamsharma8337 w1ckd3 23603vaibhav2021 anshikajain26 Spider_man nehakumariintern cpp-structure C Language C++ Difference Between CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Function Pointer in C Substring in C++ rand() and srand() in C/C++ Vector in C++ STL Inheritance in C++ Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 25661, "s": 25633, "text": "\n02 Mar, 2022" }, { "code": null, "e": 25790, "s": 25661, "text": "Let’s discuss what are the differences between structures in C and structures in C++? In C++, structures are similar to classes." }, { "code": null, "e": 25803, "s": 25790, "text": "C Structures" }, { "code": null, "e": 25818, "s": 25803, "text": "C++ Structures" }, { "code": null, "e": 25864, "s": 25818, "text": "Similarities Between the C and C++ Structures" }, { "code": null, "e": 25943, "s": 25864, "text": "Both in C and C++, members of the structure have public visibility by default." }, { "code": null, "e": 26025, "s": 25943, "text": "Lets discuss some of the above mentioned differences and similarities one by one:" }, { "code": null, "e": 26204, "s": 26025, "text": "1. Member functions inside the structure: Structures in C cannot have member functions inside a structure but Structures in C++ can have member functions along with data members." }, { "code": null, "e": 26206, "s": 26204, "text": "C" }, { "code": "// C Program to Implement Member// functions inside structure #include <stdio.h> struct marks { int num; // Member function inside Structure to // take input and store it in \"num\" void Set(int temp) { num = temp; } // function used to display the values void display() { printf(\"%d\", num); }}; // Driver Programint main(){ struct marks m1; // calling function inside Struct to // initialize value to num m1.Set(9); // calling function inside struct to // display value of Num m1.display();}", "e": 26745, "s": 26206, "text": null }, { "code": null, "e": 26752, "s": 26745, "text": "Output" }, { "code": null, "e": 26807, "s": 26752, "text": "This will generate an error in C but no error in C++. " }, { "code": null, "e": 26811, "s": 26807, "text": "C++" }, { "code": "// C++ Program to Implement Member functions inside// structure #include <iostream>using namespace std; struct marks { int num; // Member function inside Structure to // take input and store it in \"num\" void Set(int temp) { num = temp; } // function used to display the values void display() { cout << \"num=\" << num; }}; // Driver Programint main(){ marks m1; // calling function inside Struct to // initialize value to num m1.Set(9); // calling function inside struct to // display value of Num m1.display();}", "e": 27372, "s": 26811, "text": null }, { "code": null, "e": 27381, "s": 27375, "text": "num=9" }, { "code": null, "e": 27467, "s": 27383, "text": "2. Static Members: C structures cannot have static members but are allowed in C++. " }, { "code": null, "e": 27471, "s": 27469, "text": "C" }, { "code": null, "e": 27475, "s": 27471, "text": "C++" }, { "code": "// C program with structure static member struct Record { static int x;}; // Driver programint main() { return 0; }", "e": 27596, "s": 27475, "text": null }, { "code": "// C++ program with structure static member struct Record { static int x;}; // Driver programint main() { return 0; }", "e": 27719, "s": 27596, "text": null }, { "code": null, "e": 27769, "s": 27719, "text": "This will generate an error in C but not in C++. " }, { "code": null, "e": 27921, "s": 27769, "text": "3. Constructor creation in structure: Structures in C cannot have a constructor inside a structure but Structures in C++ can have Constructor creation." }, { "code": null, "e": 27923, "s": 27921, "text": "C" }, { "code": null, "e": 27927, "s": 27923, "text": "C++" }, { "code": "// C program to demonstrate that// Constructor is not allowed #include <stdio.h> struct Student { int roll; Student(int x) { roll = x; }}; // Driver Programint main(){ struct Student s(2); printf(\"%d\", s.x); return 0;}", "e": 28164, "s": 27927, "text": null }, { "code": "// CPP program to initialize data member in c++#include <iostream>using namespace std; struct Student { int roll; Student(int x) { roll = x; }}; // Driver Programint main(){ struct Student s(2); cout << s.roll; return 0;}", "e": 28403, "s": 28164, "text": null }, { "code": null, "e": 28437, "s": 28403, "text": "This will generate an error in C." }, { "code": null, "e": 28452, "s": 28437, "text": "Output in C++:" }, { "code": null, "e": 28454, "s": 28452, "text": "2" }, { "code": null, "e": 28564, "s": 28454, "text": "4. Direct Initialization: We cannot directly initialize structure data members in C but we can do it in C++. " }, { "code": null, "e": 28566, "s": 28564, "text": "C" }, { "code": null, "e": 28570, "s": 28566, "text": "C++" }, { "code": "// C program to demonstrate that direct// member initialization is not possible in C #include <stdio.h> struct Record { int x = 7;}; // Driver Programint main(){ struct Record s; printf(\"%d\", s.x); return 0;}", "e": 28794, "s": 28570, "text": null }, { "code": "// CPP program to initialize data member in c++#include <iostream>using namespace std; struct Record { int x = 7;}; // Driver Programint main(){ Record s; cout << s.x << endl; return 0;}", "e": 28995, "s": 28794, "text": null }, { "code": null, "e": 29029, "s": 28995, "text": "This will generate an error in C." }, { "code": null, "e": 29045, "s": 29029, "text": "Output in C++: " }, { "code": null, "e": 29047, "s": 29045, "text": "7" }, { "code": null, "e": 29341, "s": 29047, "text": "5. Using struct keyword: In C, we need to use a struct to declare a struct variable. In C++, a struct is not necessary. For example, let there be a structure for Record. In C, we must use “struct Record” for Record variables. In C++, we need not use struct, and using ‘Record‘ only would work." }, { "code": null, "e": 29531, "s": 29341, "text": "6. Access Modifiers: C structures do not have access modifiers as these modifiers are not supported by the language. C++ structures can have this concept as it is inbuilt in the language. " }, { "code": null, "e": 29677, "s": 29531, "text": "7. Pointers and References: In C++, there can be both pointers and references to a struct in C++, but only pointers to structs are allowed in C. " }, { "code": null, "e": 29798, "s": 29677, "text": "8. sizeof operator: This operator will generate 0 for an empty structure in C whereas 1 for an empty structure in C++. " }, { "code": null, "e": 29800, "s": 29798, "text": "C" }, { "code": null, "e": 29804, "s": 29800, "text": "C++" }, { "code": "// C program to illustrate empty structure #include <stdio.h> // empty structurestruct Record {}; // Driver Codeint main(){ struct Record s; printf(\"%lu\\n\", sizeof(s)); return 0;}", "e": 29996, "s": 29804, "text": null }, { "code": "// C++ program to illustrate empty structure#include <iostream>using namespace std; // empty structurestruct Record {}; // Driver programint main(){ struct Record s; cout << sizeof(s); return 0;} // This code is contributed by Shubham Sharma", "e": 30250, "s": 29996, "text": null }, { "code": null, "e": 30264, "s": 30250, "text": "Output in C: " }, { "code": null, "e": 30266, "s": 30264, "text": "0" }, { "code": null, "e": 30282, "s": 30266, "text": "Output in C++: " }, { "code": null, "e": 30284, "s": 30282, "text": "1" }, { "code": null, "e": 30406, "s": 30284, "text": "NOTE: The default type of sizeof is long unsigned int , that’s why “%lu” is used instead of “%d” in printf function." }, { "code": null, "e": 31030, "s": 30406, "text": "9. Data Hiding: C structures do not allow the concept of Data hiding but are permitted in C++ as it is an object-oriented language whereas C is not. Related Article: Structure vs Class in C++This article is contributed by Shubham Chaudhary. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 31043, "s": 31030, "text": "gyanendra371" }, { "code": null, "e": 31053, "s": 31043, "text": "iamsamyak" }, { "code": null, "e": 31071, "s": 31053, "text": "shubhamsharma8337" }, { "code": null, "e": 31078, "s": 31071, "text": "w1ckd3" }, { "code": null, "e": 31095, "s": 31078, "text": "23603vaibhav2021" }, { "code": null, "e": 31109, "s": 31095, "text": "anshikajain26" }, { "code": null, "e": 31120, "s": 31109, "text": "Spider_man" }, { "code": null, "e": 31137, "s": 31120, "text": "nehakumariintern" }, { "code": null, "e": 31151, "s": 31137, "text": "cpp-structure" }, { "code": null, "e": 31162, "s": 31151, "text": "C Language" }, { "code": null, "e": 31166, "s": 31162, "text": "C++" }, { "code": null, "e": 31185, "s": 31166, "text": "Difference Between" }, { "code": null, "e": 31189, "s": 31185, "text": "CPP" }, { "code": null, "e": 31287, "s": 31189, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31322, "s": 31287, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 31368, "s": 31322, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 31390, "s": 31368, "text": "Function Pointer in C" }, { "code": null, "e": 31407, "s": 31390, "text": "Substring in C++" }, { "code": null, "e": 31435, "s": 31407, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 31453, "s": 31435, "text": "Vector in C++ STL" }, { "code": null, "e": 31472, "s": 31453, "text": "Inheritance in C++" }, { "code": null, "e": 31518, "s": 31472, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 31561, "s": 31518, "text": "Map in C++ Standard Template Library (STL)" } ]
Python - Split in Nested tuples - GeeksforGeeks
03 Jul, 2020 Sometimes, while working with Python tuples, we can have a problem in which we need to perform split of elements in nested tuple, by a certain delimiter. This kind of problem can have application in different data domains. Let’s discuss certain ways in which this task can be performed. Input : test_list = [(3, (‘Gfg’, ‘best’, 6)), (10, (‘CS’, ‘good’, 9))]Output : [[3, ‘Gfg’, ‘best’, 6], [10, ‘CS’, ‘good’, 9]] Input : test_list = [(3, (1, 2, 3, 6))]Output : [[3, 1, 2, 3, 6]] Method #1 : Using list comprehension + unpack operator(*)The combination of above functions can be used to solve this problem. In this, we perform the task of unpacking the elements by delimiter using * operator and list comprehension to iterate and form pairs. # Python3 code to demonstrate working of # Split in Nested tuples# Using list comprehension + unpack operator # initializing listtest_list = [(3, ('Gfg', 'best')), (10, ('CS', 'good')), (7, ('Gfg', 'better'))] # printing original listprint("The original list is : " + str(test_list)) # Split in Nested tuples# Using list comprehension + unpack operatorres = [[a, *b] for a, b in test_list] # printing result print("The splitted elements : " + str(res)) The original list is : [(3, ('Gfg', 'best')), (10, ('CS', 'good')), (7, ('Gfg', 'better'))] The splitted elements : [[3, 'Gfg', 'best'], [10, 'CS', 'good'], [7, 'Gfg', 'better']] Method #2 : Using map() + list()The combination of above functions can be used to solve this problem. In this, we perform task of extending logic to each elements using map() and list() is used to pack the strings to different containers. # Python3 code to demonstrate working of # Split in Nested tuples# map() + list() # initializing listtest_list = [(3, ('Gfg', 'best')), (10, ('CS', 'good')), (7, ('Gfg', 'better'))] # printing original listprint("The original list is : " + str(test_list)) # Split in Nested tuples# map() + list()res = []for sub in test_list: res.append(list(map(str, (*[sub[0]], *[*sub[1]])))) # printing result print("The splitted elements : " + str(res)) The original list is : [(3, ('Gfg', 'best')), (10, ('CS', 'good')), (7, ('Gfg', 'better'))] The splitted elements : [[3, 'Gfg', 'best'], [10, 'CS', 'good'], [7, 'Gfg', 'better']] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n03 Jul, 2020" }, { "code": null, "e": 25824, "s": 25537, "text": "Sometimes, while working with Python tuples, we can have a problem in which we need to perform split of elements in nested tuple, by a certain delimiter. This kind of problem can have application in different data domains. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 25950, "s": 25824, "text": "Input : test_list = [(3, (‘Gfg’, ‘best’, 6)), (10, (‘CS’, ‘good’, 9))]Output : [[3, ‘Gfg’, ‘best’, 6], [10, ‘CS’, ‘good’, 9]]" }, { "code": null, "e": 26016, "s": 25950, "text": "Input : test_list = [(3, (1, 2, 3, 6))]Output : [[3, 1, 2, 3, 6]]" }, { "code": null, "e": 26278, "s": 26016, "text": "Method #1 : Using list comprehension + unpack operator(*)The combination of above functions can be used to solve this problem. In this, we perform the task of unpacking the elements by delimiter using * operator and list comprehension to iterate and form pairs." }, { "code": "# Python3 code to demonstrate working of # Split in Nested tuples# Using list comprehension + unpack operator # initializing listtest_list = [(3, ('Gfg', 'best')), (10, ('CS', 'good')), (7, ('Gfg', 'better'))] # printing original listprint(\"The original list is : \" + str(test_list)) # Split in Nested tuples# Using list comprehension + unpack operatorres = [[a, *b] for a, b in test_list] # printing result print(\"The splitted elements : \" + str(res)) ", "e": 26736, "s": 26278, "text": null }, { "code": null, "e": 26916, "s": 26736, "text": "The original list is : [(3, ('Gfg', 'best')), (10, ('CS', 'good')), (7, ('Gfg', 'better'))]\nThe splitted elements : [[3, 'Gfg', 'best'], [10, 'CS', 'good'], [7, 'Gfg', 'better']]\n" }, { "code": null, "e": 27157, "s": 26918, "text": "Method #2 : Using map() + list()The combination of above functions can be used to solve this problem. In this, we perform task of extending logic to each elements using map() and list() is used to pack the strings to different containers." }, { "code": "# Python3 code to demonstrate working of # Split in Nested tuples# map() + list() # initializing listtest_list = [(3, ('Gfg', 'best')), (10, ('CS', 'good')), (7, ('Gfg', 'better'))] # printing original listprint(\"The original list is : \" + str(test_list)) # Split in Nested tuples# map() + list()res = []for sub in test_list: res.append(list(map(str, (*[sub[0]], *[*sub[1]])))) # printing result print(\"The splitted elements : \" + str(res)) ", "e": 27606, "s": 27157, "text": null }, { "code": null, "e": 27786, "s": 27606, "text": "The original list is : [(3, ('Gfg', 'best')), (10, ('CS', 'good')), (7, ('Gfg', 'better'))]\nThe splitted elements : [[3, 'Gfg', 'best'], [10, 'CS', 'good'], [7, 'Gfg', 'better']]\n" }, { "code": null, "e": 27807, "s": 27786, "text": "Python list-programs" }, { "code": null, "e": 27814, "s": 27807, "text": "Python" }, { "code": null, "e": 27830, "s": 27814, "text": "Python Programs" }, { "code": null, "e": 27928, "s": 27830, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27960, "s": 27928, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28002, "s": 27960, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28044, "s": 28002, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28071, "s": 28044, "text": "Python Classes and Objects" }, { "code": null, "e": 28127, "s": 28071, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28149, "s": 28127, "text": "Defaultdict in Python" }, { "code": null, "e": 28188, "s": 28149, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28234, "s": 28188, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28272, "s": 28234, "text": "Python | Convert a list to dictionary" } ]
AngularJS $location Service - GeeksforGeeks
11 Jun, 2021 The $location in AngularJS basically uses window.location service. The $location is used to read or change the URL in the browser and it is used to reflect that URL on our page. Any change made in the URL is stored in the $location service in the AngularJS. There are various methods in the $location service such as absUrl(), url([URL]), protocol(), host(), port(), path([path]), search(search, [paramValue]), hash([hash]), replace(), and state([state]). Also, there are two events available i.e. $locationChangeStart and $locationChangeSuccess. Now let us see some methods one by one of $location service. 1. absUrl() Method: It returns the full path of your page and it is a read-only method. HTML <!DOCTYPE html><html> <head> <title>$location service</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body ng-app="locationService"> <h4>Click on the button to see the current URL</h4> <div ng-controller="locationServiceController"> <button ng-click="seeURL()">See URL</button> <p>Current URL is :: {{currentURL}}</p> </div> <script> var app = angular.module('locationService', []); app.controller('locationServiceController', ['$scope', '$location', function ($scope, $location) { $scope.seeURL = function () { $scope.currentURL = $location.absUrl(); } }]); </script></body> </html> Output: 2. port() Method: It is also a read-only method that returns the port number in which you are currently working. HTML <!DOCTYPE html><html> <head> <title>$location service</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body ng-app="locationService"> <h4> Click on the button to see the current PORT number </h4> <div ng-controller="locationServiceController"> <button ng-click="seePort()">See Port Number</button> <p>Current Port number is :: {{currentPort}}</p> </div> <script> var app = angular.module('locationService', []); app.controller('locationServiceController', ['$scope', '$location', function ($scope, $location) { $scope.seePort = function () { $scope.currentPort = $location.port(); } }]); </script></body> </html> Output: 3. protocol() Method: It returns the current protocol of the current URL and it is also a read-only method. HTML <!DOCTYPE html><html> <head> <title>$location service</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body ng-app="locationService"> <h4>Click on the button to see the current Protocol</h4> <div ng-controller="locationServiceController"> <button ng-click="seeProtocol()">See Protocol</button> <p>Current Protocol is :: {{currentProtocol}}</p> </div> <script> var app = angular.module('locationService', []); app.controller('locationServiceController', ['$scope', '$location', function ($scope, $location) { $scope.seeProtocol = function () { $scope.currentProtocol = $location.protocol(); } }]); </script> </body> </html> Output: 4. host() Method: It returns the current host of the current URL and also it is a read-only method. HTML <!DOCTYPE html><html> <head> <title>$location service</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body ng-app="locationService"> <h4>Click on the button to see the current Host</h4> <div ng-controller="locationServiceController"> <button ng-click="seeHost()">See Host</button> <p>Current Host is :: {{currentHost}}</p> </div> <script> var app = angular.module('locationService', []); app.controller('locationServiceController', ['$scope', '$location', function ($scope, $location) { $scope.seeHost = function () { $scope.currentHost = $location.host(); } }]); </script></body> </html> Output: 5. search() Method: It is a read and writes method of $location. It returns the current search parameters of the URL when passed without parameters and when passed with parameters it returns $location object. HTML <!DOCTYPE html><html> <head> <title>$location service</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body ng-app="locationService"> <h4>Click on the button to see the current Search</h4> <div ng-controller="locationServiceController"> <button ng-click="seeSearch()">See Search</button> <p>Current Search is :: {{currentSearch}}</p> </div> <script> var app = angular.module('locationService', []); app.controller('locationServiceController', ['$scope', '$location', function ($scope, $location) { $scope.seeSearch = function () { $location.search("website", "GeeksForGeeks"); $scope.currentSearch = $location.search(); } }]); </script></body> </html> Output: 6. hash() Method: It is a read and writes method of $location service. It returns the current hash value of the current URL when called without parameters and when called with parameters it returns the$location object. HTML <!DOCTYPE html><html> <head> <title>$location service</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body ng-app="locationService"> <h4>Click on the button to see the current Hash Value</h4> <div ng-controller="locationServiceController"> <button ng-click="seeHash()">See Hash</button> <p>Current Hash Value is :: {{currentHash}}</p> </div> <script> var app = angular.module('locationService', []); app.controller('locationServiceController', ['$scope', '$location', function ($scope, $location) { $scope.seeHash = function () { $location.hash("geeks"); $scope.currentHash = $location.hash(); } }]); </script></body> </html> Output: AngularJS-API AngularJS-Directives Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event Angular PrimeNG Messages Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26354, "s": 26326, "text": "\n11 Jun, 2021" }, { "code": null, "e": 26901, "s": 26354, "text": "The $location in AngularJS basically uses window.location service. The $location is used to read or change the URL in the browser and it is used to reflect that URL on our page. Any change made in the URL is stored in the $location service in the AngularJS. There are various methods in the $location service such as absUrl(), url([URL]), protocol(), host(), port(), path([path]), search(search, [paramValue]), hash([hash]), replace(), and state([state]). Also, there are two events available i.e. $locationChangeStart and $locationChangeSuccess." }, { "code": null, "e": 26962, "s": 26901, "text": "Now let us see some methods one by one of $location service." }, { "code": null, "e": 27050, "s": 26962, "text": "1. absUrl() Method: It returns the full path of your page and it is a read-only method." }, { "code": null, "e": 27055, "s": 27050, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>$location service</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body ng-app=\"locationService\"> <h4>Click on the button to see the current URL</h4> <div ng-controller=\"locationServiceController\"> <button ng-click=\"seeURL()\">See URL</button> <p>Current URL is :: {{currentURL}}</p> </div> <script> var app = angular.module('locationService', []); app.controller('locationServiceController', ['$scope', '$location', function ($scope, $location) { $scope.seeURL = function () { $scope.currentURL = $location.absUrl(); } }]); </script></body> </html>", "e": 27831, "s": 27055, "text": null }, { "code": null, "e": 27839, "s": 27831, "text": "Output:" }, { "code": null, "e": 27952, "s": 27839, "text": "2. port() Method: It is also a read-only method that returns the port number in which you are currently working." }, { "code": null, "e": 27957, "s": 27952, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>$location service</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body ng-app=\"locationService\"> <h4> Click on the button to see the current PORT number </h4> <div ng-controller=\"locationServiceController\"> <button ng-click=\"seePort()\">See Port Number</button> <p>Current Port number is :: {{currentPort}}</p> </div> <script> var app = angular.module('locationService', []); app.controller('locationServiceController', ['$scope', '$location', function ($scope, $location) { $scope.seePort = function () { $scope.currentPort = $location.port(); } }]); </script></body> </html>", "e": 28810, "s": 27957, "text": null }, { "code": null, "e": 28818, "s": 28810, "text": "Output:" }, { "code": null, "e": 28926, "s": 28818, "text": "3. protocol() Method: It returns the current protocol of the current URL and it is also a read-only method." }, { "code": null, "e": 28931, "s": 28926, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>$location service</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body ng-app=\"locationService\"> <h4>Click on the button to see the current Protocol</h4> <div ng-controller=\"locationServiceController\"> <button ng-click=\"seeProtocol()\">See Protocol</button> <p>Current Protocol is :: {{currentProtocol}}</p> </div> <script> var app = angular.module('locationService', []); app.controller('locationServiceController', ['$scope', '$location', function ($scope, $location) { $scope.seeProtocol = function () { $scope.currentProtocol = $location.protocol(); } }]); </script> </body> </html>", "e": 29807, "s": 28931, "text": null }, { "code": null, "e": 29815, "s": 29807, "text": "Output:" }, { "code": null, "e": 29915, "s": 29815, "text": "4. host() Method: It returns the current host of the current URL and also it is a read-only method." }, { "code": null, "e": 29920, "s": 29915, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>$location service</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body ng-app=\"locationService\"> <h4>Click on the button to see the current Host</h4> <div ng-controller=\"locationServiceController\"> <button ng-click=\"seeHost()\">See Host</button> <p>Current Host is :: {{currentHost}}</p> </div> <script> var app = angular.module('locationService', []); app.controller('locationServiceController', ['$scope', '$location', function ($scope, $location) { $scope.seeHost = function () { $scope.currentHost = $location.host(); } }]); </script></body> </html>", "e": 30701, "s": 29920, "text": null }, { "code": null, "e": 30709, "s": 30701, "text": "Output:" }, { "code": null, "e": 30918, "s": 30709, "text": "5. search() Method: It is a read and writes method of $location. It returns the current search parameters of the URL when passed without parameters and when passed with parameters it returns $location object." }, { "code": null, "e": 30923, "s": 30918, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>$location service</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body ng-app=\"locationService\"> <h4>Click on the button to see the current Search</h4> <div ng-controller=\"locationServiceController\"> <button ng-click=\"seeSearch()\">See Search</button> <p>Current Search is :: {{currentSearch}}</p> </div> <script> var app = angular.module('locationService', []); app.controller('locationServiceController', ['$scope', '$location', function ($scope, $location) { $scope.seeSearch = function () { $location.search(\"website\", \"GeeksForGeeks\"); $scope.currentSearch = $location.search(); } }]); </script></body> </html>", "e": 31785, "s": 30923, "text": null }, { "code": null, "e": 31793, "s": 31785, "text": "Output:" }, { "code": null, "e": 32012, "s": 31793, "text": "6. hash() Method: It is a read and writes method of $location service. It returns the current hash value of the current URL when called without parameters and when called with parameters it returns the$location object." }, { "code": null, "e": 32017, "s": 32012, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>$location service</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body ng-app=\"locationService\"> <h4>Click on the button to see the current Hash Value</h4> <div ng-controller=\"locationServiceController\"> <button ng-click=\"seeHash()\">See Hash</button> <p>Current Hash Value is :: {{currentHash}}</p> </div> <script> var app = angular.module('locationService', []); app.controller('locationServiceController', ['$scope', '$location', function ($scope, $location) { $scope.seeHash = function () { $location.hash(\"geeks\"); $scope.currentHash = $location.hash(); } }]); </script></body> </html>", "e": 32854, "s": 32017, "text": null }, { "code": null, "e": 32862, "s": 32854, "text": "Output:" }, { "code": null, "e": 32876, "s": 32862, "text": "AngularJS-API" }, { "code": null, "e": 32897, "s": 32876, "text": "AngularJS-Directives" }, { "code": null, "e": 32904, "s": 32897, "text": "Picked" }, { "code": null, "e": 32914, "s": 32904, "text": "AngularJS" }, { "code": null, "e": 32931, "s": 32914, "text": "Web Technologies" }, { "code": null, "e": 33029, "s": 32931, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33064, "s": 33029, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 33099, "s": 33064, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 33123, "s": 33099, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 33158, "s": 33123, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 33211, "s": 33158, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 33251, "s": 33211, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33284, "s": 33251, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33329, "s": 33284, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33372, "s": 33329, "text": "How to fetch data from an API in ReactJS ?" } ]
Domino and Tromino tiling problem - GeeksforGeeks
05 Aug, 2021 Given a positive integer N, the task is to find the number of ways to fill the board of dimension 2*N with a tile of dimensions 2 × 1, 1 × 2, (also known as domino) and an ‘L‘ shaped tile(also know as tromino) show below that can be rotated by 90 degrees. The L shape tile: XX X After rotating L shape tile by 90: XX X or X XX Examples: Input: N = 3Output: 5Explanation:Below is the image to illustrate all the combinations: Input: N = 1Output: 1 Approach: The given problem can be solved based on the following observations by: Let’s define a 2 state, dynamic programming say dp[i, j] denoting one of the following arrangements in column index i. The current column can be filled with 1, 2 × 1 dominos in state 0, if the previous column had state 0. The current column can be filled with 2, 1 × 2 dominos horizontally in state 0, if the i – 2 column has state 0. The current column can be filled with an ‘L‘ shaped domino in state 1 and state 2, if the previous column had state 0. The current column can be filled with 1 × 2 shaped domino in state 1 if the previous column has state 2 or in state 2 if the previous column has state 1. Therefore, the transition of the state can be defined as the following:dp[i][0] = (dp[i – 1][0] + dp[i – 2][0]+ dp[i – 2][1] + dp[i – 2][2]).dp[i][1] = dp[i – 1][0] + dp[i – 1][2].dp[i][2] = dp[i – 1][0] + dp[i – 1][1]. dp[i][0] = (dp[i – 1][0] + dp[i – 2][0]+ dp[i – 2][1] + dp[i – 2][2]).dp[i][1] = dp[i – 1][0] + dp[i – 1][2].dp[i][2] = dp[i – 1][0] + dp[i – 1][1]. dp[i][0] = (dp[i – 1][0] + dp[i – 2][0]+ dp[i – 2][1] + dp[i – 2][2]). dp[i][1] = dp[i – 1][0] + dp[i – 1][2]. dp[i][2] = dp[i – 1][0] + dp[i – 1][1]. Based on the above observations, follow the steps below to solve the problem: If the value of N is less than 3, then print N as the total number of ways. Initialize a 2-dimensional array, say dp[][3] that stores all the states of the dp. Consider the Base Case: dp[0][0] = dp[1][0] = dp[1][1] = dp[1][2] = 1. Iterate over the given range [2, N] and using the variable i and perform the following transitions in the dp as:dp[i][0] equals (dp[i – 1][0] + dp[i – 2][0]+ dp[i – 2][1] + dp[i – 2][2]).dp[i][1] equals dp[i – 1][0] + dp[i – 1][2].dp[i][2] equals dp[i – 1][0] + dp[i – 1][1]. dp[i][0] equals (dp[i – 1][0] + dp[i – 2][0]+ dp[i – 2][1] + dp[i – 2][2]). dp[i][1] equals dp[i – 1][0] + dp[i – 1][2]. dp[i][2] equals dp[i – 1][0] + dp[i – 1][1]. After completing the above steps, print the total number of ways stored in dp[N][0]. 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;const long long MOD = 1e9 + 7; // Function to find the total number// of ways to tile a 2*N board using// the given types of tileint numTilings(int N){ // If N is less than 3 if (N < 3) { return N; } // Store all dp-states vector<vector<long long> > dp( N + 1, vector<long long>(3, 0)); // Base Case dp[0][0] = dp[1][0] = 1; dp[1][1] = dp[1][2] = 1; // Traverse the range [2, N] for (int i = 2; i <= N; i++) { // Update the value of dp[i][0] dp[i][0] = (dp[i - 1][0] + dp[i - 2][0] + dp[i - 2][1] + dp[i - 2][2]) % MOD; // Update the value of dp[i][1] dp[i][1] = (dp[i - 1][0] + dp[i - 1][2]) % MOD; // Update the value of dp[i][2] dp[i][2] = (dp[i - 1][0] + dp[i - 1][1]) % MOD; } // Return the number of ways as // the value of dp[N][0] return dp[N][0];} // Driver Codeint main(){ int N = 3; cout << numTilings(N); return 0;} // Java program for the above approachimport java.util.Arrays; class GFG{ public static long MOD = 1000000007l; // Function to find the total number// of ways to tile a 2*N board using// the given types of tilepublic static long numTilings(int N){ // If N is less than 3 if (N < 3) { return N; } // Store all dp-states long[][] dp = new long[N + 1][3]; for(long[] row : dp) { Arrays.fill(row, 0); } // Base Case dp[0][0] = dp[1][0] = 1; dp[1][1] = dp[1][2] = 1; // Traverse the range [2, N] for(int i = 2; i <= N; i++) { // Update the value of dp[i][0] dp[i][0] = (dp[i - 1][0] + dp[i - 2][0] + dp[i - 2][1] + dp[i - 2][2]) % MOD; // Update the value of dp[i][1] dp[i][1] = (dp[i - 1][0] + dp[i - 1][2]) % MOD; // Update the value of dp[i][2] dp[i][2] = (dp[i - 1][0] + dp[i - 1][1]) % MOD; } // Return the number of ways as // the value of dp[N][0] return dp[N][0];} // Driver Codepublic static void main(String args[]){ int N = 3; System.out.println(numTilings(N));}} // This code is contributed by gfgking # Python3 program for the above approache9 + 7; # Function to find the total number# of ways to tile a 2*N board using# the given types of tileMOD = 1e9 + 7 def numTilings(N): # If N is less than 3 if (N < 3): return N # Store all dp-states dp = [[0] * 3 for i in range(N + 1)] # Base Case dp[0][0] = dp[1][0] = 1 dp[1][1] = dp[1][2] = 1 # Traverse the range [2, N] for i in range(2, N + 1): # Update the value of dp[i][0] dp[i][0] = (dp[i - 1][0] + dp[i - 2][0] + dp[i - 2][1] + dp[i - 2][2]) % MOD # Update the value of dp[i][1] dp[i][1] = (dp[i - 1][0] + dp[i - 1][2]) % MOD # Update the value of dp[i][2] dp[i][2] = (dp[i - 1][0] + dp[i - 1][1]) % MOD # Return the number of ways as # the value of dp[N][0] return int(dp[N][0]) # Driver CodeN = 3 print(numTilings(N)) # This code is contributed by gfgking // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ static int MOD = 1000000007; // Function to find the total number// of ways to tile a 2*N board using// the given types of tilestatic int numTilings(int N){ // If N is less than 3 if (N < 3) { return N; } // Store all dp-states int [,]dp = new int[N+1,3]; // Base Case dp[0,0] = dp[1,0] = 1; dp[1,1] = dp[1,2] = 1; // Traverse the range [2, N] for (int i = 2; i <= N; i++) { // Update the value of dp[i,0] dp[i,0] = (dp[i - 1,0] + dp[i - 2,0] + dp[i - 2,1] + dp[i - 2,2]) % MOD; // Update the value of dp[i,1] dp[i,1] = (dp[i - 1,0] + dp[i - 1,2]) % MOD; // Update the value of dp[i,2] dp[i,2] = (dp[i - 1,0] + dp[i - 1,1]) % MOD; } // Return the number of ways as // the value of dp[N,0] return dp[N,0];} // Driver Codepublic static void Main(){ int N = 3; Console.Write(numTilings(N));}} // This code is contributed by SURENDRA_GANGWAR. <script> // JavaScript program for the above approache9 + 7; // Function to find the total number // of ways to tile a 2*N board using // the given types of tile const MOD = 1e9 + 7; function numTilings(N) { // If N is less than 3 if (N < 3) { return N; } // Store all dp-states let dp = Array(N + 1).fill().map(() => Array(3).fill(0)) // Base Case dp[0][0] = dp[1][0] = 1; dp[1][1] = dp[1][2] = 1; // Traverse the range [2, N] for (let i = 2; i <= N; i++) { // Update the value of dp[i][0] dp[i][0] = (dp[i - 1][0] + dp[i - 2][0] + dp[i - 2][1] + dp[i - 2][2]) % MOD; // Update the value of dp[i][1] dp[i][1] = (dp[i - 1][0] + dp[i - 1][2]) % MOD; // Update the value of dp[i][2] dp[i][2] = (dp[i - 1][0] + dp[i - 1][1]) % MOD; } // Return the number of ways as // the value of dp[N][0] return dp[N][0]; } // Driver Code let N = 3; document.write(numTilings(N)); // This code is contributed by Potta Lokesh </script> 5 Time Complexity: O(N)Auxiliary Space: O(N) lokeshpotta20 gfgking SURENDRA_GANGWAR Google Dynamic Programming Google Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum size square sub-matrix with all 1s Optimal Substructure Property in Dynamic Programming | DP-2 Min Cost Path | DP-6 Optimal Binary Search Tree | DP-24 Box Stacking Problem | DP-22 Maximum Subarray Sum using Divide and Conquer algorithm Greedy approach vs Dynamic programming Maximum sum such that no two elements are adjacent Word Break Problem | DP-32 Top 50 Dynamic Programming Coding Problems for Interviews
[ { "code": null, "e": 25941, "s": 25913, "text": "\n05 Aug, 2021" }, { "code": null, "e": 26197, "s": 25941, "text": "Given a positive integer N, the task is to find the number of ways to fill the board of dimension 2*N with a tile of dimensions 2 × 1, 1 × 2, (also known as domino) and an ‘L‘ shaped tile(also know as tromino) show below that can be rotated by 90 degrees." }, { "code": null, "e": 26271, "s": 26197, "text": "The L shape tile:\n\nXX\nX\nAfter rotating L shape tile by 90:\n\nXX\n X\nor\nX\nXX" }, { "code": null, "e": 26281, "s": 26271, "text": "Examples:" }, { "code": null, "e": 26369, "s": 26281, "text": "Input: N = 3Output: 5Explanation:Below is the image to illustrate all the combinations:" }, { "code": null, "e": 26391, "s": 26369, "text": "Input: N = 1Output: 1" }, { "code": null, "e": 26473, "s": 26391, "text": "Approach: The given problem can be solved based on the following observations by:" }, { "code": null, "e": 26592, "s": 26473, "text": "Let’s define a 2 state, dynamic programming say dp[i, j] denoting one of the following arrangements in column index i." }, { "code": null, "e": 26695, "s": 26592, "text": "The current column can be filled with 1, 2 × 1 dominos in state 0, if the previous column had state 0." }, { "code": null, "e": 26808, "s": 26695, "text": "The current column can be filled with 2, 1 × 2 dominos horizontally in state 0, if the i – 2 column has state 0." }, { "code": null, "e": 26927, "s": 26808, "text": "The current column can be filled with an ‘L‘ shaped domino in state 1 and state 2, if the previous column had state 0." }, { "code": null, "e": 27081, "s": 26927, "text": "The current column can be filled with 1 × 2 shaped domino in state 1 if the previous column has state 2 or in state 2 if the previous column has state 1." }, { "code": null, "e": 27301, "s": 27081, "text": "Therefore, the transition of the state can be defined as the following:dp[i][0] = (dp[i – 1][0] + dp[i – 2][0]+ dp[i – 2][1] + dp[i – 2][2]).dp[i][1] = dp[i – 1][0] + dp[i – 1][2].dp[i][2] = dp[i – 1][0] + dp[i – 1][1]." }, { "code": null, "e": 27450, "s": 27301, "text": "dp[i][0] = (dp[i – 1][0] + dp[i – 2][0]+ dp[i – 2][1] + dp[i – 2][2]).dp[i][1] = dp[i – 1][0] + dp[i – 1][2].dp[i][2] = dp[i – 1][0] + dp[i – 1][1]." }, { "code": null, "e": 27521, "s": 27450, "text": "dp[i][0] = (dp[i – 1][0] + dp[i – 2][0]+ dp[i – 2][1] + dp[i – 2][2])." }, { "code": null, "e": 27561, "s": 27521, "text": "dp[i][1] = dp[i – 1][0] + dp[i – 1][2]." }, { "code": null, "e": 27601, "s": 27561, "text": "dp[i][2] = dp[i – 1][0] + dp[i – 1][1]." }, { "code": null, "e": 27679, "s": 27601, "text": "Based on the above observations, follow the steps below to solve the problem:" }, { "code": null, "e": 27755, "s": 27679, "text": "If the value of N is less than 3, then print N as the total number of ways." }, { "code": null, "e": 27839, "s": 27755, "text": "Initialize a 2-dimensional array, say dp[][3] that stores all the states of the dp." }, { "code": null, "e": 27910, "s": 27839, "text": "Consider the Base Case: dp[0][0] = dp[1][0] = dp[1][1] = dp[1][2] = 1." }, { "code": null, "e": 28186, "s": 27910, "text": "Iterate over the given range [2, N] and using the variable i and perform the following transitions in the dp as:dp[i][0] equals (dp[i – 1][0] + dp[i – 2][0]+ dp[i – 2][1] + dp[i – 2][2]).dp[i][1] equals dp[i – 1][0] + dp[i – 1][2].dp[i][2] equals dp[i – 1][0] + dp[i – 1][1]." }, { "code": null, "e": 28262, "s": 28186, "text": "dp[i][0] equals (dp[i – 1][0] + dp[i – 2][0]+ dp[i – 2][1] + dp[i – 2][2])." }, { "code": null, "e": 28307, "s": 28262, "text": "dp[i][1] equals dp[i – 1][0] + dp[i – 1][2]." }, { "code": null, "e": 28352, "s": 28307, "text": "dp[i][2] equals dp[i – 1][0] + dp[i – 1][1]." }, { "code": null, "e": 28437, "s": 28352, "text": "After completing the above steps, print the total number of ways stored in dp[N][0]." }, { "code": null, "e": 28488, "s": 28437, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28492, "s": 28488, "text": "C++" }, { "code": null, "e": 28497, "s": 28492, "text": "Java" }, { "code": null, "e": 28505, "s": 28497, "text": "Python3" }, { "code": null, "e": 28508, "s": 28505, "text": "C#" }, { "code": null, "e": 28519, "s": 28508, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std;const long long MOD = 1e9 + 7; // Function to find the total number// of ways to tile a 2*N board using// the given types of tileint numTilings(int N){ // If N is less than 3 if (N < 3) { return N; } // Store all dp-states vector<vector<long long> > dp( N + 1, vector<long long>(3, 0)); // Base Case dp[0][0] = dp[1][0] = 1; dp[1][1] = dp[1][2] = 1; // Traverse the range [2, N] for (int i = 2; i <= N; i++) { // Update the value of dp[i][0] dp[i][0] = (dp[i - 1][0] + dp[i - 2][0] + dp[i - 2][1] + dp[i - 2][2]) % MOD; // Update the value of dp[i][1] dp[i][1] = (dp[i - 1][0] + dp[i - 1][2]) % MOD; // Update the value of dp[i][2] dp[i][2] = (dp[i - 1][0] + dp[i - 1][1]) % MOD; } // Return the number of ways as // the value of dp[N][0] return dp[N][0];} // Driver Codeint main(){ int N = 3; cout << numTilings(N); return 0;}", "e": 29693, "s": 28519, "text": null }, { "code": "// Java program for the above approachimport java.util.Arrays; class GFG{ public static long MOD = 1000000007l; // Function to find the total number// of ways to tile a 2*N board using// the given types of tilepublic static long numTilings(int N){ // If N is less than 3 if (N < 3) { return N; } // Store all dp-states long[][] dp = new long[N + 1][3]; for(long[] row : dp) { Arrays.fill(row, 0); } // Base Case dp[0][0] = dp[1][0] = 1; dp[1][1] = dp[1][2] = 1; // Traverse the range [2, N] for(int i = 2; i <= N; i++) { // Update the value of dp[i][0] dp[i][0] = (dp[i - 1][0] + dp[i - 2][0] + dp[i - 2][1] + dp[i - 2][2]) % MOD; // Update the value of dp[i][1] dp[i][1] = (dp[i - 1][0] + dp[i - 1][2]) % MOD; // Update the value of dp[i][2] dp[i][2] = (dp[i - 1][0] + dp[i - 1][1]) % MOD; } // Return the number of ways as // the value of dp[N][0] return dp[N][0];} // Driver Codepublic static void main(String args[]){ int N = 3; System.out.println(numTilings(N));}} // This code is contributed by gfgking", "e": 30870, "s": 29693, "text": null }, { "code": "# Python3 program for the above approache9 + 7; # Function to find the total number# of ways to tile a 2*N board using# the given types of tileMOD = 1e9 + 7 def numTilings(N): # If N is less than 3 if (N < 3): return N # Store all dp-states dp = [[0] * 3 for i in range(N + 1)] # Base Case dp[0][0] = dp[1][0] = 1 dp[1][1] = dp[1][2] = 1 # Traverse the range [2, N] for i in range(2, N + 1): # Update the value of dp[i][0] dp[i][0] = (dp[i - 1][0] + dp[i - 2][0] + dp[i - 2][1] + dp[i - 2][2]) % MOD # Update the value of dp[i][1] dp[i][1] = (dp[i - 1][0] + dp[i - 1][2]) % MOD # Update the value of dp[i][2] dp[i][2] = (dp[i - 1][0] + dp[i - 1][1]) % MOD # Return the number of ways as # the value of dp[N][0] return int(dp[N][0]) # Driver CodeN = 3 print(numTilings(N)) # This code is contributed by gfgking", "e": 31872, "s": 30870, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ static int MOD = 1000000007; // Function to find the total number// of ways to tile a 2*N board using// the given types of tilestatic int numTilings(int N){ // If N is less than 3 if (N < 3) { return N; } // Store all dp-states int [,]dp = new int[N+1,3]; // Base Case dp[0,0] = dp[1,0] = 1; dp[1,1] = dp[1,2] = 1; // Traverse the range [2, N] for (int i = 2; i <= N; i++) { // Update the value of dp[i,0] dp[i,0] = (dp[i - 1,0] + dp[i - 2,0] + dp[i - 2,1] + dp[i - 2,2]) % MOD; // Update the value of dp[i,1] dp[i,1] = (dp[i - 1,0] + dp[i - 1,2]) % MOD; // Update the value of dp[i,2] dp[i,2] = (dp[i - 1,0] + dp[i - 1,1]) % MOD; } // Return the number of ways as // the value of dp[N,0] return dp[N,0];} // Driver Codepublic static void Main(){ int N = 3; Console.Write(numTilings(N));}} // This code is contributed by SURENDRA_GANGWAR.", "e": 33058, "s": 31872, "text": null }, { "code": "<script> // JavaScript program for the above approache9 + 7; // Function to find the total number // of ways to tile a 2*N board using // the given types of tile const MOD = 1e9 + 7; function numTilings(N) { // If N is less than 3 if (N < 3) { return N; } // Store all dp-states let dp = Array(N + 1).fill().map(() => Array(3).fill(0)) // Base Case dp[0][0] = dp[1][0] = 1; dp[1][1] = dp[1][2] = 1; // Traverse the range [2, N] for (let i = 2; i <= N; i++) { // Update the value of dp[i][0] dp[i][0] = (dp[i - 1][0] + dp[i - 2][0] + dp[i - 2][1] + dp[i - 2][2]) % MOD; // Update the value of dp[i][1] dp[i][1] = (dp[i - 1][0] + dp[i - 1][2]) % MOD; // Update the value of dp[i][2] dp[i][2] = (dp[i - 1][0] + dp[i - 1][1]) % MOD; } // Return the number of ways as // the value of dp[N][0] return dp[N][0]; } // Driver Code let N = 3; document.write(numTilings(N)); // This code is contributed by Potta Lokesh </script>", "e": 34473, "s": 33058, "text": null }, { "code": null, "e": 34475, "s": 34473, "text": "5" }, { "code": null, "e": 34520, "s": 34477, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 34534, "s": 34520, "text": "lokeshpotta20" }, { "code": null, "e": 34542, "s": 34534, "text": "gfgking" }, { "code": null, "e": 34559, "s": 34542, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 34566, "s": 34559, "text": "Google" }, { "code": null, "e": 34586, "s": 34566, "text": "Dynamic Programming" }, { "code": null, "e": 34593, "s": 34586, "text": "Google" }, { "code": null, "e": 34613, "s": 34593, "text": "Dynamic Programming" }, { "code": null, "e": 34711, "s": 34613, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34754, "s": 34711, "text": "Maximum size square sub-matrix with all 1s" }, { "code": null, "e": 34814, "s": 34754, "text": "Optimal Substructure Property in Dynamic Programming | DP-2" }, { "code": null, "e": 34835, "s": 34814, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 34870, "s": 34835, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 34899, "s": 34870, "text": "Box Stacking Problem | DP-22" }, { "code": null, "e": 34955, "s": 34899, "text": "Maximum Subarray Sum using Divide and Conquer algorithm" }, { "code": null, "e": 34994, "s": 34955, "text": "Greedy approach vs Dynamic programming" }, { "code": null, "e": 35045, "s": 34994, "text": "Maximum sum such that no two elements are adjacent" }, { "code": null, "e": 35072, "s": 35045, "text": "Word Break Problem | DP-32" } ]
How to wrap setTimeout() method in a promise ? - GeeksforGeeks
22 Nov, 2019 To wrap setTimeout in a promise returned by a future. We can wrap setTimeout in a promise by using the then() method to return a Promise. The then() method takes upto two arguments that are callback functions for the success and failure conditions of the Promise. This function returns a promise. There can be two different values if the function called onFulfilled that’s mean promise is fulfilled. If the function onRejected called that means promise is rejected. Syntax: Promise.then(onFulfilled, onRejected) Below example will illustrate the approach: Example: <!DOCTYPE html><html> <head> <title> How to wrap setTimeout in a promise? </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> How to wrap setTimeout in a promise? </h3> <br> <button onclick="change()"> Click to print </button></body> <script> function change() { return new Promise(function(resolve, reject) { // Setting 2000 ms time setTimeout(resolve, 2000); }).then(function() { console.log("Wrapped setTimeout after 2000ms"); }); }</script> </html> Output: Before Clicking the button: After clicking the button: Reference:Promise.prototype.then() Method JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25578, "s": 25550, "text": "\n22 Nov, 2019" }, { "code": null, "e": 26044, "s": 25578, "text": "To wrap setTimeout in a promise returned by a future. We can wrap setTimeout in a promise by using the then() method to return a Promise. The then() method takes upto two arguments that are callback functions for the success and failure conditions of the Promise. This function returns a promise. There can be two different values if the function called onFulfilled that’s mean promise is fulfilled. If the function onRejected called that means promise is rejected." }, { "code": null, "e": 26052, "s": 26044, "text": "Syntax:" }, { "code": null, "e": 26090, "s": 26052, "text": "Promise.then(onFulfilled, onRejected)" }, { "code": null, "e": 26134, "s": 26090, "text": "Below example will illustrate the approach:" }, { "code": null, "e": 26143, "s": 26134, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to wrap setTimeout in a promise? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> How to wrap setTimeout in a promise? </h3> <br> <button onclick=\"change()\"> Click to print </button></body> <script> function change() { return new Promise(function(resolve, reject) { // Setting 2000 ms time setTimeout(resolve, 2000); }).then(function() { console.log(\"Wrapped setTimeout after 2000ms\"); }); }</script> </html> ", "e": 26776, "s": 26143, "text": null }, { "code": null, "e": 26784, "s": 26776, "text": "Output:" }, { "code": null, "e": 26812, "s": 26784, "text": "Before Clicking the button:" }, { "code": null, "e": 26839, "s": 26812, "text": "After clicking the button:" }, { "code": null, "e": 26881, "s": 26839, "text": "Reference:Promise.prototype.then() Method" }, { "code": null, "e": 26897, "s": 26881, "text": "JavaScript-Misc" }, { "code": null, "e": 26904, "s": 26897, "text": "Picked" }, { "code": null, "e": 26915, "s": 26904, "text": "JavaScript" }, { "code": null, "e": 26932, "s": 26915, "text": "Web Technologies" }, { "code": null, "e": 26959, "s": 26932, "text": "Web technologies Questions" }, { "code": null, "e": 27057, "s": 26959, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27097, "s": 27057, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27142, "s": 27097, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27203, "s": 27142, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27275, "s": 27203, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27327, "s": 27275, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 27367, "s": 27327, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27400, "s": 27367, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27445, "s": 27400, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27488, "s": 27445, "text": "How to fetch data from an API in ReactJS ?" } ]
Math.Exp() Method in C#
The Math.Exp() method in C# is used to return e raised to the specified power. public static double Exp (double val); Here, Val is the power. If Val equals NaN or PositiveInfinity, that value is returned. However, if d equals NegativeInfinity, 0 is returned. Let us now see an example to implement Math.Exp() method − using System; public class Demo { public static void Main(){ Console.WriteLine(Math.Exp(0.0)); Console.WriteLine(Math.Exp(Double.PositiveInfinity)); Console.WriteLine(Math.Exp(Double.NegativeInfinity)); } } This will produce the following output − 1 ∞ 0 Let us see another example to implement Math.Exp() method − using System; public class Demo { public static void Main(){ Console.WriteLine(Math.Exp(10.0)); Console.WriteLine(Math.Exp(Double.NaN)); } } This will produce the following output − 22026.4657948067 NaN
[ { "code": null, "e": 1141, "s": 1062, "text": "The Math.Exp() method in C# is used to return e raised to the specified power." }, { "code": null, "e": 1180, "s": 1141, "text": "public static double Exp (double val);" }, { "code": null, "e": 1204, "s": 1180, "text": "Here, Val is the power." }, { "code": null, "e": 1321, "s": 1204, "text": "If Val equals NaN or PositiveInfinity, that value is returned. However, if d equals NegativeInfinity, 0 is returned." }, { "code": null, "e": 1380, "s": 1321, "text": "Let us now see an example to implement Math.Exp() method −" }, { "code": null, "e": 1611, "s": 1380, "text": "using System;\npublic class Demo {\n public static void Main(){\n Console.WriteLine(Math.Exp(0.0));\n Console.WriteLine(Math.Exp(Double.PositiveInfinity));\n Console.WriteLine(Math.Exp(Double.NegativeInfinity));\n }\n}" }, { "code": null, "e": 1652, "s": 1611, "text": "This will produce the following output −" }, { "code": null, "e": 1658, "s": 1652, "text": "1\n∞\n0" }, { "code": null, "e": 1718, "s": 1658, "text": "Let us see another example to implement Math.Exp() method −" }, { "code": null, "e": 1877, "s": 1718, "text": "using System;\npublic class Demo {\n public static void Main(){\n Console.WriteLine(Math.Exp(10.0));\n Console.WriteLine(Math.Exp(Double.NaN));\n }\n}" }, { "code": null, "e": 1918, "s": 1877, "text": "This will produce the following output −" }, { "code": null, "e": 1939, "s": 1918, "text": "22026.4657948067\nNaN" } ]
Goldfeld-Quandt Test - GeeksforGeeks
29 Sep, 2021 Goldfeld-Quandt Test – This test is used to test the presence of Heteroscedasticity in the given data. The test was given by Stephen M Goldfeld and Richard E Quandt. This test can be used if the error variance is positively related to one of the explanatory variables( Xi ). Mathematically it is given as – If the regression model is: where ui is the residual/error term. and the error variance is positively related to Xi2 , i.e., It can be understood in simpler terms if we understand the concept of heteroscedasticity. Heteroscedasticity — It is the situation in which variability of the independent variable (Y) is unequal across the range of values of an explanatory variable(Xi). If a scatterplot is drawn between the two variables a cone-like shape is created. As the value of Xi increases the scatter of variable Y widens or narrows creating a cone-like structure. For example, : When we try to predict the annual income on the basis of age of a person then the annual income can be a heteroscedastic variable as to when someone starts as a fresher the income earned is lesser than compared to someone who is experienced over the years and the hike in salary can have an evident amount of variation. Note: The absence of heteroscedasticity is called homoscedasticity which says that the variability is equal across values of an explanatory variable. Assumptions of Goldfeld-Quandt Test data is normally distributed. Null and Alternate Hypothesis of Goldfeld-Quandt Test Null Hypothesis: Heteroscedasticity is not present. Alternate Hypothesis: Heteroscedasticity is present. Test Statistic for Goldfeld-Quandt Test where, RSS = Residual sum of squares = ui2 df = degree of freedom Decision Rule for Goldfeld-Quandt Test If Fcalculated > Fcritical ; Reject the Null Hypothesis. Steps to Perform Goldfeld-Quandt Test: Step 1: Arrange the observations in ascending order of Xi. If there are more than one explanatory variables( X ) then you choose the one regarding which you have a concern that with this variable the error variance is positively related and arrange in ascending order according to this variable. In other words, you can choose any one of them to arrange. Step 2: Omit ‘c’ central observations and divide the remaining (n-c) observations into two groups containing (n-c)/2 observations each. The first (n-c)/2 observations belong to the first group(the smaller variance group) and the remaining (n-c)/2 observations belong to the second group(the larger variance group). Step 3: Fit a separate regression model for the first group and obtain RSS1. Also, fit a separate regression model on the second group and obtain RSS2. RSS = Residual Sum of Squares = ui2 ui = Ypredicted - Ycalculated This RSS each have (n-c)/2 – k or (n-c-2k)/2 degrees of freedom, where k is the number of parameters to be estimated. For a model with only one explanatory variable(X) the value of k =2 and increases with an increase in the number of explanatory variables. Step 4: Compute the Test Statistic Step 5: Find out the critical value Use the F Table to find out the critical value for the given level of significance(alpha). In this test, the values of df1 and df2 are the same(df1=df2). For example: If df=6 and alpha = 0.05 or 5% then the critical value will be 4.2839. Step 6: Compare Fcritical and Fcalculated and state the result. If Fcalculated < Fcritical ; Accept the Null Hypothesis. If Fcalculated > Fcritical ; Reject the Null Hypothesis. Note: There is no test that can give a black and white answer to whether there is heteroscedasticity or not. We can only suspect the presence of it. So if the null hypothesis is rejected then we can say that the presence of heteroscedasticity is very likely and if it is accepted we can say that heteroscedasticity is not likely to be present. This is all about the Goldfeld-Quandt Test. For any queries do leave a comment down below. Attention reader! Don’t stop learning now. Get hold of all the important Machine Learning Concepts with the Machine Learning Foundation Course at a student-friendly price and become industry ready. abhishek0719kadiyan sweetyty Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Informed and Uninformed Search in AI Deploy Machine Learning Model using Flask Support Vector Machine Algorithm Types of Environments in AI k-nearest neighbor algorithm in Python Principal Component Analysis with Python Python | Decision Tree Regression using sklearn Python | Stemming words with NLTK Intuition of Adam Optimizer Normalization vs Standardization
[ { "code": null, "e": 24025, "s": 23994, "text": " \n29 Sep, 2021\n" }, { "code": null, "e": 24192, "s": 24025, "text": "Goldfeld-Quandt Test – This test is used to test the presence of Heteroscedasticity in the given data. The test was given by Stephen M Goldfeld and Richard E Quandt. " }, { "code": null, "e": 24333, "s": 24192, "text": "This test can be used if the error variance is positively related to one of the explanatory variables( Xi ). Mathematically it is given as –" }, { "code": null, "e": 24361, "s": 24333, "text": "If the regression model is:" }, { "code": null, "e": 24398, "s": 24361, "text": "where ui is the residual/error term." }, { "code": null, "e": 24458, "s": 24398, "text": "and the error variance is positively related to Xi2 , i.e.," }, { "code": null, "e": 24549, "s": 24458, "text": " It can be understood in simpler terms if we understand the concept of heteroscedasticity." }, { "code": null, "e": 25235, "s": 24549, "text": "Heteroscedasticity — It is the situation in which variability of the independent variable (Y) is unequal across the range of values of an explanatory variable(Xi). If a scatterplot is drawn between the two variables a cone-like shape is created. As the value of Xi increases the scatter of variable Y widens or narrows creating a cone-like structure. For example, : When we try to predict the annual income on the basis of age of a person then the annual income can be a heteroscedastic variable as to when someone starts as a fresher the income earned is lesser than compared to someone who is experienced over the years and the hike in salary can have an evident amount of variation." }, { "code": null, "e": 25385, "s": 25235, "text": "Note: The absence of heteroscedasticity is called homoscedasticity which says that the variability is equal across values of an explanatory variable." }, { "code": null, "e": 25421, "s": 25385, "text": "Assumptions of Goldfeld-Quandt Test" }, { "code": null, "e": 25451, "s": 25421, "text": "data is normally distributed." }, { "code": null, "e": 25505, "s": 25451, "text": "Null and Alternate Hypothesis of Goldfeld-Quandt Test" }, { "code": null, "e": 25557, "s": 25505, "text": "Null Hypothesis: Heteroscedasticity is not present." }, { "code": null, "e": 25610, "s": 25557, "text": "Alternate Hypothesis: Heteroscedasticity is present." }, { "code": null, "e": 25650, "s": 25610, "text": "Test Statistic for Goldfeld-Quandt Test" }, { "code": null, "e": 25716, "s": 25650, "text": "where,\nRSS = Residual sum of squares = ui2\ndf = degree of freedom" }, { "code": null, "e": 25755, "s": 25716, "text": "Decision Rule for Goldfeld-Quandt Test" }, { "code": null, "e": 25812, "s": 25755, "text": "If Fcalculated > Fcritical ; Reject the Null Hypothesis." }, { "code": null, "e": 25852, "s": 25812, "text": "Steps to Perform Goldfeld-Quandt Test: " }, { "code": null, "e": 26207, "s": 25852, "text": "Step 1: Arrange the observations in ascending order of Xi. If there are more than one explanatory variables( X ) then you choose the one regarding which you have a concern that with this variable the error variance is positively related and arrange in ascending order according to this variable. In other words, you can choose any one of them to arrange." }, { "code": null, "e": 26522, "s": 26207, "text": "Step 2: Omit ‘c’ central observations and divide the remaining (n-c) observations into two groups containing (n-c)/2 observations each. The first (n-c)/2 observations belong to the first group(the smaller variance group) and the remaining (n-c)/2 observations belong to the second group(the larger variance group)." }, { "code": null, "e": 26674, "s": 26522, "text": "Step 3: Fit a separate regression model for the first group and obtain RSS1. Also, fit a separate regression model on the second group and obtain RSS2." }, { "code": null, "e": 26740, "s": 26674, "text": "RSS = Residual Sum of Squares = ui2\nui = Ypredicted - Ycalculated" }, { "code": null, "e": 26859, "s": 26740, "text": "This RSS each have (n-c)/2 – k or (n-c-2k)/2 degrees of freedom, where k is the number of parameters to be estimated. " }, { "code": null, "e": 26998, "s": 26859, "text": "For a model with only one explanatory variable(X) the value of k =2 and increases with an increase in the number of explanatory variables." }, { "code": null, "e": 27033, "s": 26998, "text": "Step 4: Compute the Test Statistic" }, { "code": null, "e": 27069, "s": 27033, "text": "Step 5: Find out the critical value" }, { "code": null, "e": 27223, "s": 27069, "text": "Use the F Table to find out the critical value for the given level of significance(alpha). In this test, the values of df1 and df2 are the same(df1=df2)." }, { "code": null, "e": 27307, "s": 27223, "text": "For example: If df=6 and alpha = 0.05 or 5% then the critical value will be 4.2839." }, { "code": null, "e": 27371, "s": 27307, "text": "Step 6: Compare Fcritical and Fcalculated and state the result." }, { "code": null, "e": 27487, "s": 27371, "text": "If Fcalculated < Fcritical ; Accept the Null Hypothesis.\nIf Fcalculated > Fcritical ; Reject the Null Hypothesis." }, { "code": null, "e": 27831, "s": 27487, "text": "Note: There is no test that can give a black and white answer to whether there is heteroscedasticity or not. We can only suspect the presence of it. So if the null hypothesis is rejected then we can say that the presence of heteroscedasticity is very likely and if it is accepted we can say that heteroscedasticity is not likely to be present." }, { "code": null, "e": 27922, "s": 27831, "text": "This is all about the Goldfeld-Quandt Test. For any queries do leave a comment down below." }, { "code": null, "e": 28120, "s": 27922, "text": "Attention reader! Don’t stop learning now. Get hold of all the important Machine Learning Concepts with the Machine Learning Foundation Course at a student-friendly price and become industry ready." }, { "code": null, "e": 28140, "s": 28120, "text": "abhishek0719kadiyan" }, { "code": null, "e": 28149, "s": 28140, "text": "sweetyty" }, { "code": null, "e": 28168, "s": 28149, "text": "\nMachine Learning\n" }, { "code": null, "e": 28373, "s": 28168, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 28429, "s": 28373, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 28471, "s": 28429, "text": "Deploy Machine Learning Model using Flask" }, { "code": null, "e": 28504, "s": 28471, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 28532, "s": 28504, "text": "Types of Environments in AI" }, { "code": null, "e": 28571, "s": 28532, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 28612, "s": 28571, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 28660, "s": 28612, "text": "Python | Decision Tree Regression using sklearn" }, { "code": null, "e": 28694, "s": 28660, "text": "Python | Stemming words with NLTK" }, { "code": null, "e": 28722, "s": 28694, "text": "Intuition of Adam Optimizer" } ]
Tryit Editor v3.7
Tryit: HTML headings
[]
Index Of an Extra Element | Practice | GeeksforGeeks
Given two sorted arrays of distinct elements. There is only 1 difference between the arrays. First array has one element extra added in between. Find the index of the extra element. Example 1: Input: N = 7 A[] = {2,4,6,8,9,10,12} B[] = {2,4,6,8,10,12} Output: 4 Explanation: In the second array, 9 is missing and it's index in the first array is 4. Example 2: Input: N = 6 A[] = {3,5,7,9,11,13} B[] = {3,5,7,11,13} Output: 3 Your Task: You don't have to take any input. Just complete the provided function findExtra() that takes array A[], B[] and size of A[] and return the valid index (0 based indexing). Expected Time Complexity: O(log N). Expected Auxiliary Space: O(1). Constraints: 2<=N<=104 1<=Ai<=105 0 abhigyanpatek4 days ago Simple C++ Solution: int findExtra(int a[], int b[], int n) { int start = 0, end = n-1; int result; while(start <= end){ int mid = start + (end-start)/2; if(a[mid] == b[mid]){ start = mid+1; }else{ result = mid; end = mid-1; } } return result; } 0 maac_shah5 days ago JAVA Simplest Code class Solution { public int findExtra(int a[], int b[], int n) { // add code here. for(int i=0;i<n-1;i++) { if(a[i] != b[i]) { return i; } } return n-1; } } 0 pradeepshillare6 days ago class Solution { public int findExtra(int a[], int b[], int n) { // add code here. int i = 0; while(a.length>b.length) { if (a[i] != b[i]) { return i; } else { i++; if(i==a.length-1) { break; } } } return i; } } 0 rahuljaiswalmzp2 weeks ago int findExtra(int a[], int b[], int n) { // add code here. int i = 0; while(a>b){ if(a[i]!=b[i]){ return i; } else{ i++; } } } 0 asthana10112 weeks ago Java simple Binary Search solution public int findExtra(int a[], int b[], int n) { int lb = 0, ub = n - 1; while(lb < ub) { int mid = lb + (ub - lb)/2; if(a[mid] >= b[mid]) lb = mid + 1; else if(a[mid] < b[mid]) ub = mid; } return lb; } 0 mayank180919992 weeks ago int findExtra(int a[], int b[], int n) { // add code here. map<int,int>mp; for(int i=0;i<n-1;i++){ mp[b[i]]++; } for(int i=0;i<n;i++){ if(mp.find(a[i])==mp.end()){ return i; } } return 0; } 0 akashmarkad22102 weeks ago public int findExtra(int a[], int b[], int n) { // add code here. if(a[n-1] != b[n-2]) { return n-1; } for(int i=0;i<n;i++) { if(a[i] == b[i]) { continue; } else { return i; } } return -1; } +1 imohdalam3 weeks ago JAVA | O(log n ) class Solution { public int findExtra(int a[], int b[], int n) { int a1 = 0; boolean flag = true; for(int i=0; i<n-1 && flag; i++){ if(a[i] != b[i]){ flag = false; a1 = i; } if(a[n - 1-i] != b[n - 2 - i]){ flag = false; a1 = n - 1 - i; } } return flag ? n-1 : a1; } } 0 shrustis1763 weeks ago C++ solution using BINARY SEARCH int findExtra(int a[], int b[], int n) { // add code here. int l=0, h=n-1, mid; while(l<=h) { mid = l+(h-l)/2; // when the last index is the ans //check eg: a=0,5,8,10 and b=0,5,8 if(mid == n-1) return n-1; if(a[mid] == b[mid]) l=mid+1; else if(a[mid] < b[mid]) h=mid-1; } //returning mid gives error when u are moving from left to right & again right->left //eg : a=1,2,3,4 and b=1,3,4 return l; } +1 swarajpawar3 weeks ago class Solution{ public: int findExtra(int a[], int b[], int n) { // add code here. for(int i=0;i<n;i++){ if(a[i]!=b[i])return i; } }}; 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": 420, "s": 238, "text": "Given two sorted arrays of distinct elements. There is only 1 difference between the arrays. First array has one element extra added in between. Find the index of the extra element." }, { "code": null, "e": 431, "s": 420, "text": "Example 1:" }, { "code": null, "e": 587, "s": 431, "text": "Input:\nN = 7\nA[] = {2,4,6,8,9,10,12}\nB[] = {2,4,6,8,10,12}\nOutput: 4\nExplanation: In the second array, 9 is\nmissing and it's index in the first array\nis 4." }, { "code": null, "e": 598, "s": 587, "text": "Example 2:" }, { "code": null, "e": 663, "s": 598, "text": "Input:\nN = 6\nA[] = {3,5,7,9,11,13}\nB[] = {3,5,7,11,13}\nOutput: 3" }, { "code": null, "e": 845, "s": 663, "text": "Your Task:\nYou don't have to take any input. Just complete the provided function findExtra() that takes array A[], B[] and size of A[] and return the valid index (0 based indexing)." }, { "code": null, "e": 913, "s": 845, "text": "Expected Time Complexity: O(log N).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 947, "s": 913, "text": "Constraints:\n2<=N<=104\n1<=Ai<=105" }, { "code": null, "e": 949, "s": 947, "text": "0" }, { "code": null, "e": 973, "s": 949, "text": "abhigyanpatek4 days ago" }, { "code": null, "e": 994, "s": 973, "text": "Simple C++ Solution:" }, { "code": null, "e": 1333, "s": 994, "text": "int findExtra(int a[], int b[], int n) { int start = 0, end = n-1; int result; while(start <= end){ int mid = start + (end-start)/2; if(a[mid] == b[mid]){ start = mid+1; }else{ result = mid; end = mid-1; } } return result; }" }, { "code": null, "e": 1335, "s": 1333, "text": "0" }, { "code": null, "e": 1355, "s": 1335, "text": "maac_shah5 days ago" }, { "code": null, "e": 1374, "s": 1355, "text": "JAVA Simplest Code" }, { "code": null, "e": 1642, "s": 1376, "text": "class Solution {\n public int findExtra(int a[], int b[], int n) {\n // add code here.\n for(int i=0;i<n-1;i++)\n {\n if(a[i] != b[i])\n {\n return i;\n }\n }\n \n return n-1;\n }\n}" }, { "code": null, "e": 1644, "s": 1642, "text": "0" }, { "code": null, "e": 1670, "s": 1644, "text": "pradeepshillare6 days ago" }, { "code": null, "e": 1764, "s": 1670, "text": "class Solution { public int findExtra(int a[], int b[], int n) { // add code here." }, { "code": null, "e": 1821, "s": 1764, "text": " int i = 0; while(a.length>b.length) {" }, { "code": null, "e": 2078, "s": 1821, "text": " if (a[i] != b[i]) { return i; } else { i++; if(i==a.length-1) { break; } } } return i; } }" }, { "code": null, "e": 2080, "s": 2078, "text": "0" }, { "code": null, "e": 2107, "s": 2080, "text": "rahuljaiswalmzp2 weeks ago" }, { "code": null, "e": 2329, "s": 2107, "text": " int findExtra(int a[], int b[], int n) { // add code here. int i = 0; while(a>b){ if(a[i]!=b[i]){ return i; } else{ i++; } } }" }, { "code": null, "e": 2331, "s": 2329, "text": "0" }, { "code": null, "e": 2354, "s": 2331, "text": "asthana10112 weeks ago" }, { "code": null, "e": 2389, "s": 2354, "text": "Java simple Binary Search solution" }, { "code": null, "e": 2708, "s": 2389, "text": "public int findExtra(int a[], int b[], int n) \n {\n int lb = 0, ub = n - 1;\n while(lb < ub)\n {\n int mid = lb + (ub - lb)/2;\n if(a[mid] >= b[mid])\n lb = mid + 1;\n else if(a[mid] < b[mid])\n ub = mid;\n }\n return lb;\n }" }, { "code": null, "e": 2710, "s": 2708, "text": "0" }, { "code": null, "e": 2736, "s": 2710, "text": "mayank180919992 weeks ago" }, { "code": null, "e": 3035, "s": 2736, "text": " int findExtra(int a[], int b[], int n) {\n // add code here.\n map<int,int>mp;\n for(int i=0;i<n-1;i++){\n mp[b[i]]++;\n }\n for(int i=0;i<n;i++){\n if(mp.find(a[i])==mp.end()){\n return i;\n }\n }\n return 0;\n }" }, { "code": null, "e": 3037, "s": 3035, "text": "0" }, { "code": null, "e": 3064, "s": 3037, "text": "akashmarkad22102 weeks ago" }, { "code": null, "e": 3417, "s": 3064, "text": "public int findExtra(int a[], int b[], int n) { // add code here. if(a[n-1] != b[n-2]) { return n-1; } for(int i=0;i<n;i++) { if(a[i] == b[i]) { continue; } else { return i; } } return -1; }" }, { "code": null, "e": 3420, "s": 3417, "text": "+1" }, { "code": null, "e": 3441, "s": 3420, "text": "imohdalam3 weeks ago" }, { "code": null, "e": 3458, "s": 3441, "text": "JAVA | O(log n )" }, { "code": null, "e": 3898, "s": 3458, "text": "class Solution {\n public int findExtra(int a[], int b[], int n) {\n \n int a1 = 0;\n boolean flag = true;\n \n for(int i=0; i<n-1 && flag; i++){\n if(a[i] != b[i]){\n flag = false;\n a1 = i;\n }\n if(a[n - 1-i] != b[n - 2 - i]){\n flag = false;\n a1 = n - 1 - i;\n }\n }\n return flag ? n-1 : a1;\n }\n}" }, { "code": null, "e": 3900, "s": 3898, "text": "0" }, { "code": null, "e": 3923, "s": 3900, "text": "shrustis1763 weeks ago" }, { "code": null, "e": 3956, "s": 3923, "text": "C++ solution using BINARY SEARCH" }, { "code": null, "e": 4210, "s": 3958, "text": "int findExtra(int a[], int b[], int n) { // add code here. int l=0, h=n-1, mid; while(l<=h) { mid = l+(h-l)/2; // when the last index is the ans //check eg: a=0,5,8,10 and b=0,5,8" }, { "code": null, "e": 4530, "s": 4210, "text": " if(mid == n-1) return n-1; if(a[mid] == b[mid]) l=mid+1; else if(a[mid] < b[mid]) h=mid-1; } //returning mid gives error when u are moving from left to right & again right->left //eg : a=1,2,3,4 and b=1,3,4" }, { "code": null, "e": 4551, "s": 4530, "text": " return l; }" }, { "code": null, "e": 4554, "s": 4551, "text": "+1" }, { "code": null, "e": 4577, "s": 4554, "text": "swarajpawar3 weeks ago" }, { "code": null, "e": 4753, "s": 4577, "text": "class Solution{ public: int findExtra(int a[], int b[], int n) { // add code here. for(int i=0;i<n;i++){ if(a[i]!=b[i])return i; } }};" }, { "code": null, "e": 4899, "s": 4753, "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": 4935, "s": 4899, "text": " Login to access your submissions. " }, { "code": null, "e": 4945, "s": 4935, "text": "\nProblem\n" }, { "code": null, "e": 4955, "s": 4945, "text": "\nContest\n" }, { "code": null, "e": 5018, "s": 4955, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5166, "s": 5018, "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": 5374, "s": 5166, "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": 5480, "s": 5374, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Seaborn Visualizations Tutorial. A walkthrough of many Seaborn tools... | by Andrew Cole | Towards Data Science
By Andrew Cole If you’re like me, a world without sports is basically no world at all. However, enter 2020 and the time of COVID-19, and here we are, watching replays of the 2003 NCAA Tournament’s second round pretending that we are just as invested as if it were the 2020 tournament (which should be happening as I type this). This unfortunate pandemic also means that we are missing my personal favorite time of the year, the NHL playoffs. So, to make up for the lack of life which sports brings to so many of us, I decided to put together an overview of something which brings life to a select few of us, NHL statistics data. Seaborn is one of Python’s most powerful and essential visualization packages, and there are endless possibilities for telling visual stories through your data. All NHL data was gathered from MoneyPuck.com. The GitHub repository for this notebook can be found here. We begin by cleaning the information we have a little bit. We will select data from skaters in all situations (5v5, man advantages, shorthanded, etc.). Next, because there are 31 NHL teams and this is a lot to deal with for these instructional purposes we will limit the data to that only from teams in the Central Division: Chicago Blackhawks, Nashville Predators, St. Louis Blues, Colorado Avalanche, Minnesota Wild, Winnipeg Jets, & the Dallas Stars. The DataFrame we will be left working with looks like this: We have the statistics from 200 players with 153 statistic features. We will only be focusing on basic statistics like goals, points, penalties, etc. To import the library: import seaborn as sns We rename seaborn as ‘sns’ to make it easier when we call it for visualizations later on. As with any dataset, we want to take a look at statistical relationships. Perhaps the best way of looking at a bivariate relationship is through the use of the scatter plot. Each point will show the joint distribution of an observation in one statistical feature with its second feature’s location. Let’s first take a look at how points (1 goal = 1 point, 1 assist = 1 point; 1 goal + 2 assists = 3 points) We can see that, as you’d intuitively expect, more games played results in more points being scored. This is just your basic scatter plot, so how can we make this graph give us even more information? Let’s add a hue. By adding the ‘hue’ argument to our sns.relplot() code, we are able to see how the points/games played distribution looks per team. Can we go even further? This plot only tells us about the points and games played per team, but there’s more information to be learned! What about positions? Who is scoring more points on those individual teams? Let’s add some subplots to find out. Now we have the same graphs as above, broken down by team AND position. Each row represents a different team, and each column represents a different position (Offense or Defense). For example, we can see that Chicago has one forward who scores over 80 points in just over 60 games played, while most of Chicago’s defensemen score less than 20 points regardless of how many games they play (with one exception). Histograms are one of the most powerful visualizations which any analyst can create. Histograms graphically summarize the distribution of all the data. In a bit simpler terms, a histogram shows how often each value in a dataset will occur. The x-axis contains the variable metric, while the y-axis contains the relative frequency of the observation’s value. The histogram above shows us that overwhelmingly, the majority of the league scores between 0 and 20 points. The smoothed line which we see is the kernel density estimation (KDE) — a technique which estimates unknown probability distributions of the variable based on the samples we already have. In simpler terms, if new player data was introduced to the set, there is the highest likelihood that it would fall under the tallest peaks of the smoothed line. The tick marks which we see at the bottom of the graph are known as the rug. The rug simply shows us where the individual data observations are located on the graph. You can eliminate both the KDE and the rug from the histogram by setting the code arguments to False. Another type of plot which helps give us an idea of what our data looks like is the Boxplot. Specifically, boxplots help us identify where the medians, ranges, and variabilities of data lie. The boxplot for points by team can be seen below: The boxes we see shows three quartile values of the distribution (the big colored boxes), the mean for that group (the horizontal line through the middle of the team box), and outliers (the points above the graphs). For example, Colorado has the majority of its point scorers in the range of 0–32. The point above Colorado’s box is the outlier, meaning that the Avalanche have a singular point scorer significantly higher than the rest of the team, therefore making it the outlier. To make this plot even more descriptive, we can again add ‘position’ as a hue to show outlier information among teams per position (offense or defense). Violin plot’s are a less popular but even more descriptive visualization method. Boxplot’s do not actually take into consideration the data’s distribution. If the data changes (like adding the entire league’s data instead of just the Central Division) the median and ranges do not, but a Violin plot will reflect this change. The violin plot will ‘widen’ to represent a higher density of observations around that value. We can see now that Chicago’s defensemen score in the 0–40 points range, whereas Minnesota’s defensemen score a much larger range of points. The wider a violin plot, the more dense the data is at that observation value. We can also create a more condensed version of this plot by adding a ‘split’: The graph is showing the same thing, it’s just simplified by adding the defense & offense violins into one. Chicago has forwards who score in a varying large range, while it’s defensemen are all concentrated between 0 and 20 points. A swarm plot is basically just a scatter plot where the X-axis represents a categorical variable. We can see through this swarm plot that Winnipeg has the highest goal scorer of the division, but most of their team’s point production is clustered below 10. Let’s flip the categories and see goals by position & team. Now we can see that forwards clearly score more goals than defensemen, and the highest goal scorer to date plays for Winnipeg. A jitter plot is very similar to our swarm plots, but it allows for us to remain a bit more organized. This is your normal dot-plot, but it adds a ‘jitter’ — a spacing — between points for better visualization. Let’s use a Jitter plot to take a look at number of penalties by position. We can see that all personnel who took more than 16 penalties were Forwards A jointplot is seaborn’s method of displaying a bivariate relationship at the same time as a univariate profile. Essentially combining a scatter plot with a histogram (without KDE). Let’s take a look at a jointplot to see how number of penalties taken is related to point production. If we look at the main scatter plot, we can‘t really make out much of a distinction. It is inherent to think that a small number of penalties would mean more time spent on the ice, which means more opportunities for scoring. However, the scatter plot itself does not show a strong relationship in either direction. But, the jointplot gives us the benefit of showing the distributions along the top and right spines. By looking at those, we can see that as number of penalties increase, there are less players populating those regions. The same can be said about points. Therefore we can deduce that there is a slight positive relationship between the two. Another way of visualizing a bivariate relationship, in particular when we have a large amount of data, is the hexplot. A hexplot splits the plotting window into several hexbins and then the number of observations which fall into each bin corresponds with a color to indicate density. A darker color hexbin means that there are more observations, or more density, within that region. The observation frequency bar graphs can be seen along the spines as an additional reference for information. We will use a hexplot to analyze how number of goals scored is related to number of shot attempts. Again, this graph can be somewhat inherent. As the great Wayne Gretzky/Michael Scott once said, “you miss 100% of the shots you don’t take”. We would believe that as shots increase, so do number of goals. The hexplot reiterates this notion. We see the darkest hexbin in the bottom right, as it is the most dense because scoring a goal in the NHL is no easy feat and the majority of players will be centered around this area. As we increase hexbins to the right and upwards, the color slowly begins to fade which indicates that there is a decreasing positive relationship between shot attempts and goals scored. A similar bivariate plot to the hexbin is the Kernel Density Estimation jointplot. A KDE jointplot also uses color to determine where observations are the most dense, but instead of placing them into a pre-defined hexbin, a continuous plot is made using probabilities should new data be introduced. Let’s look at the same Shot Attempts/Goals relationship. We can see that the same information is given to us as in the hexbin plot, but this shows a probabilistic view of where the observations are. Instead of the hexbin showing us that most players fall in the low goals/low shot attempts category, we can see an increasing positive relationship in the probability that more shot attempts will equal more goals, with the largest concentration of players falling in the 0–50 shot attempts range and the 0–5 goals range. A bivariate relationship can tell us a lot, but just looking at the distributions & scatterplots may not be enough to give us all the information we need about what is happening underneath the surface numbers of the data. A correlation shows us the degree in which one variable’s value influences another. A strong correlation (1.00) indicates that when one variable changes, there is a 100% positive movement in the other variable as well (-1.00 for the opposite side of the scale). Let’s take a look at how important certain variables in the NHL are in terms of correlation. Here is the code to check correlations: Looking at these numbers shows us a lot, notice that the z-axis moving down and to the right represents perfect correlation of a variable with itself. We can see certain variables like points are heavily correlated with shots on goal, shot attempts, and ice time, as the correlation coefficients are all well above 0.5. But statistics and datasets are usually not as intuitive as sport statistics so let’s see how we can make this correlation chart more friendly to the user. A heatmap is just a friendlier way of visualizing the correlation table which we produced above. If a correlation coefficient is higher, signaling a more significant correlation between two variables, the color will be darker. Again, reference the z-axis of dark blue to represent a perfect 1:1 correlation between a variable and itself. This heatmap just draws our eyes in an easier way to the best & worst correlations. For example, we easily see that shot attempts and shots on goal have the strongest correlation (no duh), and hits has the least correlation with goals. Finally, perhaps one of the strongest and most useful tools for any analyst is the Pairplot. A pairplot visualizes the distribution of single variables as well as the bivariate relationship it has with other variables. Simply, we will be creating a bivariate scatter plot for every variable in the DataFrame, and then putting them into one screen. This behemoth of a graph has a TON going on, but it is also extremely helpful for getting a good overall view of what we are looking for. We read it the same as we would a bivariate scatter plot. If we see that there are strong positive/negative relationships between two variables, we know that those variables and their relationships are worth investigating further. Seaborn is an incredibly powerful tool for making complex data into easily-digestible information. The possibilities are seemingly endless, but hopefully, this serves as a good starting place for all the possibilities. So, with that, everybody please stay safe, stay healthy, stay inside, and we’ll all turn out alright :).
[ { "code": null, "e": 187, "s": 172, "text": "By Andrew Cole" }, { "code": null, "e": 801, "s": 187, "text": "If you’re like me, a world without sports is basically no world at all. However, enter 2020 and the time of COVID-19, and here we are, watching replays of the 2003 NCAA Tournament’s second round pretending that we are just as invested as if it were the 2020 tournament (which should be happening as I type this). This unfortunate pandemic also means that we are missing my personal favorite time of the year, the NHL playoffs. So, to make up for the lack of life which sports brings to so many of us, I decided to put together an overview of something which brings life to a select few of us, NHL statistics data." }, { "code": null, "e": 1067, "s": 801, "text": "Seaborn is one of Python’s most powerful and essential visualization packages, and there are endless possibilities for telling visual stories through your data. All NHL data was gathered from MoneyPuck.com. The GitHub repository for this notebook can be found here." }, { "code": null, "e": 1521, "s": 1067, "text": "We begin by cleaning the information we have a little bit. We will select data from skaters in all situations (5v5, man advantages, shorthanded, etc.). Next, because there are 31 NHL teams and this is a lot to deal with for these instructional purposes we will limit the data to that only from teams in the Central Division: Chicago Blackhawks, Nashville Predators, St. Louis Blues, Colorado Avalanche, Minnesota Wild, Winnipeg Jets, & the Dallas Stars." }, { "code": null, "e": 1581, "s": 1521, "text": "The DataFrame we will be left working with looks like this:" }, { "code": null, "e": 1731, "s": 1581, "text": "We have the statistics from 200 players with 153 statistic features. We will only be focusing on basic statistics like goals, points, penalties, etc." }, { "code": null, "e": 1754, "s": 1731, "text": "To import the library:" }, { "code": null, "e": 1776, "s": 1754, "text": "import seaborn as sns" }, { "code": null, "e": 1866, "s": 1776, "text": "We rename seaborn as ‘sns’ to make it easier when we call it for visualizations later on." }, { "code": null, "e": 2273, "s": 1866, "text": "As with any dataset, we want to take a look at statistical relationships. Perhaps the best way of looking at a bivariate relationship is through the use of the scatter plot. Each point will show the joint distribution of an observation in one statistical feature with its second feature’s location. Let’s first take a look at how points (1 goal = 1 point, 1 assist = 1 point; 1 goal + 2 assists = 3 points)" }, { "code": null, "e": 2490, "s": 2273, "text": "We can see that, as you’d intuitively expect, more games played results in more points being scored. This is just your basic scatter plot, so how can we make this graph give us even more information? Let’s add a hue." }, { "code": null, "e": 2871, "s": 2490, "text": "By adding the ‘hue’ argument to our sns.relplot() code, we are able to see how the points/games played distribution looks per team. Can we go even further? This plot only tells us about the points and games played per team, but there’s more information to be learned! What about positions? Who is scoring more points on those individual teams? Let’s add some subplots to find out." }, { "code": null, "e": 3282, "s": 2871, "text": "Now we have the same graphs as above, broken down by team AND position. Each row represents a different team, and each column represents a different position (Offense or Defense). For example, we can see that Chicago has one forward who scores over 80 points in just over 60 games played, while most of Chicago’s defensemen score less than 20 points regardless of how many games they play (with one exception)." }, { "code": null, "e": 3640, "s": 3282, "text": "Histograms are one of the most powerful visualizations which any analyst can create. Histograms graphically summarize the distribution of all the data. In a bit simpler terms, a histogram shows how often each value in a dataset will occur. The x-axis contains the variable metric, while the y-axis contains the relative frequency of the observation’s value." }, { "code": null, "e": 4366, "s": 3640, "text": "The histogram above shows us that overwhelmingly, the majority of the league scores between 0 and 20 points. The smoothed line which we see is the kernel density estimation (KDE) — a technique which estimates unknown probability distributions of the variable based on the samples we already have. In simpler terms, if new player data was introduced to the set, there is the highest likelihood that it would fall under the tallest peaks of the smoothed line. The tick marks which we see at the bottom of the graph are known as the rug. The rug simply shows us where the individual data observations are located on the graph. You can eliminate both the KDE and the rug from the histogram by setting the code arguments to False." }, { "code": null, "e": 4607, "s": 4366, "text": "Another type of plot which helps give us an idea of what our data looks like is the Boxplot. Specifically, boxplots help us identify where the medians, ranges, and variabilities of data lie. The boxplot for points by team can be seen below:" }, { "code": null, "e": 5089, "s": 4607, "text": "The boxes we see shows three quartile values of the distribution (the big colored boxes), the mean for that group (the horizontal line through the middle of the team box), and outliers (the points above the graphs). For example, Colorado has the majority of its point scorers in the range of 0–32. The point above Colorado’s box is the outlier, meaning that the Avalanche have a singular point scorer significantly higher than the rest of the team, therefore making it the outlier." }, { "code": null, "e": 5242, "s": 5089, "text": "To make this plot even more descriptive, we can again add ‘position’ as a hue to show outlier information among teams per position (offense or defense)." }, { "code": null, "e": 5662, "s": 5242, "text": "Violin plot’s are a less popular but even more descriptive visualization method. Boxplot’s do not actually take into consideration the data’s distribution. If the data changes (like adding the entire league’s data instead of just the Central Division) the median and ranges do not, but a Violin plot will reflect this change. The violin plot will ‘widen’ to represent a higher density of observations around that value." }, { "code": null, "e": 5882, "s": 5662, "text": "We can see now that Chicago’s defensemen score in the 0–40 points range, whereas Minnesota’s defensemen score a much larger range of points. The wider a violin plot, the more dense the data is at that observation value." }, { "code": null, "e": 5960, "s": 5882, "text": "We can also create a more condensed version of this plot by adding a ‘split’:" }, { "code": null, "e": 6193, "s": 5960, "text": "The graph is showing the same thing, it’s just simplified by adding the defense & offense violins into one. Chicago has forwards who score in a varying large range, while it’s defensemen are all concentrated between 0 and 20 points." }, { "code": null, "e": 6291, "s": 6193, "text": "A swarm plot is basically just a scatter plot where the X-axis represents a categorical variable." }, { "code": null, "e": 6510, "s": 6291, "text": "We can see through this swarm plot that Winnipeg has the highest goal scorer of the division, but most of their team’s point production is clustered below 10. Let’s flip the categories and see goals by position & team." }, { "code": null, "e": 6637, "s": 6510, "text": "Now we can see that forwards clearly score more goals than defensemen, and the highest goal scorer to date plays for Winnipeg." }, { "code": null, "e": 6999, "s": 6637, "text": "A jitter plot is very similar to our swarm plots, but it allows for us to remain a bit more organized. This is your normal dot-plot, but it adds a ‘jitter’ — a spacing — between points for better visualization. Let’s use a Jitter plot to take a look at number of penalties by position. We can see that all personnel who took more than 16 penalties were Forwards" }, { "code": null, "e": 7283, "s": 6999, "text": "A jointplot is seaborn’s method of displaying a bivariate relationship at the same time as a univariate profile. Essentially combining a scatter plot with a histogram (without KDE). Let’s take a look at a jointplot to see how number of penalties taken is related to point production." }, { "code": null, "e": 7939, "s": 7283, "text": "If we look at the main scatter plot, we can‘t really make out much of a distinction. It is inherent to think that a small number of penalties would mean more time spent on the ice, which means more opportunities for scoring. However, the scatter plot itself does not show a strong relationship in either direction. But, the jointplot gives us the benefit of showing the distributions along the top and right spines. By looking at those, we can see that as number of penalties increase, there are less players populating those regions. The same can be said about points. Therefore we can deduce that there is a slight positive relationship between the two." }, { "code": null, "e": 8532, "s": 7939, "text": "Another way of visualizing a bivariate relationship, in particular when we have a large amount of data, is the hexplot. A hexplot splits the plotting window into several hexbins and then the number of observations which fall into each bin corresponds with a color to indicate density. A darker color hexbin means that there are more observations, or more density, within that region. The observation frequency bar graphs can be seen along the spines as an additional reference for information. We will use a hexplot to analyze how number of goals scored is related to number of shot attempts." }, { "code": null, "e": 9143, "s": 8532, "text": "Again, this graph can be somewhat inherent. As the great Wayne Gretzky/Michael Scott once said, “you miss 100% of the shots you don’t take”. We would believe that as shots increase, so do number of goals. The hexplot reiterates this notion. We see the darkest hexbin in the bottom right, as it is the most dense because scoring a goal in the NHL is no easy feat and the majority of players will be centered around this area. As we increase hexbins to the right and upwards, the color slowly begins to fade which indicates that there is a decreasing positive relationship between shot attempts and goals scored." }, { "code": null, "e": 9499, "s": 9143, "text": "A similar bivariate plot to the hexbin is the Kernel Density Estimation jointplot. A KDE jointplot also uses color to determine where observations are the most dense, but instead of placing them into a pre-defined hexbin, a continuous plot is made using probabilities should new data be introduced. Let’s look at the same Shot Attempts/Goals relationship." }, { "code": null, "e": 9962, "s": 9499, "text": "We can see that the same information is given to us as in the hexbin plot, but this shows a probabilistic view of where the observations are. Instead of the hexbin showing us that most players fall in the low goals/low shot attempts category, we can see an increasing positive relationship in the probability that more shot attempts will equal more goals, with the largest concentration of players falling in the 0–50 shot attempts range and the 0–5 goals range." }, { "code": null, "e": 10579, "s": 9962, "text": "A bivariate relationship can tell us a lot, but just looking at the distributions & scatterplots may not be enough to give us all the information we need about what is happening underneath the surface numbers of the data. A correlation shows us the degree in which one variable’s value influences another. A strong correlation (1.00) indicates that when one variable changes, there is a 100% positive movement in the other variable as well (-1.00 for the opposite side of the scale). Let’s take a look at how important certain variables in the NHL are in terms of correlation. Here is the code to check correlations:" }, { "code": null, "e": 11055, "s": 10579, "text": "Looking at these numbers shows us a lot, notice that the z-axis moving down and to the right represents perfect correlation of a variable with itself. We can see certain variables like points are heavily correlated with shots on goal, shot attempts, and ice time, as the correlation coefficients are all well above 0.5. But statistics and datasets are usually not as intuitive as sport statistics so let’s see how we can make this correlation chart more friendly to the user." }, { "code": null, "e": 11393, "s": 11055, "text": "A heatmap is just a friendlier way of visualizing the correlation table which we produced above. If a correlation coefficient is higher, signaling a more significant correlation between two variables, the color will be darker. Again, reference the z-axis of dark blue to represent a perfect 1:1 correlation between a variable and itself." }, { "code": null, "e": 11629, "s": 11393, "text": "This heatmap just draws our eyes in an easier way to the best & worst correlations. For example, we easily see that shot attempts and shots on goal have the strongest correlation (no duh), and hits has the least correlation with goals." }, { "code": null, "e": 11977, "s": 11629, "text": "Finally, perhaps one of the strongest and most useful tools for any analyst is the Pairplot. A pairplot visualizes the distribution of single variables as well as the bivariate relationship it has with other variables. Simply, we will be creating a bivariate scatter plot for every variable in the DataFrame, and then putting them into one screen." }, { "code": null, "e": 12346, "s": 11977, "text": "This behemoth of a graph has a TON going on, but it is also extremely helpful for getting a good overall view of what we are looking for. We read it the same as we would a bivariate scatter plot. If we see that there are strong positive/negative relationships between two variables, we know that those variables and their relationships are worth investigating further." } ]
Multiplicative Cipher
While using Caesar cipher technique, encrypting and decrypting symbols involves converting the values into numbers with a simple basic procedure of addition or subtraction. If multiplication is used to convert to cipher text, it is called a wrap-around situation. Consider the letters and the associated numbers to be used as shown below − The numbers will be used for multiplication procedure and the associated key is 7. The basic formula to be used in such a scenario to generate a multiplicative cipher is as follows − (Alphabet Number * key)mod(total number of alphabets) The number fetched through output is mapped in the table mentioned above and the corresponding letter is taken as the encrypted letter. The basic modulation function of a multiplicative cipher in Python is as follows − def unshift(key, ch): offset = ord(ch) - ASC_A return chr(((key[0] * (offset + key[1])) % WIDTH) + ASC_A) Note − The advantage with a multiplicative cipher is that it can work with very large keys like 8,953,851. It would take quite a long time for a computer to brute-force through a majority of nine million keys. 10 Lectures 2 hours Total Seminars 10 Lectures 2 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2465, "s": 2292, "text": "While using Caesar cipher technique, encrypting and decrypting symbols involves converting the values into numbers with a simple basic procedure of addition or subtraction." }, { "code": null, "e": 2632, "s": 2465, "text": "If multiplication is used to convert to cipher text, it is called a wrap-around situation. Consider the letters and the associated numbers to be used as shown below −" }, { "code": null, "e": 2815, "s": 2632, "text": "The numbers will be used for multiplication procedure and the associated key is 7. The basic formula to be used in such a scenario to generate a multiplicative cipher is as follows −" }, { "code": null, "e": 2870, "s": 2815, "text": "(Alphabet Number * key)mod(total number of alphabets)\n" }, { "code": null, "e": 3006, "s": 2870, "text": "The number fetched through output is mapped in the table mentioned above and the corresponding letter is taken as the encrypted letter." }, { "code": null, "e": 3089, "s": 3006, "text": "The basic modulation function of a multiplicative cipher in Python is as follows −" }, { "code": null, "e": 3202, "s": 3089, "text": "def unshift(key, ch):\n offset = ord(ch) - ASC_A\n return chr(((key[0] * (offset + key[1])) % WIDTH) + ASC_A)\n" }, { "code": null, "e": 3412, "s": 3202, "text": "Note − The advantage with a multiplicative cipher is that it can work with very large keys like 8,953,851. It would take quite a long time for a computer to brute-force through a majority of nine million keys." }, { "code": null, "e": 3445, "s": 3412, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 3461, "s": 3445, "text": " Total Seminars" }, { "code": null, "e": 3494, "s": 3461, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 3517, "s": 3494, "text": " Stone River ELearning" }, { "code": null, "e": 3524, "s": 3517, "text": " Print" }, { "code": null, "e": 3535, "s": 3524, "text": " Add Notes" } ]
Highlighted line chart with Plotly.Express | by Vaclav Dekanovsky | Towards Data Science
Creating interactive graphs with python’s Plotly.Express from a data frame works like a charm. With a single line of code, you can explore the basic characteristics of your dataset. Adding a few more code-lines you can conjure up a really fancy but very narrative chart. In this exercise, I’ll walk you through the process of drawing a thick colored line on the top of the shaded progress of the concurrent events. It has two enormous benefits: The trend you want to highlight is clearly visibleThe grey background suggests the distribution of other events The trend you want to highlight is clearly visible The grey background suggests the distribution of other events You can create all the charts with me, using the notebook stored on the Github. In this article you will learn: How to install Plotly How to create a line plot using px.line(df, parameteres) How to color only some lines using fig.update_traces or color_discrete_map The order of the lines matter How to position annotations on the Plotly’s chart How to use the annotations to label, highlight, create a legend or describe chart’s area How to add interactive buttons How to use this kind of graph to show changes in ranking I’ll use two datasets. The first about the progress of tourism around the world (tourist arrivals, 215 countries from 1995 to 2018), and the second showing ice-hockey national teams ranking in the last 6 years. The dataset is preprocessed in preprocess.ipynb notebook on github and stored in python’s pickle. Plotly.Express was introduced in the version 4.0.0 of the plotly library and you can easily install it using: # pip pip install plotly# anacondaconda install -c anaconda plotly Plotly Express also requires pandas to be installed, otherwise, you will get this error when you try to import it. [In]: import plotly.express as px[Out]: ImportError: Plotly express requires pandas to be installed. There are additional requirements if you want to use the plotly in Jupyter notebooks. For Jupyter Lab you need jupyterlab-plotly. In a regular notebook, I had to install nbformat (conda install -c anaconda nbformat) towardsdatascience.com Creating the line chart with plotly cannot be easier. The syntax goes as px.line(df, parameters). It looks simple, but the number of parameters is quite big. It’s also important to note that Plotly.Express loves long data structure (in contrast to wide structure), where each category and each value is a column. I’ll draw and line chart for each country, showing yearly tourists in all the 215 countries. Plotly can handle that, but the chart won’t tell you much information. You can switch off/on the lines, using the menu-legend on the right, but it’s so long that you have to scroll through it to find your countries. When you hover over the lines a tooltip pops up providing details about the data. # simple line chart with Plotly Expresspx.line(long_df, x="years", y="visitors", color="Country Name", title="Growth of tourism 1995-2018") Let’s say for your research or marketing purposes you should present the evolution of tourism in Japan 🇯🇵 and Turkey 🇹🇷. So let’s blur the other lines, giving them a grey shade similar to the background, and highlight the Japanese and Turkish lines by coloring them. You have a few options to do so. # first option is to use, .update_traces()fig = px.line(long_df, x="years", y="visitors", color="Country Name")# set color of all traces to lightgreyfig.update_traces({"line":{"color":"lightgrey"}})# color Turkish line to bluefig.update_traces(patch={"line":{"color":"blue", "width":5}}, selector={"legendgroup":"Turkey"})# color Japanese line to redfig.update_traces(patch={"line":{"color":"red", "width":5}}, selector={"legendgroup":"Japan"})# remove the legend, y-axis and add a titlefig.update_layout(title="Tourism Growth in Turkey and Japan", showlegend=False, yaxis={"visible":False})# plot the chartfig.show() Using fig.update_traces({"line":{"color":"lightgrey"}}) changes the color of all lines to light grey. Then we use patch and selector arguments of the .update_traces(). The patch sets the parameters of the line and selector defines to which line they are applied. If you wonder how I know which values to supply to the dictionary, that {"line":{"color":"blue", "width":5} changes the properties of the line and that legendgroup is the right parameter to identify the line by Country name the easiest way is to read fig["data"]. Each Plotly chart is a dictionary and all parameters can be changed when you update this dictionary. [In]: fig["data"][Out]: (Scattergl({ 'hovertemplate': 'Country Name=Aruba<br>years=%{x}<br>visitors=%{y}<extra></extra>', 'legendgroup': 'Aruba', 'line': {'color': 'lightgrey', 'dash': 'solid'}, 'mode': 'lines',... Each plotly chart is a dictionary. Use fig.to_dict() or fig[“data”] to see the values. But the result is not what we wanted. Our traces showing tourism evolution in Japan and Turkey are somewhere in the middle. Some grey lines lie over them and some remain below. We can try Plotly’s parameter category_orders which is meant to influence the order of the lines, but adding category_orders={"Country Name":["Japan","Turkey"]}) makes it even worse. These traces are displayed first and all the grey lines are on top of them. We can supply the full list of countries with Japan and Turkey at the end, but it’s easier to sort the dataframe itself. We .map() order 1 to Japan and 2 to Turkey and fillna(3) to all the other lines, then sort the data frame by this value. # sort the dataframesorted_df = long_df.copy()# map the value ordersorted_df["order"] = sorted_df["Country Name"].map({"Japan": 1, "Turkey": 2}).fillna(3)# sort by this ordersorted_df.sort_values(by=["order","years"], ascending=False, inplace=True) Another option of how to color the lines is to supply a dictionary to the plotly’s color_discrete_map parameter instead of applying fig.update_traces(). The dict structure is {trace_name: color}. {'Aruba': 'lightgrey', 'Zimbabwe': 'lightgrey',... 'Turkey': 'red', 'Japan': 'blue'} To change the width, you can manipulate the Plotly’s backend dictionary directly. for i,d in enumerate(fig["data"]): if d["legendgroup"] in ["Japan","Turkey"]: fig["data"][i]["line"]["width"] = 5 fig.show() Remember that all the code, including these various options on how to influence the look of the Plotly chart is available on Github. The chart still looks quite ugly. We have removed the legend and the axis and we don’t even know how many visitors came to these countries. To show the viewer the important values, we must annotate the plot. Annotations are another dictionaries which are added into .fig.update_layout(..., annotations=[]). This annotation parameter contains a list of dictionaries and each dict is one annotation. turkey_annotation = \[{"xref":"paper", "yref":"paper", "x":0, "y":0.15, "xanchor":'right', "yanchor":"top", "text":'7M', "font":dict(family='Arial', size=12, color="red"), "showarrow":False}, ... other annotations ...] You can influence many parameters of the annotation. Its position, font, and whether there is an arrow pointing from the annotation text to some point on the chart. The coordinates x and y of the text can either refer to the plot or the paper-canvas. In the first case, you specify the position using values displayed on the axes, in the second (0,0) is the bottom left corner of the plot area and (1,1) is the top right corner. The position also depends on the anchor (top-middle-bottom, left-center-right), offsets and adjustments. Each annotation can be modified by setting its font or HTML tags can be applied on the text like <b> or <i>. Look at this gist and the resulting plot to understand the options you have when annotating. If your annotations don’t fit the canvas, you can increase the space around the plot with margin={"l": pixels, "r": px, "t": px, "b": px} inside the .update_layout(). When we play a bit with our tourism chart, we can achieve quite good results. We set xref to paper and set it 0 for the beginning of the line. Adding xanchor="left” will align while text to the left of the plot area. You can set yref=”paper" and try to find the ideal position on the scale between 0 and 1, but it’s easier not to set it as paper and use the exact position e.g. 3 300 000 (note that since python 3.6 you can use underscores in numeric literals due to PEP515 and write the million as 3_300_000) So the complete chart would look like this: I think the most interesting about annotations outside of the plot area is that you can refer x to be on the canvas and y using the coordinates on the chart. You can set, "x":0 (on the canvas), "xanchor":"right and "y": 7_000_000 on the plot, "ynachor":"middle". The chart above is pretty impressive, isn’t it, but what if you can add something more? What if you can give the users the option to highlight whatever data they want? That can be achieved with interactive buttons. Buttons are added via fig.update_layout(updatemenus=[]). You are now probably used to the fact, that each element is described by a python dictionary and buttons are no exception. Each button has several parameters: args: what happens when the button is clicked args2: what happens when it’s unclicked (to create toggle buttons) label: what is written on the button method: whether the button changes the plot, the layout or both Each of args, args2 also accepts 3 parameters — changes to the traces, changes to the layout, and list of traces that are influenced. E.g. args=[ # updates to the traces {"line.color":["blue"],"line.width":5}, # changes to the layout {"title":"Tourism growth in Japan", "annotations": annotation_japan}, # which trace is affected [1,2] ] The button set offers additional parameters influencing their position and style. Similarly to annotations, you can position the buttons around the plot. You can also choose between the single button, set of buttons, or a dropdown. Let’s add buttons to switch on/off our two highlights about tourism in Japan and Turkey. The buttons in Plotly Express are not almighty. If you click on Japan and Turkey buttons without clearing the plot by the second-toggle-click, you will see both colored lines. I didn’t find out how to ensure that one is dyed while all the others are grey. Such complex interaction can be achieved only with the Plotly’s dashboard library — Dash. Its callback actions allow almost every imaginable output. You might also notice that so many lines, Plotly automatically picked WebGL format proven to improve the usability of the JavaScript plots with many data points. When I have first encountered this kind of chart, it displayed the rank of most popular national parks and how it evolved over time. I can’t find this example anymore, so I’ve decided to create one rank evolution chart of my own. I’ll look at the Ice-Hockey national team rankings over the last 5 years. Because I have switched to Linux recently, I gathered the data manually into .ods spreadsheet. You can use pd.read_excel(path, engine="odf) to collect the data, but I had to install pip install odfpy to achieve that. Then you repeat the above code to display the overview of the ranks and highlight your favorite country. Here I had to deal with one new problem though. I wanted to show labels displaying the rank each year, only to this highlighted line (while it is supposed to be hidden for all the others). Again this problem had two solutions with slightly different results. You can either use fig.update_traces() and set both colors and labels. In this case, you must specify both text and mode: fig.update_traces( patch={ "line":{"color":"yellow", "width":5}, "text":sweden["Ranking"].values, "textposition":"top center", "mode":"lines+text", "textfont":{"size":15, "color":"blue"}, }, selector={"legendgroup":"Sweden"}) With this approach, the text is kind of ugly stick to the lines and I did not force it to lift. That can be done when you simply annotate with fig.update_layout(annotations=[]). You iterate over the data frame and prepare a list of dictionaries with each annotation: annotations = []for index, row in sweden.iterrows(): annotations.append( {"x": row["Year"], "y": row["Ranking"], "yshift": 6, "text": row["Ranking"], "xanchor": "center", "yanchor": "bottom", "showarrow":False, "font":{"color":"blue", "size": 15} } ) I hope you liked this introduction to the tricks you can do with python’s Plotly Express. You have learned how to create the line chart containing a plethora of information and how to highlight important a part of this data to your audience. You have seen that there is often more than one approach to achieve the same. Finally, we have used the same approach of colored lines on the background of greyed ones to show changes in ranking. Do you have other use cases for this type of chart? If you want to create inspiring graphics like those in this post, use canva.com (affiliate link, when you click on it and purchase a product, you won't pay more, but I can receive a small reward; you can always write canva.com to your browser to avoid this). Canva offer some free templates and graphics too.Other articles:* Plotly Histogram - Complete Guide* Everything you wanted to know about Kfold train-test split* How to turn a list of addreses into a map All exercises can be walked through in this notebook on Github — Highlighted_Line_Chart_on_Grey_Lines_Background
[ { "code": null, "e": 443, "s": 172, "text": "Creating interactive graphs with python’s Plotly.Express from a data frame works like a charm. With a single line of code, you can explore the basic characteristics of your dataset. Adding a few more code-lines you can conjure up a really fancy but very narrative chart." }, { "code": null, "e": 617, "s": 443, "text": "In this exercise, I’ll walk you through the process of drawing a thick colored line on the top of the shaded progress of the concurrent events. It has two enormous benefits:" }, { "code": null, "e": 729, "s": 617, "text": "The trend you want to highlight is clearly visibleThe grey background suggests the distribution of other events" }, { "code": null, "e": 780, "s": 729, "text": "The trend you want to highlight is clearly visible" }, { "code": null, "e": 842, "s": 780, "text": "The grey background suggests the distribution of other events" }, { "code": null, "e": 954, "s": 842, "text": "You can create all the charts with me, using the notebook stored on the Github. In this article you will learn:" }, { "code": null, "e": 976, "s": 954, "text": "How to install Plotly" }, { "code": null, "e": 1033, "s": 976, "text": "How to create a line plot using px.line(df, parameteres)" }, { "code": null, "e": 1108, "s": 1033, "text": "How to color only some lines using fig.update_traces or color_discrete_map" }, { "code": null, "e": 1138, "s": 1108, "text": "The order of the lines matter" }, { "code": null, "e": 1188, "s": 1138, "text": "How to position annotations on the Plotly’s chart" }, { "code": null, "e": 1277, "s": 1188, "text": "How to use the annotations to label, highlight, create a legend or describe chart’s area" }, { "code": null, "e": 1308, "s": 1277, "text": "How to add interactive buttons" }, { "code": null, "e": 1365, "s": 1308, "text": "How to use this kind of graph to show changes in ranking" }, { "code": null, "e": 1576, "s": 1365, "text": "I’ll use two datasets. The first about the progress of tourism around the world (tourist arrivals, 215 countries from 1995 to 2018), and the second showing ice-hockey national teams ranking in the last 6 years." }, { "code": null, "e": 1674, "s": 1576, "text": "The dataset is preprocessed in preprocess.ipynb notebook on github and stored in python’s pickle." }, { "code": null, "e": 1784, "s": 1674, "text": "Plotly.Express was introduced in the version 4.0.0 of the plotly library and you can easily install it using:" }, { "code": null, "e": 1851, "s": 1784, "text": "# pip pip install plotly# anacondaconda install -c anaconda plotly" }, { "code": null, "e": 1966, "s": 1851, "text": "Plotly Express also requires pandas to be installed, otherwise, you will get this error when you try to import it." }, { "code": null, "e": 2067, "s": 1966, "text": "[In]: import plotly.express as px[Out]: ImportError: Plotly express requires pandas to be installed." }, { "code": null, "e": 2283, "s": 2067, "text": "There are additional requirements if you want to use the plotly in Jupyter notebooks. For Jupyter Lab you need jupyterlab-plotly. In a regular notebook, I had to install nbformat (conda install -c anaconda nbformat)" }, { "code": null, "e": 2306, "s": 2283, "text": "towardsdatascience.com" }, { "code": null, "e": 2619, "s": 2306, "text": "Creating the line chart with plotly cannot be easier. The syntax goes as px.line(df, parameters). It looks simple, but the number of parameters is quite big. It’s also important to note that Plotly.Express loves long data structure (in contrast to wide structure), where each category and each value is a column." }, { "code": null, "e": 3010, "s": 2619, "text": "I’ll draw and line chart for each country, showing yearly tourists in all the 215 countries. Plotly can handle that, but the chart won’t tell you much information. You can switch off/on the lines, using the menu-legend on the right, but it’s so long that you have to scroll through it to find your countries. When you hover over the lines a tooltip pops up providing details about the data." }, { "code": null, "e": 3182, "s": 3010, "text": "# simple line chart with Plotly Expresspx.line(long_df, x=\"years\", y=\"visitors\", color=\"Country Name\", title=\"Growth of tourism 1995-2018\")" }, { "code": null, "e": 3482, "s": 3182, "text": "Let’s say for your research or marketing purposes you should present the evolution of tourism in Japan 🇯🇵 and Turkey 🇹🇷. So let’s blur the other lines, giving them a grey shade similar to the background, and highlight the Japanese and Turkish lines by coloring them. You have a few options to do so." }, { "code": null, "e": 4207, "s": 3482, "text": "# first option is to use, .update_traces()fig = px.line(long_df, x=\"years\", y=\"visitors\", color=\"Country Name\")# set color of all traces to lightgreyfig.update_traces({\"line\":{\"color\":\"lightgrey\"}})# color Turkish line to bluefig.update_traces(patch={\"line\":{\"color\":\"blue\", \"width\":5}}, selector={\"legendgroup\":\"Turkey\"})# color Japanese line to redfig.update_traces(patch={\"line\":{\"color\":\"red\", \"width\":5}}, selector={\"legendgroup\":\"Japan\"})# remove the legend, y-axis and add a titlefig.update_layout(title=\"Tourism Growth in Turkey and Japan\", showlegend=False, yaxis={\"visible\":False})# plot the chartfig.show()" }, { "code": null, "e": 4470, "s": 4207, "text": "Using fig.update_traces({\"line\":{\"color\":\"lightgrey\"}}) changes the color of all lines to light grey. Then we use patch and selector arguments of the .update_traces(). The patch sets the parameters of the line and selector defines to which line they are applied." }, { "code": null, "e": 4835, "s": 4470, "text": "If you wonder how I know which values to supply to the dictionary, that {\"line\":{\"color\":\"blue\", \"width\":5} changes the properties of the line and that legendgroup is the right parameter to identify the line by Country name the easiest way is to read fig[\"data\"]. Each Plotly chart is a dictionary and all parameters can be changed when you update this dictionary." }, { "code": null, "e": 5066, "s": 4835, "text": "[In]: fig[\"data\"][Out]: (Scattergl({ 'hovertemplate': 'Country Name=Aruba<br>years=%{x}<br>visitors=%{y}<extra></extra>', 'legendgroup': 'Aruba', 'line': {'color': 'lightgrey', 'dash': 'solid'}, 'mode': 'lines',..." }, { "code": null, "e": 5153, "s": 5066, "text": "Each plotly chart is a dictionary. Use fig.to_dict() or fig[“data”] to see the values." }, { "code": null, "e": 5330, "s": 5153, "text": "But the result is not what we wanted. Our traces showing tourism evolution in Japan and Turkey are somewhere in the middle. Some grey lines lie over them and some remain below." }, { "code": null, "e": 5589, "s": 5330, "text": "We can try Plotly’s parameter category_orders which is meant to influence the order of the lines, but adding category_orders={\"Country Name\":[\"Japan\",\"Turkey\"]}) makes it even worse. These traces are displayed first and all the grey lines are on top of them." }, { "code": null, "e": 5831, "s": 5589, "text": "We can supply the full list of countries with Japan and Turkey at the end, but it’s easier to sort the dataframe itself. We .map() order 1 to Japan and 2 to Turkey and fillna(3) to all the other lines, then sort the data frame by this value." }, { "code": null, "e": 6080, "s": 5831, "text": "# sort the dataframesorted_df = long_df.copy()# map the value ordersorted_df[\"order\"] = sorted_df[\"Country Name\"].map({\"Japan\": 1, \"Turkey\": 2}).fillna(3)# sort by this ordersorted_df.sort_values(by=[\"order\",\"years\"], ascending=False, inplace=True)" }, { "code": null, "e": 6276, "s": 6080, "text": "Another option of how to color the lines is to supply a dictionary to the plotly’s color_discrete_map parameter instead of applying fig.update_traces(). The dict structure is {trace_name: color}." }, { "code": null, "e": 6361, "s": 6276, "text": "{'Aruba': 'lightgrey', 'Zimbabwe': 'lightgrey',... 'Turkey': 'red', 'Japan': 'blue'}" }, { "code": null, "e": 6443, "s": 6361, "text": "To change the width, you can manipulate the Plotly’s backend dictionary directly." }, { "code": null, "e": 6585, "s": 6443, "text": "for i,d in enumerate(fig[\"data\"]): if d[\"legendgroup\"] in [\"Japan\",\"Turkey\"]: fig[\"data\"][i][\"line\"][\"width\"] = 5 fig.show()" }, { "code": null, "e": 6718, "s": 6585, "text": "Remember that all the code, including these various options on how to influence the look of the Plotly chart is available on Github." }, { "code": null, "e": 7116, "s": 6718, "text": "The chart still looks quite ugly. We have removed the legend and the axis and we don’t even know how many visitors came to these countries. To show the viewer the important values, we must annotate the plot. Annotations are another dictionaries which are added into .fig.update_layout(..., annotations=[]). This annotation parameter contains a list of dictionaries and each dict is one annotation." }, { "code": null, "e": 7339, "s": 7116, "text": "turkey_annotation = \\[{\"xref\":\"paper\", \"yref\":\"paper\", \"x\":0, \"y\":0.15, \"xanchor\":'right', \"yanchor\":\"top\", \"text\":'7M', \"font\":dict(family='Arial', size=12, color=\"red\"), \"showarrow\":False}, ... other annotations ...]" }, { "code": null, "e": 7768, "s": 7339, "text": "You can influence many parameters of the annotation. Its position, font, and whether there is an arrow pointing from the annotation text to some point on the chart. The coordinates x and y of the text can either refer to the plot or the paper-canvas. In the first case, you specify the position using values displayed on the axes, in the second (0,0) is the bottom left corner of the plot area and (1,1) is the top right corner." }, { "code": null, "e": 7982, "s": 7768, "text": "The position also depends on the anchor (top-middle-bottom, left-center-right), offsets and adjustments. Each annotation can be modified by setting its font or HTML tags can be applied on the text like <b> or <i>." }, { "code": null, "e": 8075, "s": 7982, "text": "Look at this gist and the resulting plot to understand the options you have when annotating." }, { "code": null, "e": 8242, "s": 8075, "text": "If your annotations don’t fit the canvas, you can increase the space around the plot with margin={\"l\": pixels, \"r\": px, \"t\": px, \"b\": px} inside the .update_layout()." }, { "code": null, "e": 8752, "s": 8242, "text": "When we play a bit with our tourism chart, we can achieve quite good results. We set xref to paper and set it 0 for the beginning of the line. Adding xanchor=\"left” will align while text to the left of the plot area. You can set yref=”paper\" and try to find the ideal position on the scale between 0 and 1, but it’s easier not to set it as paper and use the exact position e.g. 3 300 000 (note that since python 3.6 you can use underscores in numeric literals due to PEP515 and write the million as 3_300_000)" }, { "code": null, "e": 8796, "s": 8752, "text": "So the complete chart would look like this:" }, { "code": null, "e": 9059, "s": 8796, "text": "I think the most interesting about annotations outside of the plot area is that you can refer x to be on the canvas and y using the coordinates on the chart. You can set, \"x\":0 (on the canvas), \"xanchor\":\"right and \"y\": 7_000_000 on the plot, \"ynachor\":\"middle\"." }, { "code": null, "e": 9274, "s": 9059, "text": "The chart above is pretty impressive, isn’t it, but what if you can add something more? What if you can give the users the option to highlight whatever data they want? That can be achieved with interactive buttons." }, { "code": null, "e": 9454, "s": 9274, "text": "Buttons are added via fig.update_layout(updatemenus=[]). You are now probably used to the fact, that each element is described by a python dictionary and buttons are no exception." }, { "code": null, "e": 9490, "s": 9454, "text": "Each button has several parameters:" }, { "code": null, "e": 9536, "s": 9490, "text": "args: what happens when the button is clicked" }, { "code": null, "e": 9603, "s": 9536, "text": "args2: what happens when it’s unclicked (to create toggle buttons)" }, { "code": null, "e": 9640, "s": 9603, "text": "label: what is written on the button" }, { "code": null, "e": 9704, "s": 9640, "text": "method: whether the button changes the plot, the layout or both" }, { "code": null, "e": 9843, "s": 9704, "text": "Each of args, args2 also accepts 3 parameters — changes to the traces, changes to the layout, and list of traces that are influenced. E.g." }, { "code": null, "e": 10081, "s": 9843, "text": "args=[ # updates to the traces {\"line.color\":[\"blue\"],\"line.width\":5}, # changes to the layout {\"title\":\"Tourism growth in Japan\", \"annotations\": annotation_japan}, # which trace is affected [1,2] ]" }, { "code": null, "e": 10313, "s": 10081, "text": "The button set offers additional parameters influencing their position and style. Similarly to annotations, you can position the buttons around the plot. You can also choose between the single button, set of buttons, or a dropdown." }, { "code": null, "e": 10402, "s": 10313, "text": "Let’s add buttons to switch on/off our two highlights about tourism in Japan and Turkey." }, { "code": null, "e": 10807, "s": 10402, "text": "The buttons in Plotly Express are not almighty. If you click on Japan and Turkey buttons without clearing the plot by the second-toggle-click, you will see both colored lines. I didn’t find out how to ensure that one is dyed while all the others are grey. Such complex interaction can be achieved only with the Plotly’s dashboard library — Dash. Its callback actions allow almost every imaginable output." }, { "code": null, "e": 10969, "s": 10807, "text": "You might also notice that so many lines, Plotly automatically picked WebGL format proven to improve the usability of the JavaScript plots with many data points." }, { "code": null, "e": 11273, "s": 10969, "text": "When I have first encountered this kind of chart, it displayed the rank of most popular national parks and how it evolved over time. I can’t find this example anymore, so I’ve decided to create one rank evolution chart of my own. I’ll look at the Ice-Hockey national team rankings over the last 5 years." }, { "code": null, "e": 11490, "s": 11273, "text": "Because I have switched to Linux recently, I gathered the data manually into .ods spreadsheet. You can use pd.read_excel(path, engine=\"odf) to collect the data, but I had to install pip install odfpy to achieve that." }, { "code": null, "e": 11784, "s": 11490, "text": "Then you repeat the above code to display the overview of the ranks and highlight your favorite country. Here I had to deal with one new problem though. I wanted to show labels displaying the rank each year, only to this highlighted line (while it is supposed to be hidden for all the others)." }, { "code": null, "e": 11976, "s": 11784, "text": "Again this problem had two solutions with slightly different results. You can either use fig.update_traces() and set both colors and labels. In this case, you must specify both text and mode:" }, { "code": null, "e": 12252, "s": 11976, "text": "fig.update_traces( patch={ \"line\":{\"color\":\"yellow\", \"width\":5}, \"text\":sweden[\"Ranking\"].values, \"textposition\":\"top center\", \"mode\":\"lines+text\", \"textfont\":{\"size\":15, \"color\":\"blue\"}, }, selector={\"legendgroup\":\"Sweden\"})" }, { "code": null, "e": 12519, "s": 12252, "text": "With this approach, the text is kind of ugly stick to the lines and I did not force it to lift. That can be done when you simply annotate with fig.update_layout(annotations=[]). You iterate over the data frame and prepare a list of dictionaries with each annotation:" }, { "code": null, "e": 12850, "s": 12519, "text": "annotations = []for index, row in sweden.iterrows(): annotations.append( {\"x\": row[\"Year\"], \"y\": row[\"Ranking\"], \"yshift\": 6, \"text\": row[\"Ranking\"], \"xanchor\": \"center\", \"yanchor\": \"bottom\", \"showarrow\":False, \"font\":{\"color\":\"blue\", \"size\": 15} } )" }, { "code": null, "e": 13288, "s": 12850, "text": "I hope you liked this introduction to the tricks you can do with python’s Plotly Express. You have learned how to create the line chart containing a plethora of information and how to highlight important a part of this data to your audience. You have seen that there is often more than one approach to achieve the same. Finally, we have used the same approach of colored lines on the background of greyed ones to show changes in ranking." }, { "code": null, "e": 13340, "s": 13288, "text": "Do you have other use cases for this type of chart?" }, { "code": null, "e": 13802, "s": 13340, "text": "If you want to create inspiring graphics like those in this post, use canva.com (affiliate link, when you click on it and purchase a product, you won't pay more, but I can receive a small reward; you can always write canva.com to your browser to avoid this). Canva offer some free templates and graphics too.Other articles:* Plotly Histogram - Complete Guide* Everything you wanted to know about Kfold train-test split* How to turn a list of addreses into a map" } ]
Look and Say Pattern | Practice | GeeksforGeeks
Given an integer n. Return the nth row of the following look-and-say pattern. 1 11 21 1211 111221 Look-and-Say Pattern: To generate a member of the sequence from the previous member, read off the digits of the previous member, counting the number of digits in groups of the same digit. For example: 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. 1211 is read off as "one 1, one 2, then two 1s" or 111221. 111221 is read off as "three 1s, two 2s, then one 1" or 312211. Example 1: Input: n = 5 Output: 111221 Explanation: The 5th row of the given pattern will be 111221. Example 2: Input: n = 3 Output: 21 Explanation: The 3rd row of the given pattern will be 21. Your Task: You dont need to read input or print anything. Complete the function lookandsay() which takes integer n as input parameter and returns a string denoting the contents of the nth row of given pattern. Expected Time Complexity: O(2n) Expected Auxiliary Space: O(2n-1) Constraints: 1 ≤ n ≤ 30 0 tirtha19025682 weeks ago class Solution{ static String lookandsay(int n) { if(n == 1) { return "1"; } StringBuilder sb = new StringBuilder(""); String s = "1"; for(int i=1;i<n;i++) { sb = helper(s); s = sb.toString(); } return sb.toString(); } static StringBuilder helper(String s) { StringBuilder sb = new StringBuilder(""); if(s.length() == 1) { sb.append(1); sb.append(s.charAt(0)); return sb; } for(int i=0;i<s.length()-1;i++) { int cnt = 1; while(i<s.length()-1 && s.charAt(i) == s.charAt(i+1)) { cnt++; i++; } sb.append(cnt); sb.append(s.charAt(i)); cnt = 1; } if(s.charAt(s.length()-1) != s.charAt(s.length()-2) ) { sb.append(1); sb.append(s.charAt(s.length()-1)); } return sb; } } 0 sanketgharatkar1231 month ago CPP online best solution TIME:0.0/1.3 sec string lookandsay(int n) { // code here string ans="1"; for(int i=2;i<=n;i++) { int count=0; string temp_ans; int j=0; char temp=ans[0]; while(j<ans.size()) { if(ans[j]==temp) { count++; } else { temp_ans.push_back(count+48); temp_ans.push_back(temp); temp=ans[j]; count=1; } j++; } temp_ans.push_back(count+48); temp_ans.push_back(temp); ans=temp_ans; } return ans; } 0 tapanmanu20001 month ago string lookandsay(int n) { if(n == 1) return "1"; string s = "1"; int x = s.length(); while(--n){ string res = ""; for(int i = 0; i < s.length();){ char current = s[i]; //cout<<s[i]; int count = 1; int j = i + 1; for(j = i + 1; (s[j] != '\0') && (s[i] == s[j]); j++){ count++; } i = j; res.append(to_string(count)); res.append(to_string(current-'0')); } s = res; } return s; } +1 kartikeyashokgautam2 months ago Simple JAVA Solution :- { // for the nth number, we just need to count characters of the (n-1)th number,// for the (n-1)th number, we just need to count characters of the (n-2)th number,// ...// hence, we get the idea of recursion here if(n == 1) return "1"; StringBuilder res = new StringBuilder(); String s = lookandsay(n-1) + "0"; // recursively call for (n-1) th number, "0" is only for the edge case at the end of the loop with s.charAt(i+1)for(int i=0, count=1; i < s.length()-1; i++, count++){ if(s.charAt(i+1) != s.charAt(i)){ res.append(count).append(s.charAt(i)); // if next digit is different, then append the count so far and the digit itself, then set count to zerocount=0; }} return res.toString(); } 0 mulangacanon2 months ago def lookandsay(self, n): i = 1 nterm = str() str1 = "1" while i < n: nterm = self.next_number(str1) str1 = nterm i += 1 return str1 def next_number(self, s): result = [] i = 0 while i < len(s): count = 1 while i + 1 < len(s) and s[i] == s[i + 1]: i += 1 count += 1 result.append(str(count) + s[i]) i += 1 return "".join(result) 0 mulangacanon This comment was deleted. +1 dakshraghuvanshi7613 months ago Python3 Solution (Runtime - 0.0/1.0) class Solution: def countAndSay(self, n): self.n = n if self.n == 1: return "1".format(str) # Calling our function one more time(recursion). s = self.countAndSay(self.n-1) s = str(s) # Setting the frequency(counter) = 0 and the result as empty string counter = 0 res = "" # Making groups for same consecutive numbers for i in range(0 ,len(s)): counter += 1 if i == len(s)-1 or s[i] != s[i+1]: res = res + str(counter) + s[i] counter = 0 return res 0 rogueninjaofkonoha3 months ago static String lookandsay(int n) { //your code here if(n==1) return "1"; else if(n==2) return "11"; String s = lookandsay(n-1); String ans = new String(); int count = 1; for(int i=0;i< s.length()-1;i++) { if(s.charAt(i+1) == s.charAt(i)) { count++; } else { ans = ans + count + (s.charAt(i) -'0'); count = 1; } } ans = ans + count + (s.charAt(s.length()-1) -'0'); return ans; } +1 ayerajkumar3 months ago Simple Java Recursive Program class Solution{ static String lookandsay(int n) { String atr=""; if(n==1) { return "1"; } if(n==2) { return "11"; } if(n>2) { String str =""; str=lookandsay(n-1); // str="1211"; int m=str.length(); int count=1; int i=0; for( i=0; i<m-1; i++){ if(str.charAt(i)==str.charAt(i+1)) count++; if(str.charAt(i)!=str.charAt(i+1)){ atr=atr+count+str.charAt(i); count=1; } } atr=atr+count+str.charAt(i); } return atr; }} 0 e20040806 months ago runtime: 0.0/1.0 class Solution: def lookandsay(self, n): if n == 1: return '1' cur = None count = 0 num = '' for digit in self.lookandsay(n - 1) + ' ': if digit == cur: count += 1 else: if cur: num += str(count + 1) + cur count = 0 cur = digit return num 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": 358, "s": 238, "text": "Given an integer n. Return the nth row of the following look-and-say pattern.\n1\n11\n21\n1211\n111221\nLook-and-Say Pattern:" }, { "code": null, "e": 537, "s": 358, "text": "To generate a member of the sequence from the previous member, read off the digits of the previous member, counting the number of digits in groups of the same digit. For example:" }, { "code": null, "e": 569, "s": 537, "text": "1 is read off as \"one 1\" or 11." }, { "code": null, "e": 603, "s": 569, "text": "11 is read off as \"two 1s\" or 21." }, { "code": null, "e": 650, "s": 603, "text": "21 is read off as \"one 2, then one 1\" or 1211." }, { "code": null, "e": 709, "s": 650, "text": "1211 is read off as \"one 1, one 2, then two 1s\" or 111221." }, { "code": null, "e": 773, "s": 709, "text": "111221 is read off as \"three 1s, two 2s, then one 1\" or 312211." }, { "code": null, "e": 787, "s": 775, "text": "\nExample 1:" }, { "code": null, "e": 877, "s": 787, "text": "Input:\nn = 5\nOutput: 111221\nExplanation: The 5th row of the given pattern\nwill be 111221." }, { "code": null, "e": 888, "s": 877, "text": "Example 2:" }, { "code": null, "e": 970, "s": 888, "text": "Input:\nn = 3\nOutput: 21\nExplanation: The 3rd row of the given pattern\nwill be 21." }, { "code": null, "e": 1183, "s": 970, "text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function lookandsay() which takes integer n as input parameter and returns a string denoting the contents of the nth row of given pattern." }, { "code": null, "e": 1252, "s": 1183, "text": "\nExpected Time Complexity: O(2n)\nExpected Auxiliary Space: O(2n-1) " }, { "code": null, "e": 1277, "s": 1252, "text": "\nConstraints:\n1 ≤ n ≤ 30" }, { "code": null, "e": 1279, "s": 1277, "text": "0" }, { "code": null, "e": 1304, "s": 1279, "text": "tirtha19025682 weeks ago" }, { "code": null, "e": 2049, "s": 1304, "text": "class Solution{\n static String lookandsay(int n) {\n if(n == 1) {\n return \"1\";\n }\n StringBuilder sb = new StringBuilder(\"\");\n String s = \"1\";\n for(int i=1;i<n;i++) {\n sb = helper(s);\n s = sb.toString();\n }\n return sb.toString();\n }\n\nstatic StringBuilder helper(String s) {\n StringBuilder sb = new StringBuilder(\"\");\n \n if(s.length() == 1) {\n sb.append(1);\n sb.append(s.charAt(0));\n return sb;\n }\n \n for(int i=0;i<s.length()-1;i++) {\n int cnt = 1;\n while(i<s.length()-1 && s.charAt(i) == s.charAt(i+1)) {\n cnt++;\n i++;\n }\n sb.append(cnt);\n sb.append(s.charAt(i));\n cnt = 1;\n }\n \n if(s.charAt(s.length()-1) != s.charAt(s.length()-2) ) {\n sb.append(1);\n sb.append(s.charAt(s.length()-1));\n }\n \n return sb;\n}\n\n}\n" }, { "code": null, "e": 2051, "s": 2049, "text": "0" }, { "code": null, "e": 2081, "s": 2051, "text": "sanketgharatkar1231 month ago" }, { "code": null, "e": 2123, "s": 2081, "text": "CPP online best solution TIME:0.0/1.3 sec" }, { "code": null, "e": 2807, "s": 2123, "text": " string lookandsay(int n) { // code here string ans=\"1\"; for(int i=2;i<=n;i++) { int count=0; string temp_ans; int j=0; char temp=ans[0]; while(j<ans.size()) { if(ans[j]==temp) { count++; } else { temp_ans.push_back(count+48); temp_ans.push_back(temp); temp=ans[j]; count=1; } j++; } temp_ans.push_back(count+48); temp_ans.push_back(temp);" }, { "code": null, "e": 2893, "s": 2807, "text": " ans=temp_ans; } return ans; } " }, { "code": null, "e": 2897, "s": 2895, "text": "0" }, { "code": null, "e": 2922, "s": 2897, "text": "tapanmanu20001 month ago" }, { "code": null, "e": 3613, "s": 2922, "text": "string lookandsay(int n) {\n if(n == 1) return \"1\";\n string s = \"1\";\n int x = s.length();\n while(--n){\n string res = \"\";\n for(int i = 0; i < s.length();){\n char current = s[i];\n //cout<<s[i];\n int count = 1;\n int j = i + 1;\n for(j = i + 1; (s[j] != '\\0') \n \t\t\t\t&& (s[i] == s[j]); j++){\n count++;\n }\n i = j;\n res.append(to_string(count));\n \n res.append(to_string(current-'0'));\n \n \n }\n s = res;\n }\n return s;\n } " }, { "code": null, "e": 3616, "s": 3613, "text": "+1" }, { "code": null, "e": 3648, "s": 3616, "text": "kartikeyashokgautam2 months ago" }, { "code": null, "e": 3672, "s": 3648, "text": "Simple JAVA Solution :-" }, { "code": null, "e": 3931, "s": 3672, "text": "{ // for the nth number, we just need to count characters of the (n-1)th number,// for the (n-1)th number, we just need to count characters of the (n-2)th number,// ...// hence, we get the idea of recursion here if(n == 1) return \"1\";" }, { "code": null, "e": 3972, "s": 3931, "text": "StringBuilder res = new StringBuilder();" }, { "code": null, "e": 4007, "s": 3972, "text": "String s = lookandsay(n-1) + \"0\"; " }, { "code": null, "e": 4250, "s": 4009, "text": "// recursively call for (n-1) th number, \"0\" is only for the edge case at the end of the loop with s.charAt(i+1)for(int i=0, count=1; i < s.length()-1; i++, count++){ if(s.charAt(i+1) != s.charAt(i)){ res.append(count).append(s.charAt(i));" }, { "code": null, "e": 4372, "s": 4252, "text": " // if next digit is different, then append the count so far and the digit itself, then set count to zerocount=0; }}" }, { "code": null, "e": 4405, "s": 4372, "text": "return res.toString(); }" }, { "code": null, "e": 4407, "s": 4405, "text": "0" }, { "code": null, "e": 4432, "s": 4407, "text": "mulangacanon2 months ago" }, { "code": null, "e": 4928, "s": 4432, "text": "def lookandsay(self, n): i = 1 nterm = str() str1 = \"1\" while i < n: nterm = self.next_number(str1) str1 = nterm i += 1 return str1 def next_number(self, s): result = [] i = 0 while i < len(s): count = 1 while i + 1 < len(s) and s[i] == s[i + 1]: i += 1 count += 1 result.append(str(count) + s[i]) i += 1 return \"\".join(result)" }, { "code": null, "e": 4930, "s": 4928, "text": "0" }, { "code": null, "e": 4943, "s": 4930, "text": "mulangacanon" }, { "code": null, "e": 4969, "s": 4943, "text": "This comment was deleted." }, { "code": null, "e": 4972, "s": 4969, "text": "+1" }, { "code": null, "e": 5004, "s": 4972, "text": "dakshraghuvanshi7613 months ago" }, { "code": null, "e": 5041, "s": 5004, "text": "Python3 Solution (Runtime - 0.0/1.0)" }, { "code": null, "e": 5667, "s": 5043, "text": "class Solution:\n def countAndSay(self, n):\n self.n = n \n if self.n == 1:\n return \"1\".format(str)\n\n # Calling our function one more time(recursion).\n s = self.countAndSay(self.n-1)\n s = str(s)\n\n # Setting the frequency(counter) = 0 and the result as empty string\n counter = 0 \n res = \"\"\n\n \n # Making groups for same consecutive numbers \n for i in range(0 ,len(s)):\n counter += 1\n if i == len(s)-1 or s[i] != s[i+1]:\n res = res + str(counter) + s[i]\n counter = 0\n\n return res" }, { "code": null, "e": 5671, "s": 5669, "text": "0" }, { "code": null, "e": 5702, "s": 5671, "text": "rogueninjaofkonoha3 months ago" }, { "code": null, "e": 6268, "s": 5702, "text": " static String lookandsay(int n) {\n //your code here\n if(n==1)\n return \"1\";\n else if(n==2)\n return \"11\";\n String s = lookandsay(n-1);\n String ans = new String();\n int count = 1;\n for(int i=0;i< s.length()-1;i++) {\n if(s.charAt(i+1) == s.charAt(i)) {\n count++;\n }\n else {\n ans = ans + count + (s.charAt(i) -'0');\n count = 1;\n }\n }\n ans = ans + count + (s.charAt(s.length()-1) -'0');\n return ans;\n}" }, { "code": null, "e": 6271, "s": 6268, "text": "+1" }, { "code": null, "e": 6295, "s": 6271, "text": "ayerajkumar3 months ago" }, { "code": null, "e": 6325, "s": 6295, "text": "Simple Java Recursive Program" }, { "code": null, "e": 7012, "s": 6325, "text": "class Solution{ static String lookandsay(int n) { String atr=\"\"; if(n==1) { return \"1\"; } if(n==2) { return \"11\"; } if(n>2) { String str =\"\"; str=lookandsay(n-1); // str=\"1211\"; int m=str.length(); int count=1; int i=0; for( i=0; i<m-1; i++){ if(str.charAt(i)==str.charAt(i+1)) count++; if(str.charAt(i)!=str.charAt(i+1)){ atr=atr+count+str.charAt(i); count=1; } } atr=atr+count+str.charAt(i); } return atr; }}" }, { "code": null, "e": 7014, "s": 7012, "text": "0" }, { "code": null, "e": 7035, "s": 7014, "text": "e20040806 months ago" }, { "code": null, "e": 7052, "s": 7035, "text": "runtime: 0.0/1.0" }, { "code": null, "e": 7467, "s": 7052, "text": "class Solution:\n def lookandsay(self, n):\n if n == 1:\n return '1'\n cur = None\n count = 0\n num = ''\n for digit in self.lookandsay(n - 1) + ' ':\n if digit == cur:\n count += 1\n else:\n if cur:\n num += str(count + 1) + cur\n count = 0\n cur = digit\n return num" }, { "code": null, "e": 7613, "s": 7467, "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": 7649, "s": 7613, "text": " Login to access your submissions. " }, { "code": null, "e": 7659, "s": 7649, "text": "\nProblem\n" }, { "code": null, "e": 7669, "s": 7659, "text": "\nContest\n" }, { "code": null, "e": 7732, "s": 7669, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7880, "s": 7732, "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": 8088, "s": 7880, "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": 8194, "s": 8088, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
one to one mapping in hibernate | one to one relationship | foreign
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws One to one is a relationship in relational database, it will occur when a parent table record has zero or one child record in child table. In this tutorial, we are going to implement the one to one mapping in hibernate (relationship) using xml configuration. One to one mapping in hibernate can be achieved in two ways. One to one mapping with foreign key One to one mapping with primary key In this example, we are implementing the one to one mapping with foreign key using xml configuration. One to one mapping in hibernate is like many to one relationship, but in the many to one relationship a foreign key column can allow duplicate values. If we prevent the duplicate values in foreign key column then it will act as one to one mapping. To do so.. To prevent the duplicates in foreign key column, hibernate provides two attributes like unique=”true” and not-null=”true”. We can apply these attributes in <many-to-one> in hibernate mapping file (hbm.xml). In order to get one to one relationship between two objects, in child class pojo class we need a reference variable of type parent class. If we take the Person and Passport, there is a relationship between Person to Passport is one to one relationship. Because one Person can have only one Passport. We can implement this relationship using hibernate one to one mapping. Project Structure : Required Dependencies : <dependencies> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.0.Final</version> </dependency> <!-- MySQL Driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.0.5</version> </dependency> </dependencies> Hibernate POJO Classes : Person.java package com.onlinetutorialspoint.hibernate.pojo; public class Person { private int personId; private String personName; public int getPersonId() { return personId; } public void setPersonId(int personId) { this.personId = personId; } public String getPersonName() { return personName; } public void setPersonName(String personName) { this.personName = personName; } } Passport.java package com.onlinetutorialspoint.hibernate.pojo; import java.util.Date; public class Passport { private int passportNumber; private Date issudDate; private Date expireDate; private Person person; public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public int getPassportNumber() { return passportNumber; } public void setPassportNumber(int passportNumber) { this.passportNumber = passportNumber; } public Date getIssudDate() { return issudDate; } public void setIssudDate(Date issudDate) { this.issudDate = issudDate; } public Date getExpireDate() { return expireDate; } public void setExpireDate(Date expireDate) { this.expireDate = expireDate; } } Hibernate Mapping Files : person.hbm.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.onlinetutorialspoint.hibernate.pojo.Person" table="person"> <id name="personId" column="personid" /> <property name="personName" column="personname" /> </class> </hibernate-mapping> passport.hbm.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.onlinetutorialspoint.hibernate.pojo.Passport" table="passport"> <id name="passportNumber" column="ppid" /> <property name="issudDate" column="idate" /> <property name="expireDate" column="edate" /> <many-to-one name="person" class="com.onlinetutorialspoint.hibernate.pojo.Person" column="per_id" unique="true" not-null="true" cascade="all"/> </class> </hibernate-mapping> Hibenate Utility: HibernateUtil.java package com.onlinetutorialspoint.util; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; public class HibernateUtil { private HibernateUtil() { } private static SessionFactory sessionFactory; public static synchronized SessionFactory getInstnce() { if (sessionFactory == null) { Configuration configuration = new Configuration().configure("hibernate.cfg.xml"); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()); sessionFactory = configuration.buildSessionFactory(builder.build()); } return sessionFactory; } } Well! we are almost done. Run the application Main.java import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import com.onlinetutorialspoint.hibernate.pojo.Passport; import com.onlinetutorialspoint.hibernate.pojo.Person; import com.onlinetutorialspoint.util.HibernateUtil; public class Main { public static void main(String[] args) { SessionFactory sessionFactory = HibernateUtil.getInstnce(); Session session = sessionFactory.openSession(); Person person = new Person(); person.setPersonId(1001); person.setPersonName("Chandrashekhar"); Passport passport = new Passport(); passport.setPassportNumber(12346856); passport.setExpireDate(new Date()); passport.setIssudDate(new Date()); passport.setPerson(person); Transaction transaction = session.beginTransaction(); session.save(passport); transaction.commit(); session.close(); sessionFactory.close(); } } Output : Hibernate: select person_.personid, person_.personname as personna2_1_ from person person_ where person_.personid=? Hibernate: insert into person (personname, personid) values (?, ?) Hibernate: insert into passport (idate, edate, per_id, ppid) values (?, ?, ?, ?) Database Output : Happy Learning 🙂 One to One Mapping in Hibernate Example File size: 20 KB Downloads: 818 Hibernate One to One Mapping using primary key (XML) Hibernate Many to Many Mapping Example (XML) Hibernate Composite Key Mapping Example Hibernate One To Many Example (XML Mapping) Many to One Mapping in Hibernate Example Hibernate Filter Example Xml Configuration hbm2ddl.auto Example in Hibernate XML Config Basic Hibernate Example with XML Configuration Calling Stored Procedures in Hibernate Hibernate Right Join Example Hibernate One To Many Using Annotations Custom Generator Class in Hibernate Hibernate Inheritance Mapping Strategies hibernate update query example Table per Concrete Class in Hibernate Inheritance Hibernate One to One Mapping using primary key (XML) Hibernate Many to Many Mapping Example (XML) Hibernate Composite Key Mapping Example Hibernate One To Many Example (XML Mapping) Many to One Mapping in Hibernate Example Hibernate Filter Example Xml Configuration hbm2ddl.auto Example in Hibernate XML Config Basic Hibernate Example with XML Configuration Calling Stored Procedures in Hibernate Hibernate Right Join Example Hibernate One To Many Using Annotations Custom Generator Class in Hibernate Hibernate Inheritance Mapping Strategies hibernate update query example Table per Concrete Class in Hibernate Inheritance Milana Travis October 25, 2017 at 11:21 am - Reply Thank you very much for your blog. I enjoyed reading this article. Milana Travis October 25, 2017 at 11:21 am - Reply Thank you very much for your blog. I enjoyed reading this article. Thank you very much for your blog. I enjoyed reading this article. Δ Hibernate – Introduction Hibernate – Advantages Hibernate – Download and Setup Hibernate – Sql Dialect list Hibernate – Helloworld – XML Hibernate – Install Tools in Eclipse Hibernate – Object States Hibernate – Helloworld – Annotations Hibernate – One to One Mapping – XML Hibernate – One to One Mapping foreign key – XML Hibernate – One To Many -XML Hibernate – One To Many – Annotations Hibernate – Many to Many Mapping – XML Hibernate – Many to One – XML Hibernate – Composite Key Mapping Hibernate – Named Query Hibernate – Native SQL Query Hibernate – load() vs get() Hibernate Criteria API with Example Hibernate – Restrictions Hibernate – Projection Hibernate – Query Language (HQL) Hibernate – Groupby Criteria HQL Hibernate – Orderby Criteria Hibernate – HQLSelect Operation Hibernate – HQL Update, Delete Hibernate – Update Query Hibernate – Update vs Merge Hibernate – Right Join Hibernate – Left Join Hibernate – Pagination Hibernate – Generator Classes Hibernate – Custom Generator Hibernate – Inheritance Mappings Hibernate – Table per Class Hibernate – Table per Sub Class Hibernate – Table per Concrete Class Hibernate – Table per Class Annotations Hibernate – Stored Procedures Hibernate – @Formula Annotation Hibernate – Singleton SessionFactory Hibernate – Interceptor hbm2ddl.auto Example in Hibernate XML Config Hibernate – First Level Cache
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 657, "s": 398, "text": "One to one is a relationship in relational database, it will occur when a parent table record has zero or one child record in child table. In this tutorial, we are going to implement the one to one mapping in hibernate (relationship) using xml configuration." }, { "code": null, "e": 718, "s": 657, "text": "One to one mapping in hibernate can be achieved in two ways." }, { "code": null, "e": 754, "s": 718, "text": "One to one mapping with foreign key" }, { "code": null, "e": 790, "s": 754, "text": "One to one mapping with primary key" }, { "code": null, "e": 892, "s": 790, "text": "In this example, we are implementing the one to one mapping with foreign key using xml configuration." }, { "code": null, "e": 1140, "s": 892, "text": "One to one mapping in hibernate is like many to one relationship, but in the many to one relationship a foreign key column can allow duplicate values. If we prevent the duplicate values in foreign key column then it will act as one to one mapping." }, { "code": null, "e": 1358, "s": 1140, "text": "To do so.. To prevent the duplicates in foreign key column, hibernate provides two attributes like unique=”true” and not-null=”true”. We can apply these attributes in <many-to-one> in hibernate mapping file (hbm.xml)." }, { "code": null, "e": 1496, "s": 1358, "text": "In order to get one to one relationship between two objects, in child class pojo class we need a reference variable of type parent class." }, { "code": null, "e": 1729, "s": 1496, "text": "If we take the Person and Passport, there is a relationship between Person to Passport is one to one relationship. Because one Person can have only one Passport. We can implement this relationship using hibernate one to one mapping." }, { "code": null, "e": 1749, "s": 1729, "text": "Project Structure :" }, { "code": null, "e": 1773, "s": 1749, "text": "Required Dependencies :" }, { "code": null, "e": 2219, "s": 1773, "text": "<dependencies>\n <!-- Hibernate -->\n <dependency>\n <groupId>org.hibernate</groupId>\n <artifactId>hibernate-core</artifactId>\n <version>4.3.0.Final</version>\n </dependency>\n <!-- MySQL Driver -->\n <dependency>\n <groupId>mysql</groupId>\n <artifactId>mysql-connector-java</artifactId>\n <version>5.0.5</version>\n </dependency>\n</dependencies>" }, { "code": null, "e": 2244, "s": 2219, "text": "Hibernate POJO Classes :" }, { "code": null, "e": 2256, "s": 2244, "text": "Person.java" }, { "code": null, "e": 2646, "s": 2256, "text": "package com.onlinetutorialspoint.hibernate.pojo;\n\npublic class Person {\n\tprivate int personId;\n\tprivate String personName;\n\tpublic int getPersonId() {\n\t\treturn personId;\n\t}\n\tpublic void setPersonId(int personId) {\n\t\tthis.personId = personId;\n\t}\n\tpublic String getPersonName() {\n\t\treturn personName;\n\t}\n\tpublic void setPersonName(String personName) {\n\t\tthis.personName = personName;\n\t}\n\t\n}\n" }, { "code": null, "e": 2660, "s": 2646, "text": "Passport.java" }, { "code": null, "e": 3513, "s": 2660, "text": "package com.onlinetutorialspoint.hibernate.pojo;\n\nimport java.util.Date;\n\npublic class Passport {\n private int passportNumber;\n private Date issudDate;\n private Date expireDate;\n private Person person;\n public Person getPerson() {\n return person;\n }\n public void setPerson(Person person) {\n this.person = person;\n }\n public int getPassportNumber() {\n return passportNumber;\n }\n public void setPassportNumber(int passportNumber) {\n this.passportNumber = passportNumber;\n }\n public Date getIssudDate() {\n return issudDate;\n }\n public void setIssudDate(Date issudDate) {\n this.issudDate = issudDate;\n }\n public Date getExpireDate() {\n return expireDate;\n }\n public void setExpireDate(Date expireDate) {\n this.expireDate = expireDate;\n }\n\n}" }, { "code": null, "e": 3539, "s": 3513, "text": "Hibernate Mapping Files :" }, { "code": null, "e": 3554, "s": 3539, "text": "person.hbm.xml" }, { "code": null, "e": 3982, "s": 3554, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE hibernate-mapping PUBLIC\n \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\"\n \"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">\n<hibernate-mapping>\n <class name=\"com.onlinetutorialspoint.hibernate.pojo.Person\" table=\"person\">\n <id name=\"personId\" column=\"personid\" />\n <property name=\"personName\" column=\"personname\" />\n </class>\n</hibernate-mapping>" }, { "code": null, "e": 3999, "s": 3982, "text": "passport.hbm.xml" }, { "code": null, "e": 4646, "s": 3999, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE hibernate-mapping PUBLIC\n \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\"\n \"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">\n<hibernate-mapping>\n <class name=\"com.onlinetutorialspoint.hibernate.pojo.Passport\"\n table=\"passport\">\n <id name=\"passportNumber\" column=\"ppid\" />\n <property name=\"issudDate\" column=\"idate\" />\n <property name=\"expireDate\" column=\"edate\" />\n <many-to-one name=\"person\" class=\"com.onlinetutorialspoint.hibernate.pojo.Person\"\n column=\"per_id\" unique=\"true\" not-null=\"true\" cascade=\"all\"/>\n </class>\n</hibernate-mapping>" }, { "code": null, "e": 4664, "s": 4646, "text": "Hibenate Utility:" }, { "code": null, "e": 4683, "s": 4664, "text": "HibernateUtil.java" }, { "code": null, "e": 5468, "s": 4683, "text": "package com.onlinetutorialspoint.util;\n\nimport org.hibernate.SessionFactory;\nimport org.hibernate.boot.registry.StandardServiceRegistryBuilder;\nimport org.hibernate.cfg.Configuration;\n\npublic class HibernateUtil {\n private HibernateUtil() {\n\n }\n\n private static SessionFactory sessionFactory;\n\n public static synchronized SessionFactory getInstnce() {\n\n if (sessionFactory == null) {\n Configuration configuration = new Configuration().configure(\"hibernate.cfg.xml\");\n StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()\n .applySettings(configuration.getProperties());\n sessionFactory = configuration.buildSessionFactory(builder.build());\n }\n return sessionFactory;\n\n }\n}" }, { "code": null, "e": 5494, "s": 5468, "text": "Well! we are almost done." }, { "code": null, "e": 5514, "s": 5494, "text": "Run the application" }, { "code": null, "e": 5524, "s": 5514, "text": "Main.java" }, { "code": null, "e": 6532, "s": 5524, "text": "import java.util.Date;\n\nimport org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.Transaction;\n\nimport com.onlinetutorialspoint.hibernate.pojo.Passport;\nimport com.onlinetutorialspoint.hibernate.pojo.Person;\nimport com.onlinetutorialspoint.util.HibernateUtil;\n\npublic class Main {\n\n public static void main(String[] args) {\n\n SessionFactory sessionFactory = HibernateUtil.getInstnce();\n Session session = sessionFactory.openSession();\n\n Person person = new Person();\n person.setPersonId(1001);\n person.setPersonName(\"Chandrashekhar\");\n\n Passport passport = new Passport();\n passport.setPassportNumber(12346856);\n passport.setExpireDate(new Date());\n passport.setIssudDate(new Date());\n passport.setPerson(person);\n\n Transaction transaction = session.beginTransaction();\n session.save(passport);\n transaction.commit();\n\n session.close();\n sessionFactory.close();\n }\n}" }, { "code": null, "e": 6541, "s": 6532, "text": "Output :" }, { "code": null, "e": 6805, "s": 6541, "text": "Hibernate: select person_.personid, person_.personname as personna2_1_ from person person_ where person_.personid=?\nHibernate: insert into person (personname, personid) values (?, ?)\nHibernate: insert into passport (idate, edate, per_id, ppid) values (?, ?, ?, ?)" }, { "code": null, "e": 6823, "s": 6805, "text": "Database Output :" }, { "code": null, "e": 6840, "s": 6823, "text": "Happy Learning 🙂" }, { "code": null, "e": 6916, "s": 6840, "text": "\n\nOne to One Mapping in Hibernate Example\n\nFile size: 20 KB\nDownloads: 818\n" }, { "code": null, "e": 7542, "s": 6916, "text": "\nHibernate One to One Mapping using primary key (XML)\nHibernate Many to Many Mapping Example (XML)\nHibernate Composite Key Mapping Example\nHibernate One To Many Example (XML Mapping)\nMany to One Mapping in Hibernate Example\nHibernate Filter Example Xml Configuration\nhbm2ddl.auto Example in Hibernate XML Config\nBasic Hibernate Example with XML Configuration\nCalling Stored Procedures in Hibernate\nHibernate Right Join Example\nHibernate One To Many Using Annotations\nCustom Generator Class in Hibernate\nHibernate Inheritance Mapping Strategies\nhibernate update query example\nTable per Concrete Class in Hibernate Inheritance\n" }, { "code": null, "e": 7595, "s": 7542, "text": "Hibernate One to One Mapping using primary key (XML)" }, { "code": null, "e": 7640, "s": 7595, "text": "Hibernate Many to Many Mapping Example (XML)" }, { "code": null, "e": 7680, "s": 7640, "text": "Hibernate Composite Key Mapping Example" }, { "code": null, "e": 7724, "s": 7680, "text": "Hibernate One To Many Example (XML Mapping)" }, { "code": null, "e": 7765, "s": 7724, "text": "Many to One Mapping in Hibernate Example" }, { "code": null, "e": 7808, "s": 7765, "text": "Hibernate Filter Example Xml Configuration" }, { "code": null, "e": 7853, "s": 7808, "text": "hbm2ddl.auto Example in Hibernate XML Config" }, { "code": null, "e": 7900, "s": 7853, "text": "Basic Hibernate Example with XML Configuration" }, { "code": null, "e": 7939, "s": 7900, "text": "Calling Stored Procedures in Hibernate" }, { "code": null, "e": 7968, "s": 7939, "text": "Hibernate Right Join Example" }, { "code": null, "e": 8008, "s": 7968, "text": "Hibernate One To Many Using Annotations" }, { "code": null, "e": 8044, "s": 8008, "text": "Custom Generator Class in Hibernate" }, { "code": null, "e": 8085, "s": 8044, "text": "Hibernate Inheritance Mapping Strategies" }, { "code": null, "e": 8116, "s": 8085, "text": "hibernate update query example" }, { "code": null, "e": 8166, "s": 8116, "text": "Table per Concrete Class in Hibernate Inheritance" }, { "code": null, "e": 8297, "s": 8166, "text": "\n\n\n\n\n\nMilana Travis\nOctober 25, 2017 at 11:21 am - Reply \n\nThank you very much for your blog.\nI enjoyed reading this article.\n\n\n\n\n" }, { "code": null, "e": 8426, "s": 8297, "text": "\n\n\n\n\nMilana Travis\nOctober 25, 2017 at 11:21 am - Reply \n\nThank you very much for your blog.\nI enjoyed reading this article.\n\n\n\n" }, { "code": null, "e": 8461, "s": 8426, "text": "Thank you very much for your blog." }, { "code": null, "e": 8493, "s": 8461, "text": "I enjoyed reading this article." }, { "code": null, "e": 8499, "s": 8497, "text": "Δ" }, { "code": null, "e": 8525, "s": 8499, "text": " Hibernate – Introduction" }, { "code": null, "e": 8549, "s": 8525, "text": " Hibernate – Advantages" }, { "code": null, "e": 8581, "s": 8549, "text": " Hibernate – Download and Setup" }, { "code": null, "e": 8611, "s": 8581, "text": " Hibernate – Sql Dialect list" }, { "code": null, "e": 8641, "s": 8611, "text": " Hibernate – Helloworld – XML" }, { "code": null, "e": 8679, "s": 8641, "text": " Hibernate – Install Tools in Eclipse" }, { "code": null, "e": 8706, "s": 8679, "text": " Hibernate – Object States" }, { "code": null, "e": 8744, "s": 8706, "text": " Hibernate – Helloworld – Annotations" }, { "code": null, "e": 8782, "s": 8744, "text": " Hibernate – One to One Mapping – XML" }, { "code": null, "e": 8832, "s": 8782, "text": " Hibernate – One to One Mapping foreign key – XML" }, { "code": null, "e": 8862, "s": 8832, "text": " Hibernate – One To Many -XML" }, { "code": null, "e": 8901, "s": 8862, "text": " Hibernate – One To Many – Annotations" }, { "code": null, "e": 8941, "s": 8901, "text": " Hibernate – Many to Many Mapping – XML" }, { "code": null, "e": 8972, "s": 8941, "text": " Hibernate – Many to One – XML" }, { "code": null, "e": 9007, "s": 8972, "text": " Hibernate – Composite Key Mapping" }, { "code": null, "e": 9032, "s": 9007, "text": " Hibernate – Named Query" }, { "code": null, "e": 9062, "s": 9032, "text": " Hibernate – Native SQL Query" }, { "code": null, "e": 9091, "s": 9062, "text": " Hibernate – load() vs get()" }, { "code": null, "e": 9128, "s": 9091, "text": " Hibernate Criteria API with Example" }, { "code": null, "e": 9154, "s": 9128, "text": " Hibernate – Restrictions" }, { "code": null, "e": 9178, "s": 9154, "text": " Hibernate – Projection" }, { "code": null, "e": 9212, "s": 9178, "text": " Hibernate – Query Language (HQL)" }, { "code": null, "e": 9246, "s": 9212, "text": " Hibernate – Groupby Criteria HQL" }, { "code": null, "e": 9276, "s": 9246, "text": " Hibernate – Orderby Criteria" }, { "code": null, "e": 9309, "s": 9276, "text": " Hibernate – HQLSelect Operation" }, { "code": null, "e": 9341, "s": 9309, "text": " Hibernate – HQL Update, Delete" }, { "code": null, "e": 9367, "s": 9341, "text": " Hibernate – Update Query" }, { "code": null, "e": 9396, "s": 9367, "text": " Hibernate – Update vs Merge" }, { "code": null, "e": 9420, "s": 9396, "text": " Hibernate – Right Join" }, { "code": null, "e": 9443, "s": 9420, "text": " Hibernate – Left Join" }, { "code": null, "e": 9467, "s": 9443, "text": " Hibernate – Pagination" }, { "code": null, "e": 9498, "s": 9467, "text": " Hibernate – Generator Classes" }, { "code": null, "e": 9528, "s": 9498, "text": " Hibernate – Custom Generator" }, { "code": null, "e": 9562, "s": 9528, "text": " Hibernate – Inheritance Mappings" }, { "code": null, "e": 9591, "s": 9562, "text": " Hibernate – Table per Class" }, { "code": null, "e": 9624, "s": 9591, "text": " Hibernate – Table per Sub Class" }, { "code": null, "e": 9662, "s": 9624, "text": " Hibernate – Table per Concrete Class" }, { "code": null, "e": 9704, "s": 9662, "text": " Hibernate – Table per Class Annotations" }, { "code": null, "e": 9735, "s": 9704, "text": " Hibernate – Stored Procedures" }, { "code": null, "e": 9768, "s": 9735, "text": " Hibernate – @Formula Annotation" }, { "code": null, "e": 9806, "s": 9768, "text": " Hibernate – Singleton SessionFactory" }, { "code": null, "e": 9831, "s": 9806, "text": " Hibernate – Interceptor" }, { "code": null, "e": 9877, "s": 9831, "text": " hbm2ddl.auto Example in Hibernate XML Config" } ]
How to upload multiple files and store them in a folder with PHP?
Below are the steps to upload multiple files and store them in a folder − Input name must be defined as an array i.e. name="inputName[]" Input element should have multiple="multiple" or just multiple In the PHP file, use the syntax "$_FILES['inputName']['param'][index]" Empty file names and paths have to be checked for since the array might contain empty strings. To resolve this, use array_filter() before count. Below is a demonstration of the code − <input name="upload[]" type="file" multiple="multiple" /> $files = array_filter($_FILES['upload']['name']); //Use something similar before processing files. // Count the number of uploaded files in array $total_count = count($_FILES['upload']['name']); // Loop through every file for( $i=0 ; $i < $total_count ; $i++ ) { //The temp file path is obtained $tmpFilePath = $_FILES['upload']['tmp_name'][$i]; //A file path needs to be present if ($tmpFilePath != ""){ //Setup our new file path $newFilePath = "./uploadFiles/" . $_FILES['upload']['name'][$i]; //File is uploaded to temp dir if(move_uploaded_file($tmpFilePath, $newFilePath)) { //Other code goes here } } } The files are listed and the count of the number of files that need to be uploaded is stored in ‘total_count’ variable. A temporary file path is created and every file is iteratively put in this temporary path that holds a folder.
[ { "code": null, "e": 1136, "s": 1062, "text": "Below are the steps to upload multiple files and store them in a folder −" }, { "code": null, "e": 1199, "s": 1136, "text": "Input name must be defined as an array i.e. name=\"inputName[]\"" }, { "code": null, "e": 1262, "s": 1199, "text": "Input element should have multiple=\"multiple\" or just multiple" }, { "code": null, "e": 1333, "s": 1262, "text": "In the PHP file, use the syntax \"$_FILES['inputName']['param'][index]\"" }, { "code": null, "e": 1478, "s": 1333, "text": "Empty file names and paths have to be checked for since the array might contain empty strings. To resolve this, use array_filter() before count." }, { "code": null, "e": 1517, "s": 1478, "text": "Below is a demonstration of the code −" }, { "code": null, "e": 1575, "s": 1517, "text": "<input name=\"upload[]\" type=\"file\" multiple=\"multiple\" />" }, { "code": null, "e": 2238, "s": 1575, "text": "$files = array_filter($_FILES['upload']['name']); //Use something similar before processing files.\n// Count the number of uploaded files in array\n$total_count = count($_FILES['upload']['name']);\n// Loop through every file\nfor( $i=0 ; $i < $total_count ; $i++ ) {\n //The temp file path is obtained\n $tmpFilePath = $_FILES['upload']['tmp_name'][$i];\n //A file path needs to be present\n if ($tmpFilePath != \"\"){\n //Setup our new file path\n $newFilePath = \"./uploadFiles/\" . $_FILES['upload']['name'][$i];\n //File is uploaded to temp dir\n if(move_uploaded_file($tmpFilePath, $newFilePath)) {\n //Other code goes here\n }\n }\n}" }, { "code": null, "e": 2469, "s": 2238, "text": "The files are listed and the count of the number of files that need to be uploaded is stored in ‘total_count’ variable. A temporary file path is created and every file is iteratively put in this temporary path that holds a folder." } ]
Semi-Supervised Classification of Unlabeled Data (PU Learning) | by Alon Agmon | Towards Data Science
Suppose you have a dataset of payment transactions. Some of the transactions are labeled as fraud and the rest are labeled as authentic, and you are required to design a model that will distinguish between fraudulent and authentic transactions. Assuming you have enough data and good features, this seems like a straightforward classification task. However, suppose that only 15% of your data is labeled, and that the labeled samples belong to just one class so that your training set consists of 15% samples labeled as authentic while the rest are unlabeled and could be either authentic or fraudulent. How would you go about classifying them? Has this twist in the requirements just turned this task into an unsupervised learning problem? Well, not necessarily. This problem — which is often referred to as a PU (positive and unlabeled) classification problem — should be first distinguished from two similar and common “labeling issues” that complicate many classification tasks. The first and most common type of labeling issue is the problem of a small training set. It arises when although you have a decent amount of data, just a small part of it is actually labeled. This problem has many varieties and quite a few specific training methodologies. Another common labeling issue (that is often conflated with PU problems) involves cases in which our training data set is fully labeled, but it consists of just one class. Suppose, for example, that all we have is a data set of non-fraudulent transactions and that we need to use this data set to train a model to distinguish between (similar) non-fraudulent transactions and fraudulent ones. This is also a common problem that is usually treated as an unsupervised outlier detection problem, though there are also quite a few tools widely available in the ML landscape that are specifically designed to handle these scenarios (OneClassSVM might be the most famous). A PU classification problem, in contrast, is a case involving a training set in which just part of the data is labeled as positive while the rest is unlabeled and could be either positive or negative. For instance, suppose that your employer is a bank that can provide you with a lot of transactional data, but can only confirm that part of it is 100% authentic. The example that I will use here involves a similar scenario with respect to fraudulent banknotes. It includes a data set of 1200 banknotes, most of which are unlabeled while just part of them is confirmed as authentic. Although PU problems are also quite common, they are often much less discussed than the two classification problems mentioned earlier, and very few hands-on examples or libraries are widely available. The purpose of this post is to present one possible approach to PU problems which I have recently used in a classification project. It is based on the paper “Learning classifiers from only positive and unlabeled data” (2008) written by Charles Elkan and Keith Noto, and on some code written by Alexandre Drouin. Although there are more approaches to PU learning in scientific publications (I intend to discuss another rather popular approach in a future post), Elkan and Noto’s (E&N) approach is quite simple and can be easily implemented in Python. E&N essentially claim that given a data set in which we have positive and unlabeled data, the probability that a certain sample is positive [ P(y=1|x)] equals the probability that the sample is labeled [P(s=1|x)] divided by the probability that a positive sample is labeled in our data set [P(s=1|y=1)]. If this claim is true (and I’m not going to prove or defend it — you can read the proof in the paper itself and experiment with the code), then it seems relatively easy to implement. This is so because although we don't have enough labeled data to train a classifier to tell us whether a sample is positive or negative, in a PU scenario we do have enough labeled data to tell us whether a positive sample is likely to be labeled or not and, according to E&N, this is enough to estimate how likely it is to be positive. Putting things more formally, given an unlabeled data set with just a group of samples labeled as positive, we can estimate the probability that unlabeled sample x is positive if we estimate P(s=1|x) / P(s=1|y=1). Luckily, we can use almost any sklearn-based classifier to estimate this according to the following steps: (1) Fit a classifier on a data set containing labeled and unlabeled data while using an isLabeled indicator as a target y. Fitting a classifier in this way will train it to predict the probability that a given sample x is labeled — P(s=1| x). (2) Use the classifier to predict the probability that the known positive samples in our data set are labeled so that the predicted results will represent the probability that a positive sample is labeled — P(s=1|y=1|x) Calculate the mean of these predicted probabilities and that will be our P(s=1|y=1). Having estimated P(s=1|y=1), all we need to do in order to predict the probability that data point k is positive according to E&N is to estimate P(s=1|k) or the probability that it is labeled which is exactly what the classifier we trained on (1) knows how to do. (3) Use the classifier we trained on (1) to estimate the probability that k is labeled or P(s=1|k). (4) Once we have estimated P(s=1|k), we can actually classify k by dividing it by P(s=1|y=1), which has been estimated on step (2), and get the actual probabilities that it belongs to either class. Steps 1–4 above can be implemented as follows: # prepare datax_data = the training sety_data = target var (1 for the positives and not-1 for the rest)# fit the classifier and estimate P(s=1|y=1)classifier, ps1y1 = fit_PU_estimator(x_data, y_data, 0.2, Estimator())# estimate the prob that x_data is labeled P(s=1|X)predicted_s = classifier.predict_proba(x_data)# estimate the actual probabilities that X is positive# by calculating P(s=1|X) / P(s=1|y=1)predicted_y = estimated_s / ps1y1 Let’s start with the main move here: fit_PU_estimator() method. The fit_PU_estimator() method completes 2 main tasks: it fits a classifier you choose on a sample of the positive and unlabeled training set and then estimates the probability that a positive sample is labeled. Correspondingly, it returns the fitted classifier (that learned to estimate the proba that a given sample is labeled) and the estimated probability P(s=1|y=1). After that, all we need to do is find P(s=1|x) or the probability that x is labeled. Because that's what our classifier is trained to do, we just need to call its predict_proba() method. Finally, in order to actually classify sample x we just need to divide the result by P(s=1|y=1) that we have already found. This can be represented in code as: The implementation of the fit_PU_estimator() method itself is quite self-explanatory : In order to test this, I used the Bank Note Authentication data set, which is based on 4 data points that were extracted from images of genuine and forged banknotes. I first used the classifier on the labeled data set in order to set a baseline, and then removed the labels of 75% of the samples in order to test how it performs on a P&U data set. As the output shows, it is true this data set is not one of the hardest to classify, but you can see that although the PU classifier only “knew” about 153 positive samples while all the rest 1219 were unlabeled, it performed quite well compared to a classifier that had all labels available. However, it did lose about 17% of the recall and therefore lost quite a few true positives. Yet, whenever this is all we have, then I believe that these results are quite satisfying comparing to the alternatives. ===>> load data set <<===data size: (1372, 5)Target variable (fraud or not):0 7621 610===>> create baseline classification results <<===Classification results:f1: 99.57%roc: 99.57%recall: 99.15%precision: 100.00%===>> classify on all the data set <<===Target variable (labeled or not):-1 12191 153Classification results:f1: 90.24%roc: 91.11%recall: 82.62%precision: 99.41% Few important notes. First, the performance of this approach greatly depends on the size of the dataset. In this example, I have used about 150 positive samples and about 1200 unlabeled. This is far from being the ideal data set for this approach. If we only had 100 samples, for example, our classifier would have performed very poorly. Second, as the attached notebook shows, there are a few variables to tune (such as the size of the sample to be set aside, the probability threshold to use for classification, etc), but the most important one is probably the chosen classifier and its parameters. I have chosen to use XGBoost because it performs relatively well on small data sets with few features, but it is important to note that it will not perform best in every scenario and it is important to test for the right classifier. The notebook is available here.
[ { "code": null, "e": 810, "s": 46, "text": "Suppose you have a dataset of payment transactions. Some of the transactions are labeled as fraud and the rest are labeled as authentic, and you are required to design a model that will distinguish between fraudulent and authentic transactions. Assuming you have enough data and good features, this seems like a straightforward classification task. However, suppose that only 15% of your data is labeled, and that the labeled samples belong to just one class so that your training set consists of 15% samples labeled as authentic while the rest are unlabeled and could be either authentic or fraudulent. How would you go about classifying them? Has this twist in the requirements just turned this task into an unsupervised learning problem? Well, not necessarily." }, { "code": null, "e": 1969, "s": 810, "text": "This problem — which is often referred to as a PU (positive and unlabeled) classification problem — should be first distinguished from two similar and common “labeling issues” that complicate many classification tasks. The first and most common type of labeling issue is the problem of a small training set. It arises when although you have a decent amount of data, just a small part of it is actually labeled. This problem has many varieties and quite a few specific training methodologies. Another common labeling issue (that is often conflated with PU problems) involves cases in which our training data set is fully labeled, but it consists of just one class. Suppose, for example, that all we have is a data set of non-fraudulent transactions and that we need to use this data set to train a model to distinguish between (similar) non-fraudulent transactions and fraudulent ones. This is also a common problem that is usually treated as an unsupervised outlier detection problem, though there are also quite a few tools widely available in the ML landscape that are specifically designed to handle these scenarios (OneClassSVM might be the most famous)." }, { "code": null, "e": 2753, "s": 1969, "text": "A PU classification problem, in contrast, is a case involving a training set in which just part of the data is labeled as positive while the rest is unlabeled and could be either positive or negative. For instance, suppose that your employer is a bank that can provide you with a lot of transactional data, but can only confirm that part of it is 100% authentic. The example that I will use here involves a similar scenario with respect to fraudulent banknotes. It includes a data set of 1200 banknotes, most of which are unlabeled while just part of them is confirmed as authentic. Although PU problems are also quite common, they are often much less discussed than the two classification problems mentioned earlier, and very few hands-on examples or libraries are widely available." }, { "code": null, "e": 3303, "s": 2753, "text": "The purpose of this post is to present one possible approach to PU problems which I have recently used in a classification project. It is based on the paper “Learning classifiers from only positive and unlabeled data” (2008) written by Charles Elkan and Keith Noto, and on some code written by Alexandre Drouin. Although there are more approaches to PU learning in scientific publications (I intend to discuss another rather popular approach in a future post), Elkan and Noto’s (E&N) approach is quite simple and can be easily implemented in Python." }, { "code": null, "e": 3607, "s": 3303, "text": "E&N essentially claim that given a data set in which we have positive and unlabeled data, the probability that a certain sample is positive [ P(y=1|x)] equals the probability that the sample is labeled [P(s=1|x)] divided by the probability that a positive sample is labeled in our data set [P(s=1|y=1)]." }, { "code": null, "e": 4126, "s": 3607, "text": "If this claim is true (and I’m not going to prove or defend it — you can read the proof in the paper itself and experiment with the code), then it seems relatively easy to implement. This is so because although we don't have enough labeled data to train a classifier to tell us whether a sample is positive or negative, in a PU scenario we do have enough labeled data to tell us whether a positive sample is likely to be labeled or not and, according to E&N, this is enough to estimate how likely it is to be positive." }, { "code": null, "e": 4447, "s": 4126, "text": "Putting things more formally, given an unlabeled data set with just a group of samples labeled as positive, we can estimate the probability that unlabeled sample x is positive if we estimate P(s=1|x) / P(s=1|y=1). Luckily, we can use almost any sklearn-based classifier to estimate this according to the following steps:" }, { "code": null, "e": 4690, "s": 4447, "text": "(1) Fit a classifier on a data set containing labeled and unlabeled data while using an isLabeled indicator as a target y. Fitting a classifier in this way will train it to predict the probability that a given sample x is labeled — P(s=1| x)." }, { "code": null, "e": 4910, "s": 4690, "text": "(2) Use the classifier to predict the probability that the known positive samples in our data set are labeled so that the predicted results will represent the probability that a positive sample is labeled — P(s=1|y=1|x)" }, { "code": null, "e": 4995, "s": 4910, "text": "Calculate the mean of these predicted probabilities and that will be our P(s=1|y=1)." }, { "code": null, "e": 5259, "s": 4995, "text": "Having estimated P(s=1|y=1), all we need to do in order to predict the probability that data point k is positive according to E&N is to estimate P(s=1|k) or the probability that it is labeled which is exactly what the classifier we trained on (1) knows how to do." }, { "code": null, "e": 5359, "s": 5259, "text": "(3) Use the classifier we trained on (1) to estimate the probability that k is labeled or P(s=1|k)." }, { "code": null, "e": 5557, "s": 5359, "text": "(4) Once we have estimated P(s=1|k), we can actually classify k by dividing it by P(s=1|y=1), which has been estimated on step (2), and get the actual probabilities that it belongs to either class." }, { "code": null, "e": 5604, "s": 5557, "text": "Steps 1–4 above can be implemented as follows:" }, { "code": null, "e": 6051, "s": 5604, "text": "# prepare datax_data = the training sety_data = target var (1 for the positives and not-1 for the rest)# fit the classifier and estimate P(s=1|y=1)classifier, ps1y1 = fit_PU_estimator(x_data, y_data, 0.2, Estimator())# estimate the prob that x_data is labeled P(s=1|X)predicted_s = classifier.predict_proba(x_data)# estimate the actual probabilities that X is positive# by calculating P(s=1|X) / P(s=1|y=1)predicted_y = estimated_s / ps1y1" }, { "code": null, "e": 6115, "s": 6051, "text": "Let’s start with the main move here: fit_PU_estimator() method." }, { "code": null, "e": 6833, "s": 6115, "text": "The fit_PU_estimator() method completes 2 main tasks: it fits a classifier you choose on a sample of the positive and unlabeled training set and then estimates the probability that a positive sample is labeled. Correspondingly, it returns the fitted classifier (that learned to estimate the proba that a given sample is labeled) and the estimated probability P(s=1|y=1). After that, all we need to do is find P(s=1|x) or the probability that x is labeled. Because that's what our classifier is trained to do, we just need to call its predict_proba() method. Finally, in order to actually classify sample x we just need to divide the result by P(s=1|y=1) that we have already found. This can be represented in code as:" }, { "code": null, "e": 6920, "s": 6833, "text": "The implementation of the fit_PU_estimator() method itself is quite self-explanatory :" }, { "code": null, "e": 7773, "s": 6920, "text": "In order to test this, I used the Bank Note Authentication data set, which is based on 4 data points that were extracted from images of genuine and forged banknotes. I first used the classifier on the labeled data set in order to set a baseline, and then removed the labels of 75% of the samples in order to test how it performs on a P&U data set. As the output shows, it is true this data set is not one of the hardest to classify, but you can see that although the PU classifier only “knew” about 153 positive samples while all the rest 1219 were unlabeled, it performed quite well compared to a classifier that had all labels available. However, it did lose about 17% of the recall and therefore lost quite a few true positives. Yet, whenever this is all we have, then I believe that these results are quite satisfying comparing to the alternatives." }, { "code": null, "e": 8159, "s": 7773, "text": "===>> load data set <<===data size: (1372, 5)Target variable (fraud or not):0 7621 610===>> create baseline classification results <<===Classification results:f1: 99.57%roc: 99.57%recall: 99.15%precision: 100.00%===>> classify on all the data set <<===Target variable (labeled or not):-1 12191 153Classification results:f1: 90.24%roc: 91.11%recall: 82.62%precision: 99.41%" }, { "code": null, "e": 8993, "s": 8159, "text": "Few important notes. First, the performance of this approach greatly depends on the size of the dataset. In this example, I have used about 150 positive samples and about 1200 unlabeled. This is far from being the ideal data set for this approach. If we only had 100 samples, for example, our classifier would have performed very poorly. Second, as the attached notebook shows, there are a few variables to tune (such as the size of the sample to be set aside, the probability threshold to use for classification, etc), but the most important one is probably the chosen classifier and its parameters. I have chosen to use XGBoost because it performs relatively well on small data sets with few features, but it is important to note that it will not perform best in every scenario and it is important to test for the right classifier." } ]
Explain the insertion sort by using C language.
Sorting is the process of arranging the elements either in ascending (or) descending order. C language provides five sorting techniques, which are as follows − Bubble sort (or) Exchange Sort Selection sort Insertion sort(or) Linear sort Quick sort (or) Partition exchange sort Merge Sort (or) External sort The logic used to sort the elements by using the insertion sort technique is as follows − for(i = 1; i <= n - 1; i++){ for(j = i; j > 0 && a[j - 1] > a[j]; j--){ t = a[j]; a[j] = a[j - 1]; a[j - 1] = t; } } Let us consider some elements which are in unsorted order − Following is the C program to sort the elements by using the insertion sort technique − #include<stdio.h> int main() { int a[50], i,j,n,t; printf("enter the No: of elements in the list:\n"); scanf("%d", &n); printf("enter the elements:\n"); for(i=0; i<n; i++){ scanf ("%d", &a[i]); } for(i = 1; i <= n - 1; i++){ for(j=i; j > 0 && a[j - 1] > a[j]; j--){ t = a[j]; a[j] = a[j - 1]; a[j - 1] = t; } } printf ("after insertion sorting the elements are:\n"); for (i=0; i<n; i++) printf("%d\t", a[i]); return 0; } When the above program is executed, it produces the following output − Enter the No: of elements in the list: 10 Enter the elements: 34 125 2 6 78 49 1 3 89 23 After insertion sorting the elements are: 1 2 3 6 23 34 49 78 89 125
[ { "code": null, "e": 1154, "s": 1062, "text": "Sorting is the process of arranging the elements either in ascending (or) descending order." }, { "code": null, "e": 1222, "s": 1154, "text": "C language provides five sorting techniques, which are as follows −" }, { "code": null, "e": 1253, "s": 1222, "text": "Bubble sort (or) Exchange Sort" }, { "code": null, "e": 1268, "s": 1253, "text": "Selection sort" }, { "code": null, "e": 1299, "s": 1268, "text": "Insertion sort(or) Linear sort" }, { "code": null, "e": 1339, "s": 1299, "text": "Quick sort (or) Partition exchange sort" }, { "code": null, "e": 1369, "s": 1339, "text": "Merge Sort (or) External sort" }, { "code": null, "e": 1459, "s": 1369, "text": "The logic used to sort the elements by using the insertion sort technique is as follows −" }, { "code": null, "e": 1600, "s": 1459, "text": "for(i = 1; i <= n - 1; i++){\n for(j = i; j > 0 && a[j - 1] > a[j]; j--){\n t = a[j];\n a[j] = a[j - 1];\n a[j - 1] = t;\n }\n}" }, { "code": null, "e": 1660, "s": 1600, "text": "Let us consider some elements which are in unsorted order −" }, { "code": null, "e": 1748, "s": 1660, "text": "Following is the C program to sort the elements by using the insertion sort technique −" }, { "code": null, "e": 2250, "s": 1748, "text": "#include<stdio.h>\nint main() {\n int a[50], i,j,n,t;\n printf(\"enter the No: of elements in the list:\\n\");\n scanf(\"%d\", &n);\n printf(\"enter the elements:\\n\");\n for(i=0; i<n; i++){\n scanf (\"%d\", &a[i]);\n }\n for(i = 1; i <= n - 1; i++){\n for(j=i; j > 0 && a[j - 1] > a[j]; j--){\n t = a[j];\n a[j] = a[j - 1];\n a[j - 1] = t;\n }\n }\n printf (\"after insertion sorting the elements are:\\n\");\n for (i=0; i<n; i++)\n printf(\"%d\\t\", a[i]);\n return 0;\n}" }, { "code": null, "e": 2321, "s": 2250, "text": "When the above program is executed, it produces the following output −" }, { "code": null, "e": 2479, "s": 2321, "text": "Enter the No: of elements in the list:\n10\nEnter the elements:\n34\n125\n2\n6\n78\n49\n1\n3\n89\n23\nAfter insertion sorting the elements are:\n1 2 3 6 23 34 49 78 89 125" } ]
Print all combinations of balanced parentheses in C++
In this problem, we are given an integer n. Our task is to print all possible pairs of n balanced parentheses. Balanced parentheses are parentheses pairs that have a closing symbol for every corresponding opening symbol. Also, pairs should be properly nested. Let’s take an example to understand the problem, Input: n = 2 Output: {}{} {{}} To solve this problem, we need to keep track of pairs of brackets. The initial count of brackets is 0. Then we will recursively a function till the total bracket count is less than n. Count brackets, recursively call for brackets based on the count. If opening bracket count is more than closing, put closing brackets and then go for a remaining count of pairs, if the opening bracket is less than n recursively call for remaining bracket pairs. The below code with show implementation of our solution, Live Demo # include<iostream> using namespace std; # define MAX_COUNT 100 void printParenthesesPairs(int pos, int n, int open, int close){ static char str[MAX_COUNT]; if(close == n) { cout<<str<<endl; return; } else { if(open > close) { str[pos] = '}'; printParenthesesPairs(pos+1, n, open, close+1); } if(open < n) { str[pos] = '{'; printParenthesesPairs(pos+1, n, open+1, close); } } } int main() { int n = 3; cout<<"All parentheses pairs of length "<<n<<" are:\n"; if(n > 0) printParenthesesPairs(0, n, 0, 0); getchar(); return 0; } All parentheses pairs of length 3 are − {}{}{} {}{{}} {{}}{} {{}{}} {{{}}}
[ { "code": null, "e": 1173, "s": 1062, "text": "In this problem, we are given an integer n. Our task is to print all possible pairs of n balanced parentheses." }, { "code": null, "e": 1322, "s": 1173, "text": "Balanced parentheses are parentheses pairs that have a closing symbol for every corresponding opening symbol. Also, pairs should be properly nested." }, { "code": null, "e": 1371, "s": 1322, "text": "Let’s take an example to understand the problem," }, { "code": null, "e": 1402, "s": 1371, "text": "Input: n = 2\nOutput: {}{} {{}}" }, { "code": null, "e": 1848, "s": 1402, "text": "To solve this problem, we need to keep track of pairs of brackets. The initial count of brackets is 0. Then we will recursively a function till the total bracket count is less than n. Count brackets, recursively call for brackets based on the count. If opening bracket count is more than closing, put closing brackets and then go for a remaining count of pairs, if the opening bracket is less than n recursively call for remaining bracket pairs." }, { "code": null, "e": 1905, "s": 1848, "text": "The below code with show implementation of our solution," }, { "code": null, "e": 1916, "s": 1905, "text": " Live Demo" }, { "code": null, "e": 2550, "s": 1916, "text": "# include<iostream>\nusing namespace std;\n# define MAX_COUNT 100\nvoid printParenthesesPairs(int pos, int n, int open, int close){\n static char str[MAX_COUNT];\n if(close == n) {\n cout<<str<<endl;\n return;\n }\n else {\n if(open > close) {\n str[pos] = '}';\n printParenthesesPairs(pos+1, n, open, close+1);\n }\n if(open < n) {\n str[pos] = '{';\n printParenthesesPairs(pos+1, n, open+1, close);\n }\n }\n}\nint main() {\n int n = 3;\n cout<<\"All parentheses pairs of length \"<<n<<\" are:\\n\";\n if(n > 0)\n printParenthesesPairs(0, n, 0, 0);\n getchar();\n return 0;\n}" }, { "code": null, "e": 2625, "s": 2550, "text": "All parentheses pairs of length 3 are −\n{}{}{}\n{}{{}}\n{{}}{}\n{{}{}}\n{{{}}}" } ]
Feature Extraction Techniques. An end to end guide on how to reduce a... | by Pier Paolo Ippolito | Towards Data Science
1 2 3 4 5 6 7 8 9 10 Powered by Play.ht Create audio with Play.ht Create Audio Narrations with Play.ht It is nowadays becoming quite common to be working with datasets of hundreds (or even thousands) of features. If the number of features becomes similar (or even bigger!) than the number of observations stored in a dataset then this can most likely lead to a Machine Learning model suffering from overfitting. In order to avoid this type of problem, it is necessary to apply either regularization or dimensionality reduction techniques (Feature Extraction). In Machine Learning, the dimensionali of a dataset is equal to the number of variables used to represent it. Using Regularization could certainly help reduce the risk of overfitting, but using instead Feature Extraction techniques can also lead to other types of advantages such as: Accuracy improvements. Overfitting risk reduction. Speed up in training. Improved Data Visualization. Increase in explainability of our model. Feature Extraction aims to reduce the number of features in a dataset by creating new features from the existing ones (and then discarding the original features). These new reduced set of features should then be able to summarize most of the information contained in the original set of features. In this way, a summarised version of the original features can be created from a combination of the original set. Another commonly used technique to reduce the number of feature in a dataset is Feature Selection. The difference between Feature Selection and Feature Extraction is that feature selection aims instead to rank the importance of the existing features in the dataset and discard less important ones (no new features are created). If you are interested in finding out more about Feature Selection, you can find more information about it in my previous article. In this article, I will walk you through how to apply Feature Extraction techniques using the Kaggle Mushroom Classification Dataset as an example. Our objective will be to try to predict if a Mushroom is poisonous or not by looking at the given features. All the code used in this post (and more!) is available on Kaggle and on my GitHub Account. First of all, we need to import all the necessary libraries. The dataset we will be using in this example is shown in the figure below. Before feeding this data into our Machine Learning models I decided to divide our data into features (X) and labels (Y) and One Hot Encode all the Categorical Variables. Successively, I decided to create a function (forest_test) to divide the input data into train and test sets and then train and test a Random Forest Classifier. We can now use this function using the whole dataset and then use it successively to compare these results when using instead of the whole dataset just a reduced version. As shown below, training a Random Forest classifier using all the features, led to 100% Accuracy in about 2.2s of training time. In each of the following examples, the training time of each model will be printed out on the first line of each snippet for your reference. 2.2676709799999992[[1274 0] [ 0 1164]] precision recall f1-score support 0 1.00 1.00 1.00 1274 1 1.00 1.00 1.00 1164 accuracy 1.00 2438 macro avg 1.00 1.00 1.00 2438weighted avg 1.00 1.00 1.00 2438 PCA is one of the most used linear dimensionality reduction technique. When using PCA, we take as input our original data and try to find a combination of the input features which can best summarize the original data distribution so that to reduce its original dimensions. PCA is able to do this by maximizing variances and minimizing the reconstruction error by looking at pair wised distances. In PCA, our original data is projected into a set of orthogonal axes and each of the axes gets ranked in order of importance. PCA is an unsupervised learning algorithm, therefore it doesn’t care about the data labels but only about variation. This can lead in some cases to misclassification of data. In this example, I will first perform PCA in the whole dataset to reduce our data to just two dimensions and I will then construct a data frame with our new features and their respective labels. Using our newly created data frame, we can now plot our data distribution in a 2D scatter plot. We can now repeat this same process keeping instead 3 dimensions and creating animations using Plotly (feel free to interact with the animation below!). While using PCA, we can also explore how much of the original data variance was preserved using the explained_variance_ratio_ Scikit-learn function. Once calculated the variance ratio, we can then go on creating fancy visualization graphs. Running again a Random Forest Classifier using the set of 3 features constructed by PCA (instead of the whole dataset) led to 98% classification accuracy while using just 2 features 95% accuracy. [10.31484926 9.42671062 8.35720548]2.769664902999999[[1261 13] [ 41 1123]] precision recall f1-score support 0 0.97 0.99 0.98 1274 1 0.99 0.96 0.98 1164 accuracy 0.98 2438 macro avg 0.98 0.98 0.98 2438weighted avg 0.98 0.98 0.98 2438 Additionally, using our two-dimensional dataset, we can now also visualize the decision boundary used by our Random Forest in order to classify each of the different data points. ICA is a linear dimensionality reduction method which takes as input data a mixture of independent components and it aims to correctly identify each of them (deleting all the unnecessary noise). Two input features can be considered independent if both their linear and not linear dependance is equal to zero [1]. Independent Component Analysis is commonly used in medical applications such as EEG and fMRI analysis to separate useful signals from unhelpful ones. As a simple example of an ICA application, let’s consider we are given an audio registration in which there are two different people talking. Using ICA we could, for example, try to identify the two different independent components in the registration (the two different people). In this way, we could make our unsupervised learning algorithm recognise between the different speakers in the conversation. Using ICA, we can now again reduce our dataset to just three features, test its accuracy using a Random Forest Classifier and plot the results. 2.8933812039999793[[1263 11] [ 44 1120]] precision recall f1-score support 0 0.97 0.99 0.98 1274 1 0.99 0.96 0.98 1164 accuracy 0.98 2438 macro avg 0.98 0.98 0.98 2438weighted avg 0.98 0.98 0.98 2438 From the animation below we can see that even though PCA and ICA led to the same accuracy results, they constructed two different 3-Dimensional space distribution. LDA is supervised learning dimensionality reduction technique and Machine Learning classifier. LDA aims to maximize the distance between the mean of each class and minimize the spreading within the class itself. LDA uses therefore within classes and between classes as measures. This is a good choice because maximizing the distance between the means of each class when projecting the data in a lower-dimensional space can lead to better classification results (thanks to the reduced overlap between the different classes). When using LDA, is assumed that the input data follows a Gaussian Distribution (like in this case), therefore applying LDA to not Gaussian data can possibly lead to poor classification results. In this example, we will run LDA to reduce our dataset to just one feature, test its accuracy and plot the results. Original number of features: 117Reduced number of features: 1 Because our data distribution closely follows a Gaussian Distribution, LDA performed really well, in this case, achieving 100% accuracy using a Random Forest Classifier. 1.2756952610000099[[1274 0] [ 0 1164]] precision recall f1-score support 0 1.00 1.00 1.00 1274 1 1.00 1.00 1.00 1164 accuracy 1.00 2438 macro avg 1.00 1.00 1.00 2438weighted avg 1.00 1.00 1.00 2438 As I mentioned at the beginning of this section, LDA can also be used as a classifier. Therefore, we can now test how an LDA Classifier can perform in this situation. 0.008464782999993758[[1274 0] [ 2 1162]] precision recall f1-score support 0 1.00 1.00 1.00 1274 1 1.00 1.00 1.00 1164 accuracy 1.00 2438 macro avg 1.00 1.00 1.00 2438weighted avg 1.00 1.00 1.00 2438 Finally, we can now visualize how our two classes distribution looks like creating a distribution plot of our one-dimensional data. We have considered so far methods such as PCA and LDA, which are able to perform really well in case of linear relationships between the different features, we will now move on considering how to deal with non-linear cases. Locally Linear Embedding is a dimensionality reduction technique based on Manifold Learning. A Manifold is an object of D dimensions which is embedded in an higher-dimensional space. Manifold Learning aims then to make this object representable in its original D dimensions instead of being represented in an unnecessary greater space. A typical example used to explain Manifold Learning in Machine Learning is the Swiss Roll Manifold (Figure 6). We are given as input some data which has a distribution resembling the one of a roll (in a 3D space), and we can then unroll it so that to reduce our data into a two-dimensional space. Some examples of Manifold Learning algorithms are: Isomap, Locally Linear Embedding, Modified Locally Linear Embedding, Hessian Eigenmapping, etc... I will now walk you through how to implement LLE in our example. According to the Scikit-learn documentation [3]: Locally linear embedding (LLE) seeks a lower-dimensional projection of the data which preserves distances within local neighborhoods. It can be thought of as a series of local Principal Component Analyses which are globally compared to find the best non-linear embedding. We can now run LLE on our dataset to reduce our data dimensionality to 3 dimensions, test the overall accuracy and plot the results. 2.578125[[1273 0] [1143 22]] precision recall f1-score support 0 0.53 1.00 0.69 1273 1 1.00 0.02 0.04 1165 micro avg 0.53 0.53 0.53 2438 macro avg 0.76 0.51 0.36 2438weighted avg 0.75 0.53 0.38 2438 t-SNE is non-linear dimensionality reduction technique which is typically used to visualize high dimensional datasets. Some of the main applications of t-SNE are Natural Language Processing (NLP), speech processing, etc... t-SNE works by minimizing the divergence between a distribution constituted by the pairwise probability similarities of the input features in the original high dimensional space and its equivalent in the reduced low dimensional space. t-SNE makes then use of the Kullback-Leiber (KL) divergence in order to measure the dissimilarity of the two different distributions. The KL divergence is then minimized using gradient descent. When using t-SNE, the higher dimensional space is modelled using a Gaussian Distribution, while the lower-dimensional space is modelled using a Student’s t-distribution. This is done, in order to avoid an imbalance in the neighbouring points distance distribution caused by the translation into a lower-dimensional space. We are now ready to use TSNE and reduce our dataset to just 3 features. [t-SNE] Computing 121 nearest neighbors...[t-SNE] Indexed 8124 samples in 0.139s...[t-SNE] Computed neighbors for 8124 samples in 11.891s...[t-SNE] Computed conditional probabilities for sample 1000 / 8124[t-SNE] Computed conditional probabilities for sample 2000 / 8124[t-SNE] Computed conditional probabilities for sample 3000 / 8124[t-SNE] Computed conditional probabilities for sample 4000 / 8124[t-SNE] Computed conditional probabilities for sample 5000 / 8124[t-SNE] Computed conditional probabilities for sample 6000 / 8124[t-SNE] Computed conditional probabilities for sample 7000 / 8124[t-SNE] Computed conditional probabilities for sample 8000 / 8124[t-SNE] Computed conditional probabilities for sample 8124 / 8124[t-SNE] Mean sigma: 2.658530[t-SNE] KL divergence after 250 iterations with early exaggeration: 65.601128[t-SNE] KL divergence after 300 iterations: 1.909915143.984375 Visualizing the distribution of the resulting features we can clearly see how our data has been nicely separated even though being transformed in a reduced space. Testing our Random Forest accuracy using the t-SNE reduced subset confirms that now our classes can be easily separated. 2.6462027340000134[[1274 0] [ 0 1164]] precision recall f1-score support 0 1.00 1.00 1.00 1274 1 1.00 1.00 1.00 1164 accuracy 1.00 2438 macro avg 1.00 1.00 1.00 2438weighted avg 1.00 1.00 1.00 2438 Autoencoders are a family of Machine Learning algorithms which can be used as a dimensionality reduction technique. The main difference between Autoencoders and other dimensionality reduction techniques is that Autoencoders use non-linear transformations to project data from a high dimension to a lower one. There exist different types of Autoencoders such as: Denoising Autoencoder Variational Autoencoder Convolutional Autoencoder Sparse Autoencoder In this example, we will start by building a basic Autoencoder (Figure 7). The basic architecture of an Autoencoder can be broken down into 2 main components: Encoder: takes the input data and compress it, so that to remove all the possible noise and unhelpful information. The output of the Encoder stage is usually called bottleneck or latent-space.Decoder: takes as input the encoded latent space and tries to reproduce the original Autoencoder input using just it’s compressed form (the encoded latent space). Encoder: takes the input data and compress it, so that to remove all the possible noise and unhelpful information. The output of the Encoder stage is usually called bottleneck or latent-space. Decoder: takes as input the encoded latent space and tries to reproduce the original Autoencoder input using just it’s compressed form (the encoded latent space). If all the input features are independent of each other, then the Autoencoder will find particularly difficult to encode and decode to input data into a lower-dimensional space. Autoencoders can be implemented in Python using Keras API. In this case, we specify in the encoding layer the number of features we want to get our input data reduced to (for this example 3). As we can see from the code snippet below, Autoencoders take X (our input features) as both our features and labels (X, Y). For this example, I decided to use ReLu as the activation function for the encoding stage and Softmax for the decoding stage. If I wouldn’t have used non-linear activation functions, then the Autoencoder would have tried to reduce the input data using a linear transformation (therefore giving us a result similar to if we would have used PCA). We can now repeat a similar workflow as in the previous examples, this time using a simple Autoencoder as our Feature Extraction Technique. 1.734375[[1238 36] [ 67 1097]] precision recall f1-score support 0 0.95 0.97 0.96 1274 1 0.97 0.94 0.96 1164 micro avg 0.96 0.96 0.96 2438 macro avg 0.96 0.96 0.96 2438weighted avg 0.96 0.96 0.96 2438 I hope you enjoyed this article, thank you for reading! If you want to keep updated with my latest articles and projects follow me on Medium and subscribe to my mailing list. These are some of my contacts details: Linkedin Personal Blog Personal Website Medium Profile GitHub Kaggle [1] Diving Deeper into Dimension Reduction with Independent Components Analysis (ICA), Paperspace. Accessed at: https://blog.paperspace.com/dimension-reduction-with-independent-components-analysis/ [2] Iterative Non-linear Dimensionality Reduction with Manifold Sculpting, ResearchGate. Accessed at: https://www.researchgate.net/publication/220270207_Iterative_Non-linear_Dimensionality_Reduction_with_Manifold_Sculpting [3] Manifold learning, Scikit-learn documentation. Accessed at: https://scikit-learn.org/stable/modules/manifold.html#targetText=Manifold%20learning%20is%20an%20approach,sets%20is%20only%20artificially%20high. [4] Variational Autoencoders are Beautiful, Comp Three Inc. Steven Flores. Accessed at: http://www.compthree.com/blog/autoencoder/
[ { "code": null, "e": 174, "s": 172, "text": "1" }, { "code": null, "e": 176, "s": 174, "text": "2" }, { "code": null, "e": 178, "s": 176, "text": "3" }, { "code": null, "e": 180, "s": 178, "text": "4" }, { "code": null, "e": 182, "s": 180, "text": "5" }, { "code": null, "e": 184, "s": 182, "text": "6" }, { "code": null, "e": 186, "s": 184, "text": "7" }, { "code": null, "e": 188, "s": 186, "text": "8" }, { "code": null, "e": 190, "s": 188, "text": "9" }, { "code": null, "e": 193, "s": 190, "text": "10" }, { "code": null, "e": 212, "s": 193, "text": "Powered by Play.ht" }, { "code": null, "e": 238, "s": 212, "text": "Create audio with Play.ht" }, { "code": null, "e": 275, "s": 238, "text": "Create Audio Narrations with Play.ht" }, { "code": null, "e": 841, "s": 275, "text": "It is nowadays becoming quite common to be working with datasets of hundreds (or even thousands) of features. If the number of features becomes similar (or even bigger!) than the number of observations stored in a dataset then this can most likely lead to a Machine Learning model suffering from overfitting. In order to avoid this type of problem, it is necessary to apply either regularization or dimensionality reduction techniques (Feature Extraction). In Machine Learning, the dimensionali of a dataset is equal to the number of variables used to represent it." }, { "code": null, "e": 1015, "s": 841, "text": "Using Regularization could certainly help reduce the risk of overfitting, but using instead Feature Extraction techniques can also lead to other types of advantages such as:" }, { "code": null, "e": 1038, "s": 1015, "text": "Accuracy improvements." }, { "code": null, "e": 1066, "s": 1038, "text": "Overfitting risk reduction." }, { "code": null, "e": 1088, "s": 1066, "text": "Speed up in training." }, { "code": null, "e": 1117, "s": 1088, "text": "Improved Data Visualization." }, { "code": null, "e": 1158, "s": 1117, "text": "Increase in explainability of our model." }, { "code": null, "e": 1569, "s": 1158, "text": "Feature Extraction aims to reduce the number of features in a dataset by creating new features from the existing ones (and then discarding the original features). These new reduced set of features should then be able to summarize most of the information contained in the original set of features. In this way, a summarised version of the original features can be created from a combination of the original set." }, { "code": null, "e": 2027, "s": 1569, "text": "Another commonly used technique to reduce the number of feature in a dataset is Feature Selection. The difference between Feature Selection and Feature Extraction is that feature selection aims instead to rank the importance of the existing features in the dataset and discard less important ones (no new features are created). If you are interested in finding out more about Feature Selection, you can find more information about it in my previous article." }, { "code": null, "e": 2375, "s": 2027, "text": "In this article, I will walk you through how to apply Feature Extraction techniques using the Kaggle Mushroom Classification Dataset as an example. Our objective will be to try to predict if a Mushroom is poisonous or not by looking at the given features. All the code used in this post (and more!) is available on Kaggle and on my GitHub Account." }, { "code": null, "e": 2436, "s": 2375, "text": "First of all, we need to import all the necessary libraries." }, { "code": null, "e": 2511, "s": 2436, "text": "The dataset we will be using in this example is shown in the figure below." }, { "code": null, "e": 2681, "s": 2511, "text": "Before feeding this data into our Machine Learning models I decided to divide our data into features (X) and labels (Y) and One Hot Encode all the Categorical Variables." }, { "code": null, "e": 2842, "s": 2681, "text": "Successively, I decided to create a function (forest_test) to divide the input data into train and test sets and then train and test a Random Forest Classifier." }, { "code": null, "e": 3013, "s": 2842, "text": "We can now use this function using the whole dataset and then use it successively to compare these results when using instead of the whole dataset just a reduced version." }, { "code": null, "e": 3283, "s": 3013, "text": "As shown below, training a Random Forest classifier using all the features, led to 100% Accuracy in about 2.2s of training time. In each of the following examples, the training time of each model will be printed out on the first line of each snippet for your reference." }, { "code": null, "e": 3645, "s": 3283, "text": "2.2676709799999992[[1274 0] [ 0 1164]] precision recall f1-score support 0 1.00 1.00 1.00 1274 1 1.00 1.00 1.00 1164 accuracy 1.00 2438 macro avg 1.00 1.00 1.00 2438weighted avg 1.00 1.00 1.00 2438" }, { "code": null, "e": 4167, "s": 3645, "text": "PCA is one of the most used linear dimensionality reduction technique. When using PCA, we take as input our original data and try to find a combination of the input features which can best summarize the original data distribution so that to reduce its original dimensions. PCA is able to do this by maximizing variances and minimizing the reconstruction error by looking at pair wised distances. In PCA, our original data is projected into a set of orthogonal axes and each of the axes gets ranked in order of importance." }, { "code": null, "e": 4342, "s": 4167, "text": "PCA is an unsupervised learning algorithm, therefore it doesn’t care about the data labels but only about variation. This can lead in some cases to misclassification of data." }, { "code": null, "e": 4537, "s": 4342, "text": "In this example, I will first perform PCA in the whole dataset to reduce our data to just two dimensions and I will then construct a data frame with our new features and their respective labels." }, { "code": null, "e": 4633, "s": 4537, "text": "Using our newly created data frame, we can now plot our data distribution in a 2D scatter plot." }, { "code": null, "e": 4786, "s": 4633, "text": "We can now repeat this same process keeping instead 3 dimensions and creating animations using Plotly (feel free to interact with the animation below!)." }, { "code": null, "e": 5026, "s": 4786, "text": "While using PCA, we can also explore how much of the original data variance was preserved using the explained_variance_ratio_ Scikit-learn function. Once calculated the variance ratio, we can then go on creating fancy visualization graphs." }, { "code": null, "e": 5222, "s": 5026, "text": "Running again a Random Forest Classifier using the set of 3 features constructed by PCA (instead of the whole dataset) led to 98% classification accuracy while using just 2 features 95% accuracy." }, { "code": null, "e": 5620, "s": 5222, "text": "[10.31484926 9.42671062 8.35720548]2.769664902999999[[1261 13] [ 41 1123]] precision recall f1-score support 0 0.97 0.99 0.98 1274 1 0.99 0.96 0.98 1164 accuracy 0.98 2438 macro avg 0.98 0.98 0.98 2438weighted avg 0.98 0.98 0.98 2438" }, { "code": null, "e": 5799, "s": 5620, "text": "Additionally, using our two-dimensional dataset, we can now also visualize the decision boundary used by our Random Forest in order to classify each of the different data points." }, { "code": null, "e": 6112, "s": 5799, "text": "ICA is a linear dimensionality reduction method which takes as input data a mixture of independent components and it aims to correctly identify each of them (deleting all the unnecessary noise). Two input features can be considered independent if both their linear and not linear dependance is equal to zero [1]." }, { "code": null, "e": 6262, "s": 6112, "text": "Independent Component Analysis is commonly used in medical applications such as EEG and fMRI analysis to separate useful signals from unhelpful ones." }, { "code": null, "e": 6667, "s": 6262, "text": "As a simple example of an ICA application, let’s consider we are given an audio registration in which there are two different people talking. Using ICA we could, for example, try to identify the two different independent components in the registration (the two different people). In this way, we could make our unsupervised learning algorithm recognise between the different speakers in the conversation." }, { "code": null, "e": 6811, "s": 6667, "text": "Using ICA, we can now again reduce our dataset to just three features, test its accuracy using a Random Forest Classifier and plot the results." }, { "code": null, "e": 7173, "s": 6811, "text": "2.8933812039999793[[1263 11] [ 44 1120]] precision recall f1-score support 0 0.97 0.99 0.98 1274 1 0.99 0.96 0.98 1164 accuracy 0.98 2438 macro avg 0.98 0.98 0.98 2438weighted avg 0.98 0.98 0.98 2438" }, { "code": null, "e": 7337, "s": 7173, "text": "From the animation below we can see that even though PCA and ICA led to the same accuracy results, they constructed two different 3-Dimensional space distribution." }, { "code": null, "e": 7432, "s": 7337, "text": "LDA is supervised learning dimensionality reduction technique and Machine Learning classifier." }, { "code": null, "e": 7861, "s": 7432, "text": "LDA aims to maximize the distance between the mean of each class and minimize the spreading within the class itself. LDA uses therefore within classes and between classes as measures. This is a good choice because maximizing the distance between the means of each class when projecting the data in a lower-dimensional space can lead to better classification results (thanks to the reduced overlap between the different classes)." }, { "code": null, "e": 8055, "s": 7861, "text": "When using LDA, is assumed that the input data follows a Gaussian Distribution (like in this case), therefore applying LDA to not Gaussian data can possibly lead to poor classification results." }, { "code": null, "e": 8171, "s": 8055, "text": "In this example, we will run LDA to reduce our dataset to just one feature, test its accuracy and plot the results." }, { "code": null, "e": 8233, "s": 8171, "text": "Original number of features: 117Reduced number of features: 1" }, { "code": null, "e": 8403, "s": 8233, "text": "Because our data distribution closely follows a Gaussian Distribution, LDA performed really well, in this case, achieving 100% accuracy using a Random Forest Classifier." }, { "code": null, "e": 8765, "s": 8403, "text": "1.2756952610000099[[1274 0] [ 0 1164]] precision recall f1-score support 0 1.00 1.00 1.00 1274 1 1.00 1.00 1.00 1164 accuracy 1.00 2438 macro avg 1.00 1.00 1.00 2438weighted avg 1.00 1.00 1.00 2438" }, { "code": null, "e": 8932, "s": 8765, "text": "As I mentioned at the beginning of this section, LDA can also be used as a classifier. Therefore, we can now test how an LDA Classifier can perform in this situation." }, { "code": null, "e": 9296, "s": 8932, "text": "0.008464782999993758[[1274 0] [ 2 1162]] precision recall f1-score support 0 1.00 1.00 1.00 1274 1 1.00 1.00 1.00 1164 accuracy 1.00 2438 macro avg 1.00 1.00 1.00 2438weighted avg 1.00 1.00 1.00 2438" }, { "code": null, "e": 9428, "s": 9296, "text": "Finally, we can now visualize how our two classes distribution looks like creating a distribution plot of our one-dimensional data." }, { "code": null, "e": 9652, "s": 9428, "text": "We have considered so far methods such as PCA and LDA, which are able to perform really well in case of linear relationships between the different features, we will now move on considering how to deal with non-linear cases." }, { "code": null, "e": 9988, "s": 9652, "text": "Locally Linear Embedding is a dimensionality reduction technique based on Manifold Learning. A Manifold is an object of D dimensions which is embedded in an higher-dimensional space. Manifold Learning aims then to make this object representable in its original D dimensions instead of being represented in an unnecessary greater space." }, { "code": null, "e": 10285, "s": 9988, "text": "A typical example used to explain Manifold Learning in Machine Learning is the Swiss Roll Manifold (Figure 6). We are given as input some data which has a distribution resembling the one of a roll (in a 3D space), and we can then unroll it so that to reduce our data into a two-dimensional space." }, { "code": null, "e": 10434, "s": 10285, "text": "Some examples of Manifold Learning algorithms are: Isomap, Locally Linear Embedding, Modified Locally Linear Embedding, Hessian Eigenmapping, etc..." }, { "code": null, "e": 10548, "s": 10434, "text": "I will now walk you through how to implement LLE in our example. According to the Scikit-learn documentation [3]:" }, { "code": null, "e": 10820, "s": 10548, "text": "Locally linear embedding (LLE) seeks a lower-dimensional projection of the data which preserves distances within local neighborhoods. It can be thought of as a series of local Principal Component Analyses which are globally compared to find the best non-linear embedding." }, { "code": null, "e": 10953, "s": 10820, "text": "We can now run LLE on our dataset to reduce our data dimensionality to 3 dimensions, test the overall accuracy and plot the results." }, { "code": null, "e": 11305, "s": 10953, "text": "2.578125[[1273 0] [1143 22]] precision recall f1-score support 0 0.53 1.00 0.69 1273 1 1.00 0.02 0.04 1165 micro avg 0.53 0.53 0.53 2438 macro avg 0.76 0.51 0.36 2438weighted avg 0.75 0.53 0.38 2438" }, { "code": null, "e": 11528, "s": 11305, "text": "t-SNE is non-linear dimensionality reduction technique which is typically used to visualize high dimensional datasets. Some of the main applications of t-SNE are Natural Language Processing (NLP), speech processing, etc..." }, { "code": null, "e": 11957, "s": 11528, "text": "t-SNE works by minimizing the divergence between a distribution constituted by the pairwise probability similarities of the input features in the original high dimensional space and its equivalent in the reduced low dimensional space. t-SNE makes then use of the Kullback-Leiber (KL) divergence in order to measure the dissimilarity of the two different distributions. The KL divergence is then minimized using gradient descent." }, { "code": null, "e": 12279, "s": 11957, "text": "When using t-SNE, the higher dimensional space is modelled using a Gaussian Distribution, while the lower-dimensional space is modelled using a Student’s t-distribution. This is done, in order to avoid an imbalance in the neighbouring points distance distribution caused by the translation into a lower-dimensional space." }, { "code": null, "e": 12351, "s": 12279, "text": "We are now ready to use TSNE and reduce our dataset to just 3 features." }, { "code": null, "e": 13244, "s": 12351, "text": "[t-SNE] Computing 121 nearest neighbors...[t-SNE] Indexed 8124 samples in 0.139s...[t-SNE] Computed neighbors for 8124 samples in 11.891s...[t-SNE] Computed conditional probabilities for sample 1000 / 8124[t-SNE] Computed conditional probabilities for sample 2000 / 8124[t-SNE] Computed conditional probabilities for sample 3000 / 8124[t-SNE] Computed conditional probabilities for sample 4000 / 8124[t-SNE] Computed conditional probabilities for sample 5000 / 8124[t-SNE] Computed conditional probabilities for sample 6000 / 8124[t-SNE] Computed conditional probabilities for sample 7000 / 8124[t-SNE] Computed conditional probabilities for sample 8000 / 8124[t-SNE] Computed conditional probabilities for sample 8124 / 8124[t-SNE] Mean sigma: 2.658530[t-SNE] KL divergence after 250 iterations with early exaggeration: 65.601128[t-SNE] KL divergence after 300 iterations: 1.909915143.984375" }, { "code": null, "e": 13407, "s": 13244, "text": "Visualizing the distribution of the resulting features we can clearly see how our data has been nicely separated even though being transformed in a reduced space." }, { "code": null, "e": 13528, "s": 13407, "text": "Testing our Random Forest accuracy using the t-SNE reduced subset confirms that now our classes can be easily separated." }, { "code": null, "e": 13890, "s": 13528, "text": "2.6462027340000134[[1274 0] [ 0 1164]] precision recall f1-score support 0 1.00 1.00 1.00 1274 1 1.00 1.00 1.00 1164 accuracy 1.00 2438 macro avg 1.00 1.00 1.00 2438weighted avg 1.00 1.00 1.00 2438" }, { "code": null, "e": 14199, "s": 13890, "text": "Autoencoders are a family of Machine Learning algorithms which can be used as a dimensionality reduction technique. The main difference between Autoencoders and other dimensionality reduction techniques is that Autoencoders use non-linear transformations to project data from a high dimension to a lower one." }, { "code": null, "e": 14252, "s": 14199, "text": "There exist different types of Autoencoders such as:" }, { "code": null, "e": 14274, "s": 14252, "text": "Denoising Autoencoder" }, { "code": null, "e": 14298, "s": 14274, "text": "Variational Autoencoder" }, { "code": null, "e": 14324, "s": 14298, "text": "Convolutional Autoencoder" }, { "code": null, "e": 14343, "s": 14324, "text": "Sparse Autoencoder" }, { "code": null, "e": 14502, "s": 14343, "text": "In this example, we will start by building a basic Autoencoder (Figure 7). The basic architecture of an Autoencoder can be broken down into 2 main components:" }, { "code": null, "e": 14857, "s": 14502, "text": "Encoder: takes the input data and compress it, so that to remove all the possible noise and unhelpful information. The output of the Encoder stage is usually called bottleneck or latent-space.Decoder: takes as input the encoded latent space and tries to reproduce the original Autoencoder input using just it’s compressed form (the encoded latent space)." }, { "code": null, "e": 15050, "s": 14857, "text": "Encoder: takes the input data and compress it, so that to remove all the possible noise and unhelpful information. The output of the Encoder stage is usually called bottleneck or latent-space." }, { "code": null, "e": 15213, "s": 15050, "text": "Decoder: takes as input the encoded latent space and tries to reproduce the original Autoencoder input using just it’s compressed form (the encoded latent space)." }, { "code": null, "e": 15391, "s": 15213, "text": "If all the input features are independent of each other, then the Autoencoder will find particularly difficult to encode and decode to input data into a lower-dimensional space." }, { "code": null, "e": 15707, "s": 15391, "text": "Autoencoders can be implemented in Python using Keras API. In this case, we specify in the encoding layer the number of features we want to get our input data reduced to (for this example 3). As we can see from the code snippet below, Autoencoders take X (our input features) as both our features and labels (X, Y)." }, { "code": null, "e": 16052, "s": 15707, "text": "For this example, I decided to use ReLu as the activation function for the encoding stage and Softmax for the decoding stage. If I wouldn’t have used non-linear activation functions, then the Autoencoder would have tried to reduce the input data using a linear transformation (therefore giving us a result similar to if we would have used PCA)." }, { "code": null, "e": 16192, "s": 16052, "text": "We can now repeat a similar workflow as in the previous examples, this time using a simple Autoencoder as our Feature Extraction Technique." }, { "code": null, "e": 16544, "s": 16192, "text": "1.734375[[1238 36] [ 67 1097]] precision recall f1-score support 0 0.95 0.97 0.96 1274 1 0.97 0.94 0.96 1164 micro avg 0.96 0.96 0.96 2438 macro avg 0.96 0.96 0.96 2438weighted avg 0.96 0.96 0.96 2438" }, { "code": null, "e": 16600, "s": 16544, "text": "I hope you enjoyed this article, thank you for reading!" }, { "code": null, "e": 16758, "s": 16600, "text": "If you want to keep updated with my latest articles and projects follow me on Medium and subscribe to my mailing list. These are some of my contacts details:" }, { "code": null, "e": 16767, "s": 16758, "text": "Linkedin" }, { "code": null, "e": 16781, "s": 16767, "text": "Personal Blog" }, { "code": null, "e": 16798, "s": 16781, "text": "Personal Website" }, { "code": null, "e": 16813, "s": 16798, "text": "Medium Profile" }, { "code": null, "e": 16820, "s": 16813, "text": "GitHub" }, { "code": null, "e": 16827, "s": 16820, "text": "Kaggle" }, { "code": null, "e": 17025, "s": 16827, "text": "[1] Diving Deeper into Dimension Reduction with Independent Components Analysis (ICA), Paperspace. Accessed at: https://blog.paperspace.com/dimension-reduction-with-independent-components-analysis/" }, { "code": null, "e": 17248, "s": 17025, "text": "[2] Iterative Non-linear Dimensionality Reduction with Manifold Sculpting, ResearchGate. Accessed at: https://www.researchgate.net/publication/220270207_Iterative_Non-linear_Dimensionality_Reduction_with_Manifold_Sculpting" }, { "code": null, "e": 17458, "s": 17248, "text": "[3] Manifold learning, Scikit-learn documentation. Accessed at: https://scikit-learn.org/stable/modules/manifold.html#targetText=Manifold%20learning%20is%20an%20approach,sets%20is%20only%20artificially%20high." } ]
Python | Decimal exp() method - GeeksforGeeks
05 Sep, 2019 Decimal#exp() : exp() is a Decimal class method which returns the value of the (natural) exponential function e**x at the given number Syntax: Decimal.exp() Parameter: Decimal values Return: the value of the (natural) exponential function e**x at the given number Code #1 : Example for exp() method # Python Program explaining # exp() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal(-1) b = Decimal('0.142857') # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b) # Using Decimal.exp() methodprint ("\n\nDecimal a with exp() method : ", a.exp()) print ("Decimal b with exp() method : ", b.exp()) Output : Decimal value a : -1 Decimal value b : 0.142857 Decimal a with exp() method : 0.3678794411714423215955237702 Decimal b with exp() method : 1.153564830100120253802476512 Code #2 : Example for exp() method # Python Program explaining # exp() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal('-3.14') b = Decimal('7.555') # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b) # Using Decimal.exp() methodprint ("\n\nDecimal a with exp() method : ", a.exp()) print ("Decimal b with exp() method : ", b.exp()) Output : Decimal value a : -3.14 Decimal value b : 7.555 Decimal a with exp() method : 0.04328279790196590079772976615 Decimal b with exp() method : 1910.270243928773816178935745 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python 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
[ { "code": null, "e": 26175, "s": 26147, "text": "\n05 Sep, 2019" }, { "code": null, "e": 26310, "s": 26175, "text": "Decimal#exp() : exp() is a Decimal class method which returns the value of the (natural) exponential function e**x at the given number" }, { "code": null, "e": 26332, "s": 26310, "text": "Syntax: Decimal.exp()" }, { "code": null, "e": 26358, "s": 26332, "text": "Parameter: Decimal values" }, { "code": null, "e": 26439, "s": 26358, "text": "Return: the value of the (natural) exponential function e**x at the given number" }, { "code": null, "e": 26474, "s": 26439, "text": "Code #1 : Example for exp() method" }, { "code": "# Python Program explaining # exp() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal(-1) b = Decimal('0.142857') # printing Decimal valuesprint (\"Decimal value a : \", a)print (\"Decimal value b : \", b) # Using Decimal.exp() methodprint (\"\\n\\nDecimal a with exp() method : \", a.exp()) print (\"Decimal b with exp() method : \", b.exp())", "e": 26864, "s": 26474, "text": null }, { "code": null, "e": 26873, "s": 26864, "text": "Output :" }, { "code": null, "e": 27050, "s": 26873, "text": "Decimal value a : -1\nDecimal value b : 0.142857\n\n\nDecimal a with exp() method : 0.3678794411714423215955237702\nDecimal b with exp() method : 1.153564830100120253802476512\n\n" }, { "code": null, "e": 27085, "s": 27050, "text": "Code #2 : Example for exp() method" }, { "code": "# Python Program explaining # exp() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal('-3.14') b = Decimal('7.555') # printing Decimal valuesprint (\"Decimal value a : \", a)print (\"Decimal value b : \", b) # Using Decimal.exp() methodprint (\"\\n\\nDecimal a with exp() method : \", a.exp()) print (\"Decimal b with exp() method : \", b.exp())", "e": 27477, "s": 27085, "text": null }, { "code": null, "e": 27486, "s": 27477, "text": "Output :" }, { "code": null, "e": 27663, "s": 27486, "text": "Decimal value a : -3.14\nDecimal value b : 7.555\n\n\nDecimal a with exp() method : 0.04328279790196590079772976615\nDecimal b with exp() method : 1910.270243928773816178935745\n" }, { "code": null, "e": 27670, "s": 27663, "text": "Python" }, { "code": null, "e": 27768, "s": 27670, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27786, "s": 27768, "text": "Python Dictionary" }, { "code": null, "e": 27821, "s": 27786, "text": "Read a file line by line in Python" }, { "code": null, "e": 27853, "s": 27821, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27875, "s": 27853, "text": "Enumerate() in Python" }, { "code": null, "e": 27917, "s": 27875, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27947, "s": 27917, "text": "Iterate over a list in Python" }, { "code": null, "e": 27991, "s": 27947, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28020, "s": 27991, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28057, "s": 28020, "text": "Create a Pandas DataFrame from Lists" } ]
How to Plot Histogram from List of Data in Matplotlib? - GeeksforGeeks
11 Feb, 2022 In this article, we are going to see how to Plot a Histogram from a List of Data in Matplotlib in Python. The histogram helps us to plot bar-graph with specified bins and can be created using the hist() function. Syntax: hist( dataVariable, bins=x, edgecolor=’anyColor’ ) Parameters: dataVariable- Any variable that holds a set of data. It can be a list or a column in a DataFrame etc. bins- It can be used to group the data in the DataVariable. It can accept an Integer or a list of numbers. edgecolor- It gives an edge color to each bin i.e., Each bar in histogram. We can plot the histogram using data in the list by passing a list to hist method. In this example, we passed the list to hist method to plot histogram from list of data. Here we didn’t specify edgecolor and bins parameters in hist method. So in the above output, we didn’t find any edge color to any bar and we got a random number of bins (bars). Python3 # import necessary packagesimport matplotlib.pyplot as plt # list of weightsweights = [30, 50, 45, 80, 76, 55, 45, 47, 50, 65] # plotting labelled histogramplt.hist(weights)plt.xlabel('weight')plt.ylabel('Person count')plt.show() Output: To the same data that we used in the above example, we will specify bins and edgecolor additionally in this example. Python3 # import necessary packagesimport matplotlib.pyplot as plt # list of weightsweights = [30, 50, 45, 80, 76, 55, 45, 47, 50, 65] # plotting labelled histogramplt.hist(weights, bins=5, edgecolor='black')plt.xlabel('weight')plt.ylabel('Person count')plt.show() Output: As we specified bin count as 5 we got 5 bars in the resultant plot and edgecolor helps us to distinguish bars between them if they are close to each other as the above scenario. We can also pass list of values as an argument to bins parameter in hist method. It helps us to filter the data from the list. Python3 # import necessary packagesimport matplotlib.pyplot as plt # list of weightsweights = [30, 50, 45, 80, 76, 55, 45, 47, 50, 65] # list of binsbins = [30, 40, 50, 60] # plotting labelled histogramplt.hist(weights, bins=bins, edgecolor='black')plt.xlabel('weight')plt.ylabel('Person count')plt.show() Output: As we passed the list of bins that contains 30,40,50,60 to bins parameter, so while plotting histogram from list of data python only considers the data that are in the range of specified bins. so if the data value exceeds the range then that data point is not considered while plotting. In the given list of data- 65,76,80 exceeds the bin range so, those data points are not considered during plotting the graph. germanshephered48 Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Pandas dataframe.groupby() Create a directory in Python Defaultdict in Python Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n11 Feb, 2022" }, { "code": null, "e": 25753, "s": 25647, "text": "In this article, we are going to see how to Plot a Histogram from a List of Data in Matplotlib in Python." }, { "code": null, "e": 25860, "s": 25753, "text": "The histogram helps us to plot bar-graph with specified bins and can be created using the hist() function." }, { "code": null, "e": 25919, "s": 25860, "text": "Syntax: hist( dataVariable, bins=x, edgecolor=’anyColor’ )" }, { "code": null, "e": 25931, "s": 25919, "text": "Parameters:" }, { "code": null, "e": 26033, "s": 25931, "text": "dataVariable- Any variable that holds a set of data. It can be a list or a column in a DataFrame etc." }, { "code": null, "e": 26140, "s": 26033, "text": "bins- It can be used to group the data in the DataVariable. It can accept an Integer or a list of numbers." }, { "code": null, "e": 26215, "s": 26140, "text": "edgecolor- It gives an edge color to each bin i.e., Each bar in histogram." }, { "code": null, "e": 26298, "s": 26215, "text": "We can plot the histogram using data in the list by passing a list to hist method." }, { "code": null, "e": 26563, "s": 26298, "text": "In this example, we passed the list to hist method to plot histogram from list of data. Here we didn’t specify edgecolor and bins parameters in hist method. So in the above output, we didn’t find any edge color to any bar and we got a random number of bins (bars)." }, { "code": null, "e": 26571, "s": 26563, "text": "Python3" }, { "code": "# import necessary packagesimport matplotlib.pyplot as plt # list of weightsweights = [30, 50, 45, 80, 76, 55, 45, 47, 50, 65] # plotting labelled histogramplt.hist(weights)plt.xlabel('weight')plt.ylabel('Person count')plt.show()", "e": 26811, "s": 26571, "text": null }, { "code": null, "e": 26819, "s": 26811, "text": "Output:" }, { "code": null, "e": 26936, "s": 26819, "text": "To the same data that we used in the above example, we will specify bins and edgecolor additionally in this example." }, { "code": null, "e": 26944, "s": 26936, "text": "Python3" }, { "code": "# import necessary packagesimport matplotlib.pyplot as plt # list of weightsweights = [30, 50, 45, 80, 76, 55, 45, 47, 50, 65] # plotting labelled histogramplt.hist(weights, bins=5, edgecolor='black')plt.xlabel('weight')plt.ylabel('Person count')plt.show()", "e": 27211, "s": 26944, "text": null }, { "code": null, "e": 27219, "s": 27211, "text": "Output:" }, { "code": null, "e": 27397, "s": 27219, "text": "As we specified bin count as 5 we got 5 bars in the resultant plot and edgecolor helps us to distinguish bars between them if they are close to each other as the above scenario." }, { "code": null, "e": 27524, "s": 27397, "text": "We can also pass list of values as an argument to bins parameter in hist method. It helps us to filter the data from the list." }, { "code": null, "e": 27532, "s": 27524, "text": "Python3" }, { "code": "# import necessary packagesimport matplotlib.pyplot as plt # list of weightsweights = [30, 50, 45, 80, 76, 55, 45, 47, 50, 65] # list of binsbins = [30, 40, 50, 60] # plotting labelled histogramplt.hist(weights, bins=bins, edgecolor='black')plt.xlabel('weight')plt.ylabel('Person count')plt.show()", "e": 27840, "s": 27532, "text": null }, { "code": null, "e": 27848, "s": 27840, "text": "Output:" }, { "code": null, "e": 28135, "s": 27848, "text": "As we passed the list of bins that contains 30,40,50,60 to bins parameter, so while plotting histogram from list of data python only considers the data that are in the range of specified bins. so if the data value exceeds the range then that data point is not considered while plotting." }, { "code": null, "e": 28261, "s": 28135, "text": "In the given list of data- 65,76,80 exceeds the bin range so, those data points are not considered during plotting the graph." }, { "code": null, "e": 28279, "s": 28261, "text": "germanshephered48" }, { "code": null, "e": 28286, "s": 28279, "text": "Picked" }, { "code": null, "e": 28304, "s": 28286, "text": "Python-matplotlib" }, { "code": null, "e": 28311, "s": 28304, "text": "Python" }, { "code": null, "e": 28409, "s": 28311, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28441, "s": 28409, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28483, "s": 28441, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28525, "s": 28483, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28581, "s": 28525, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28608, "s": 28581, "text": "Python Classes and Objects" }, { "code": null, "e": 28639, "s": 28608, "text": "Python | os.path.join() method" }, { "code": null, "e": 28675, "s": 28639, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 28704, "s": 28675, "text": "Create a directory in Python" }, { "code": null, "e": 28726, "s": 28704, "text": "Defaultdict in Python" } ]
AngularJS | ng-checked Directive - GeeksforGeeks
26 Mar, 2019 The ng-checked Directive in AngularJS is used to read the checked or unchecked state of the checkbox or radiobutton to true or false. If the expression inside the ng-checked attribute returns true then the checkbox/radiobutton will be checked otherwise it will be unchecked. Syntax: <input type="checkbox|radio" ng-checked="expression"> Contents... </input> If expression returns true then the element’s checked attribute will be checked. Example: This example uses ng-checked Directive to select checkbox and return the all selected checkbox value. <!DOCTYPE html><html> <head> <title>ng-checked Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body ng-app="app"> <div ng-controller="geek"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-checked Directive</h2> <input type="checkbox" ng-checked="check1 && check2 && check3 && check4 && check5" ng-model="isChecked" /><b>Select All</b><br> <input type="checkbox" ng-model="check1" ng-checked="isChecked" />First<br> <input type="checkbox" ng-model="check2" ng-checked="isChecked" />Second<br> <input type="checkbox" ng-model="check3" ng-checked="isChecked" />Three<br> <input type="checkbox" ng-model="check4" ng-checked="isChecked" /> Four<br> <input type="checkbox" ng-model="check5" ng-checked="isChecked" />Five<br><br> <b>isAllSelected = {{isChecked}}</b> </div> <script> var app = angular.module("app", []); app.controller('geek', ['$scope', function ($scope) { }]); </script></body> </html> Output:Before clicking the checkbox:After clicking the checkbox (select all): AngularJS-Directives AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular File Upload Angular PrimeNG Dropdown Component Angular | keyup event Angular PrimeNG Calendar Component Auth Guards in Angular 9/10/11 Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 29626, "s": 29598, "text": "\n26 Mar, 2019" }, { "code": null, "e": 29901, "s": 29626, "text": "The ng-checked Directive in AngularJS is used to read the checked or unchecked state of the checkbox or radiobutton to true or false. If the expression inside the ng-checked attribute returns true then the checkbox/radiobutton will be checked otherwise it will be unchecked." }, { "code": null, "e": 29909, "s": 29901, "text": "Syntax:" }, { "code": null, "e": 29984, "s": 29909, "text": "<input type=\"checkbox|radio\" ng-checked=\"expression\"> Contents... </input>" }, { "code": null, "e": 30065, "s": 29984, "text": "If expression returns true then the element’s checked attribute will be checked." }, { "code": null, "e": 30176, "s": 30065, "text": "Example: This example uses ng-checked Directive to select checkbox and return the all selected checkbox value." }, { "code": "<!DOCTYPE html><html> <head> <title>ng-checked Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body ng-app=\"app\"> <div ng-controller=\"geek\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>ng-checked Directive</h2> <input type=\"checkbox\" ng-checked=\"check1 && check2 && check3 && check4 && check5\" ng-model=\"isChecked\" /><b>Select All</b><br> <input type=\"checkbox\" ng-model=\"check1\" ng-checked=\"isChecked\" />First<br> <input type=\"checkbox\" ng-model=\"check2\" ng-checked=\"isChecked\" />Second<br> <input type=\"checkbox\" ng-model=\"check3\" ng-checked=\"isChecked\" />Three<br> <input type=\"checkbox\" ng-model=\"check4\" ng-checked=\"isChecked\" /> Four<br> <input type=\"checkbox\" ng-model=\"check5\" ng-checked=\"isChecked\" />Five<br><br> <b>isAllSelected = {{isChecked}}</b> </div> <script> var app = angular.module(\"app\", []); app.controller('geek', ['$scope', function ($scope) { }]); </script></body> </html>", "e": 31431, "s": 30176, "text": null }, { "code": null, "e": 31509, "s": 31431, "text": "Output:Before clicking the checkbox:After clicking the checkbox (select all):" }, { "code": null, "e": 31530, "s": 31509, "text": "AngularJS-Directives" }, { "code": null, "e": 31540, "s": 31530, "text": "AngularJS" }, { "code": null, "e": 31557, "s": 31540, "text": "Web Technologies" }, { "code": null, "e": 31655, "s": 31557, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31675, "s": 31655, "text": "Angular File Upload" }, { "code": null, "e": 31710, "s": 31675, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 31732, "s": 31710, "text": "Angular | keyup event" }, { "code": null, "e": 31767, "s": 31732, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 31798, "s": 31767, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 31838, "s": 31798, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31871, "s": 31838, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31916, "s": 31871, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31959, "s": 31916, "text": "How to fetch data from an API in ReactJS ?" } ]
Can we declare the method of an Interface final in java?
An interface in Java is a specification of method prototypes. Whenever you need to guide the programmer or, make a contract specifying how the methods and fields of a type should be you can define an interface. By default, all the methods of an interface are public and abstract. For example, In the following Java program, we are having a declaring a method with name demo. public interface MyInterface{ void demo(); } If you compile this using the javac command as shown below − c:\Examples>javac MyInterface.java it gets compiled without errors. But, if you verify the interface after compilation using the javap command as shown below − c:\Examples>javap MyInterface Compiled from "MyInterface.java" public interface MyInterface { public abstract void demo(); } You can observe that the compiler has placed the public and, abstract modifiers before the method on behalf of you. In addition to this as of Java9 you can have default, static, private, private and static with the methods of an interface. Except these you cannot use any other modifiers with the methods of an interface. Moreover, if you declare a method final you cannot override/implement it and, an abstract method must be overridden or implemented. Therefore, you cannot declare the method of an interface final. If you still do so, it generates a compile time error saying “modifier final not allowed here”. In the following Java program, we are trying to declare a method of an interface final. public interface MyInterface{ public abstract final void demo(); } On compiling, the above program generates the following compile time error − MyInterface.java:2: error: modifier final not allowed here public abstract final void demo(); ^ 1 error
[ { "code": null, "e": 1273, "s": 1062, "text": "An interface in Java is a specification of method prototypes. Whenever you need to guide the programmer or, make a contract specifying how the methods and fields of a type should be you can define an interface." }, { "code": null, "e": 1437, "s": 1273, "text": "By default, all the methods of an interface are public and abstract. For example, In the following Java program, we are having a declaring a method with name demo." }, { "code": null, "e": 1485, "s": 1437, "text": "public interface MyInterface{\n void demo();\n}" }, { "code": null, "e": 1546, "s": 1485, "text": "If you compile this using the javac command as shown below −" }, { "code": null, "e": 1581, "s": 1546, "text": "c:\\Examples>javac MyInterface.java" }, { "code": null, "e": 1706, "s": 1581, "text": "it gets compiled without errors. But, if you verify the interface after compilation using the javap command as shown below −" }, { "code": null, "e": 1834, "s": 1706, "text": "c:\\Examples>javap MyInterface\nCompiled from \"MyInterface.java\"\npublic interface MyInterface {\n public abstract void demo();\n}" }, { "code": null, "e": 1950, "s": 1834, "text": "You can observe that the compiler has placed the public and, abstract modifiers before the method on behalf of you." }, { "code": null, "e": 2156, "s": 1950, "text": "In addition to this as of Java9 you can have default, static, private, private and static with the methods of an interface. Except these you cannot use any other modifiers with the methods of an interface." }, { "code": null, "e": 2352, "s": 2156, "text": "Moreover, if you declare a method final you cannot override/implement it and, an abstract method must be overridden or implemented. Therefore, you cannot declare the method of an interface final." }, { "code": null, "e": 2448, "s": 2352, "text": "If you still do so, it generates a compile time error saying “modifier final not allowed here”." }, { "code": null, "e": 2536, "s": 2448, "text": "In the following Java program, we are trying to declare a method of an interface final." }, { "code": null, "e": 2606, "s": 2536, "text": "public interface MyInterface{\n public abstract final void demo();\n}" }, { "code": null, "e": 2683, "s": 2606, "text": "On compiling, the above program generates the following compile time error −" }, { "code": null, "e": 2820, "s": 2683, "text": "MyInterface.java:2: error: modifier final not allowed here\n public abstract final void demo();\n ^\n1 error" } ]
ByteBuffer putChar() methods in Java with Examples - GeeksforGeeks
24 Jun, 2019 The putChar(char value) method of java.nio.ByteBuffer Class is used to write two bytes containing the given char value, in the current byte order, into this buffer at the current position, and then increments the position by two. Syntax: public abstract ByteBuffer putChar(char value) Parameters: This method takes the char value to be written. Return Value: This method returns this buffer. Exception: This method throws the following exceptions: BufferOverflowException- If this buffer’s current position is not smaller than its limit ReadOnlyBufferException- If this buffer is read-only Below are the examples to illustrate the putChar(char value) method: Example 1: // Java program to demonstrate// putChar() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 6; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer // using putChar() method bb.putChar('a') .putChar('b') .putChar('c') .rewind(); // print the ByteBuffer System.out.print("Original ByteBuffer: [ "); for (int i = 1; i <= capacity / 2; i++) System.out.print(bb.getChar() + " "); System.out.print("]"); } catch (BufferOverflowException e) { System.out.println("Exception throws : " + e); } catch (ReadOnlyBufferException e) { System.out.println("Exception throws : " + e); } }} Original ByteBuffer: [ a b c ] Example 2: To demonstrate BufferOverflowException. // Java program to demonstrate// putChar() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 6; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer // using putChar() method bb.putChar('a') .putChar('b') .putChar('c') .rewind(); // print the ByteBuffer System.out.print("Original ByteBuffer: [ "); for (int i = 1; i <= capacity / 2; i++) System.out.print(bb.getChar() + " "); System.out.print("]\n\n"); // putting the value in ByteBuffer // using putChar() method bb.putChar('d'); } catch (BufferOverflowException e) { System.out.println("buffer's current position" + " is not smaller than" + " its limit"); System.out.println("Exception throws : " + e); } catch (ReadOnlyBufferException e) { System.out.println("Exception throws : " + e); } }} Original ByteBuffer: [ a b c ] buffer's current position is not smaller than its limit Exception throws : java.nio.BufferOverflowException Examples 3: To demonstrate ReadOnlyBufferException. // Java program to demonstrate// putChar() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 6; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer // using putChar() method bb.putChar('a') .putChar('b') .putChar('c') .rewind(); // print the ByteBuffer System.out.print("Original ByteBuffer: [ "); for (int i = 1; i <= capacity / 2; i++) System.out.print(bb.getChar() + " "); System.out.print("]\n"); // Creating a read-only copy of ByteBuffer // using asReadOnlyBuffer() method ByteBuffer bb1 = bb.asReadOnlyBuffer(); System.out.println("\nTrying to put the char value" + " in read-only buffer"); // putting the value in readonly ByteBuffer // using putChart() method bb1.putChar('d'); } catch (BufferOverflowException e) { System.out.println("Exception throws : " + e); } catch (ReadOnlyBufferException e) { System.out.println("Exception throws : " + e); } }} Original ByteBuffer: [ a b c ] Trying to put the char value in read-only buffer Exception throws : java.nio.ReadOnlyBufferException The putChar(int index, char value) method of java.nio.ByteBuffer Class is used to write two bytes containing the given char value, in the current byte order, into this buffer at the given index. Syntax: public abstract ByteBuffer putChar(int index, char value) Parameters: This method takes the following arguments as a parameter: index: The index at which the byte will be written value: The char value to be written Return Value: This method returns the this buffer. Exception: This method throws the following exception: IndexOutOfBoundsException- If index is negative or not smaller than the buffer’s limit ReadOnlyBufferException- If this buffer is read-only Below are the examples to illustrate the putChar(int index, char value) method: Example 1: // Java program to demonstrate// putChar() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 6; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer // using putChar() at index 0 bb.putChar(0, 'a'); // putting the value in ByteBuffer // using putChar() at index 2 bb.putChar(2, 'b'); // putting the value in ByteBuffer // using putChar() at index 1 bb.putChar(4, 'c'); // rewinding the ByteBuffer bb.rewind(); // print the ByteBuffer System.out.print("Original ByteBuffer: [ "); for (int i = 1; i <= capacity / 2; i++) System.out.print(bb.getChar() + " "); System.out.print("]\n"); } catch (IndexOutOfBoundsException e) { System.out.println("Exception throws : " + e); } catch (ReadOnlyBufferException e) { System.out.println("Exception throws : " + e); } }} Original ByteBuffer: [ a b c ] Example 2: To demonstrate IndexOutOfBoundsException. // Java program to demonstrate// putChar() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 6; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer // using putChar() at index 0 bb.putChar(0, 'a'); // putting the value in ByteBuffer // using putChar() at index 2 bb.putChar(2, 'b'); // putting the value in ByteBuffer // using putChar() at index 1 bb.putChar(4, 'c'); // rewinding the ByteBuffer bb.rewind(); // print the ByteBuffer System.out.print("Original ByteBuffer: [ "); for (int i = 1; i <= capacity / 2; i++) System.out.print(bb.getChar() + " "); System.out.print("]\n"); // putting the value in ByteBuffer // using put() at index -1 bb.putChar(-1, 'd'); } catch (IndexOutOfBoundsException e) { System.out.println("\nindex is negative or not smaller " + "than the buffer's limit"); System.out.println("Exception throws : " + e); } catch (ReadOnlyBufferException e) { System.out.println("Exception throws : " + e); } }} Original ByteBuffer: [ a b c ] index is negative or not smaller than the buffer's limit Exception throws : java.lang.IndexOutOfBoundsException Example 3: To demonstrate ReadOnlyBufferException. // Java program to demonstrate// putChar() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 6; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // Creating a read-only copy of ByteBuffer // using asReadOnlyBuffer() method ByteBuffer bb1 = bb.asReadOnlyBuffer(); System.out.println("Trying to put the byte value" + " in read-only buffer"); // putting the value in readonly ByteBuffer // using putChar() method bb1.putChar(4, 'c'); } catch (IndexOutOfBoundsException e) { System.out.println("Exception throws : " + e); } catch (ReadOnlyBufferException e) { System.out.println("Exception throws : " + e); } }} Trying to put the byte value in read-only buffer Exception throws : java.nio.ReadOnlyBufferException Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#putChar-char- https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#putChar-int-char- Java-ByteBuffer Java-Functions Java-NIO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Different ways of Reading a text file in Java Constructors in Java Stream In Java Exceptions in Java Generics in Java Comparator Interface in Java with Examples StringBuilder Class in Java with Examples HashMap get() Method in Java Functional Interfaces in Java Strings in Java
[ { "code": null, "e": 23868, "s": 23840, "text": "\n24 Jun, 2019" }, { "code": null, "e": 24098, "s": 23868, "text": "The putChar(char value) method of java.nio.ByteBuffer Class is used to write two bytes containing the given char value, in the current byte order, into this buffer at the current position, and then increments the position by two." }, { "code": null, "e": 24106, "s": 24098, "text": "Syntax:" }, { "code": null, "e": 24153, "s": 24106, "text": "public abstract ByteBuffer putChar(char value)" }, { "code": null, "e": 24213, "s": 24153, "text": "Parameters: This method takes the char value to be written." }, { "code": null, "e": 24260, "s": 24213, "text": "Return Value: This method returns this buffer." }, { "code": null, "e": 24316, "s": 24260, "text": "Exception: This method throws the following exceptions:" }, { "code": null, "e": 24405, "s": 24316, "text": "BufferOverflowException- If this buffer’s current position is not smaller than its limit" }, { "code": null, "e": 24458, "s": 24405, "text": "ReadOnlyBufferException- If this buffer is read-only" }, { "code": null, "e": 24527, "s": 24458, "text": "Below are the examples to illustrate the putChar(char value) method:" }, { "code": null, "e": 24538, "s": 24527, "text": "Example 1:" }, { "code": "// Java program to demonstrate// putChar() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 6; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer // using putChar() method bb.putChar('a') .putChar('b') .putChar('c') .rewind(); // print the ByteBuffer System.out.print(\"Original ByteBuffer: [ \"); for (int i = 1; i <= capacity / 2; i++) System.out.print(bb.getChar() + \" \"); System.out.print(\"]\"); } catch (BufferOverflowException e) { System.out.println(\"Exception throws : \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"Exception throws : \" + e); } }}", "e": 25638, "s": 24538, "text": null }, { "code": null, "e": 25670, "s": 25638, "text": "Original ByteBuffer: [ a b c ]\n" }, { "code": null, "e": 25721, "s": 25670, "text": "Example 2: To demonstrate BufferOverflowException." }, { "code": "// Java program to demonstrate// putChar() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 6; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer // using putChar() method bb.putChar('a') .putChar('b') .putChar('c') .rewind(); // print the ByteBuffer System.out.print(\"Original ByteBuffer: [ \"); for (int i = 1; i <= capacity / 2; i++) System.out.print(bb.getChar() + \" \"); System.out.print(\"]\\n\\n\"); // putting the value in ByteBuffer // using putChar() method bb.putChar('d'); } catch (BufferOverflowException e) { System.out.println(\"buffer's current position\" + \" is not smaller than\" + \" its limit\"); System.out.println(\"Exception throws : \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"Exception throws : \" + e); } }}", "e": 27096, "s": 25721, "text": null }, { "code": null, "e": 27237, "s": 27096, "text": "Original ByteBuffer: [ a b c ]\n\nbuffer's current position is not smaller than its limit\nException throws : java.nio.BufferOverflowException\n" }, { "code": null, "e": 27289, "s": 27237, "text": "Examples 3: To demonstrate ReadOnlyBufferException." }, { "code": "// Java program to demonstrate// putChar() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 6; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer // using putChar() method bb.putChar('a') .putChar('b') .putChar('c') .rewind(); // print the ByteBuffer System.out.print(\"Original ByteBuffer: [ \"); for (int i = 1; i <= capacity / 2; i++) System.out.print(bb.getChar() + \" \"); System.out.print(\"]\\n\"); // Creating a read-only copy of ByteBuffer // using asReadOnlyBuffer() method ByteBuffer bb1 = bb.asReadOnlyBuffer(); System.out.println(\"\\nTrying to put the char value\" + \" in read-only buffer\"); // putting the value in readonly ByteBuffer // using putChart() method bb1.putChar('d'); } catch (BufferOverflowException e) { System.out.println(\"Exception throws : \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"Exception throws : \" + e); } }}", "e": 28784, "s": 27289, "text": null }, { "code": null, "e": 28918, "s": 28784, "text": "Original ByteBuffer: [ a b c ]\n\nTrying to put the char value in read-only buffer\nException throws : java.nio.ReadOnlyBufferException\n" }, { "code": null, "e": 29113, "s": 28918, "text": "The putChar(int index, char value) method of java.nio.ByteBuffer Class is used to write two bytes containing the given char value, in the current byte order, into this buffer at the given index." }, { "code": null, "e": 29121, "s": 29113, "text": "Syntax:" }, { "code": null, "e": 29179, "s": 29121, "text": "public abstract ByteBuffer putChar(int index, char value)" }, { "code": null, "e": 29249, "s": 29179, "text": "Parameters: This method takes the following arguments as a parameter:" }, { "code": null, "e": 29300, "s": 29249, "text": "index: The index at which the byte will be written" }, { "code": null, "e": 29336, "s": 29300, "text": "value: The char value to be written" }, { "code": null, "e": 29387, "s": 29336, "text": "Return Value: This method returns the this buffer." }, { "code": null, "e": 29442, "s": 29387, "text": "Exception: This method throws the following exception:" }, { "code": null, "e": 29529, "s": 29442, "text": "IndexOutOfBoundsException- If index is negative or not smaller than the buffer’s limit" }, { "code": null, "e": 29582, "s": 29529, "text": "ReadOnlyBufferException- If this buffer is read-only" }, { "code": null, "e": 29662, "s": 29582, "text": "Below are the examples to illustrate the putChar(int index, char value) method:" }, { "code": null, "e": 29673, "s": 29662, "text": "Example 1:" }, { "code": "// Java program to demonstrate// putChar() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 6; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer // using putChar() at index 0 bb.putChar(0, 'a'); // putting the value in ByteBuffer // using putChar() at index 2 bb.putChar(2, 'b'); // putting the value in ByteBuffer // using putChar() at index 1 bb.putChar(4, 'c'); // rewinding the ByteBuffer bb.rewind(); // print the ByteBuffer System.out.print(\"Original ByteBuffer: [ \"); for (int i = 1; i <= capacity / 2; i++) System.out.print(bb.getChar() + \" \"); System.out.print(\"]\\n\"); } catch (IndexOutOfBoundsException e) { System.out.println(\"Exception throws : \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"Exception throws : \" + e); } }}", "e": 31011, "s": 29673, "text": null }, { "code": null, "e": 31043, "s": 31011, "text": "Original ByteBuffer: [ a b c ]\n" }, { "code": null, "e": 31096, "s": 31043, "text": "Example 2: To demonstrate IndexOutOfBoundsException." }, { "code": "// Java program to demonstrate// putChar() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 6; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer // using putChar() at index 0 bb.putChar(0, 'a'); // putting the value in ByteBuffer // using putChar() at index 2 bb.putChar(2, 'b'); // putting the value in ByteBuffer // using putChar() at index 1 bb.putChar(4, 'c'); // rewinding the ByteBuffer bb.rewind(); // print the ByteBuffer System.out.print(\"Original ByteBuffer: [ \"); for (int i = 1; i <= capacity / 2; i++) System.out.print(bb.getChar() + \" \"); System.out.print(\"]\\n\"); // putting the value in ByteBuffer // using put() at index -1 bb.putChar(-1, 'd'); } catch (IndexOutOfBoundsException e) { System.out.println(\"\\nindex is negative or not smaller \" + \"than the buffer's limit\"); System.out.println(\"Exception throws : \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"Exception throws : \" + e); } }}", "e": 32679, "s": 31096, "text": null }, { "code": null, "e": 32824, "s": 32679, "text": "Original ByteBuffer: [ a b c ]\n\nindex is negative or not smaller than the buffer's limit\nException throws : java.lang.IndexOutOfBoundsException\n" }, { "code": null, "e": 32875, "s": 32824, "text": "Example 3: To demonstrate ReadOnlyBufferException." }, { "code": "// Java program to demonstrate// putChar() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 6; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // Creating a read-only copy of ByteBuffer // using asReadOnlyBuffer() method ByteBuffer bb1 = bb.asReadOnlyBuffer(); System.out.println(\"Trying to put the byte value\" + \" in read-only buffer\"); // putting the value in readonly ByteBuffer // using putChar() method bb1.putChar(4, 'c'); } catch (IndexOutOfBoundsException e) { System.out.println(\"Exception throws : \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"Exception throws : \" + e); } }}", "e": 33951, "s": 32875, "text": null }, { "code": null, "e": 34053, "s": 33951, "text": "Trying to put the byte value in read-only buffer\nException throws : java.nio.ReadOnlyBufferException\n" }, { "code": null, "e": 34064, "s": 34053, "text": "Reference:" }, { "code": null, "e": 34145, "s": 34064, "text": "https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#putChar-char-" }, { "code": null, "e": 34230, "s": 34145, "text": "https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#putChar-int-char-" }, { "code": null, "e": 34246, "s": 34230, "text": "Java-ByteBuffer" }, { "code": null, "e": 34261, "s": 34246, "text": "Java-Functions" }, { "code": null, "e": 34278, "s": 34261, "text": "Java-NIO package" }, { "code": null, "e": 34283, "s": 34278, "text": "Java" }, { "code": null, "e": 34288, "s": 34283, "text": "Java" }, { "code": null, "e": 34386, "s": 34288, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34395, "s": 34386, "text": "Comments" }, { "code": null, "e": 34408, "s": 34395, "text": "Old Comments" }, { "code": null, "e": 34454, "s": 34408, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 34475, "s": 34454, "text": "Constructors in Java" }, { "code": null, "e": 34490, "s": 34475, "text": "Stream In Java" }, { "code": null, "e": 34509, "s": 34490, "text": "Exceptions in Java" }, { "code": null, "e": 34526, "s": 34509, "text": "Generics in Java" }, { "code": null, "e": 34569, "s": 34526, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 34611, "s": 34569, "text": "StringBuilder Class in Java with Examples" }, { "code": null, "e": 34640, "s": 34611, "text": "HashMap get() Method in Java" }, { "code": null, "e": 34670, "s": 34640, "text": "Functional Interfaces in Java" } ]
Check if the characters of a given string are in alphabetical order - GeeksforGeeks
13 May, 2021 Given a string ‘s’, the task is to find if the characters of the string are in alphabetical order. The string contains only lowercase characters. Examples: Input: Str = "aabbbcc" Output: In alphabetical order Input: Str = "aabbbcca" Output: Not in alphabetical order A simple approach: Store the string to a character array and sort the array. If the characters in the sorted array are in the same order as the string then print ‘In alphabetical order ‘. Print ‘Not in alphabetical order’ otherwise. Below is the implementation of the above approach : C++ Java Python3 C# PHP Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function that checks whether// the string is in alphabetical// order or notbool isAlphabaticOrder(string s){ // length of the string int n = s.length(); // create a character array // of the length of the string char c[n]; // assign the string // to character array for (int i = 0; i < n; i++) { c[i] = s[i]; } // sort the character array sort(c, c + n); // check if the character array // is equal to the string or not for (int i = 0; i < n; i++) if (c[i] != s[i]) return false; return true; } // Driver codeint main(){ string s = "aabbbcc"; // check whether the string is // in alphabetical order or not if (isAlphabaticOrder(s)) cout << "Yes"; else cout << "No"; return 0;} // Java implementation of above approach // import Arrays classimport java.util.Arrays; public class GFG { // Function that checks whether // the string is in alphabetical // order or not static boolean isAlphabaticOrder(String s) { // length of the string int n = s.length(); // create a character array // of the length of the string char c[] = new char [n]; // assign the string // to character array for (int i = 0; i < n; i++) { c[i] = s.charAt(i); } // sort the character array Arrays.sort(c); // check if the character array // is equal to the string or not for (int i = 0; i < n; i++) if (c[i] != s.charAt(i)) return false; return true; } public static void main(String args[]) { String s = "aabbbcc"; // check whether the string is // in alphabetical order or not if (isAlphabaticOrder(s)) System.out.println("Yes"); else System.out.println("No"); } // This Code is contributed by ANKITRAI1} # Python 3 implementation of above approach # Function that checks whether# the string is in alphabetical# order or notdef isAlphabaticOrder(s): # length of the string n = len(s) # create a character array # of the length of the string c = [s[i] for i in range(len(s))] # sort the character array c.sort(reverse = False) # check if the character array # is equal to the string or not for i in range(n): if (c[i] != s[i]): return False return True # Driver codeif __name__ == '__main__': s = "aabbbcc" # check whether the string is # in alphabetical order or not if (isAlphabaticOrder(s)): print("Yes") else: print("No") # This code is contributed by# Surendra_Gangwar // C# implementation of above approach// import Arrays class using System; public class GFG{ // Function that checks whether // the string is in alphabetical // order or not static bool isAlphabaticOrder(String s) { // length of the string int n = s.Length; // create a character array // of the length of the string char []c = new char [n]; // assign the string // to character array for (int i = 0; i < n; i++) { c[i] = s[i]; } // sort the character array Array.Sort(c); // check if the character array // is equal to the string or not for (int i = 0; i < n; i++) if (c[i] != s[i]) return false; return true; } static public void Main (){ String s = "aabbbcc"; // check whether the string is // in alphabetical order or not if (isAlphabaticOrder(s)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} <?php// PHP implementation of above approach // Function that checks whether// the string is in alphabetical// order or notFunction isAlphabaticOrder($s){ // length of the string $n = strlen($s); $c = array(); // assign the string // to character array for ($i = 0; $i < $n; $i++) { $c[$i] = $s[$i]; } // sort the character array sort($c); // check if the character array // is equal to the string or not for ($i = 0; $i < $n; $i++) if ($c[$i] != $s[$i]) return false; return true;} // Driver code$s = "aabbbcc"; // check whether the string is// in alphabetical order or notif (isAlphabaticOrder($s)) echo "Yes";else echo "No"; // This Code is contributed// by Shivi_Aggarwal?> <script>//Javascript implementation of above approach // Function that checks whether// the string is in alphabetical// order or notfunction isAlphabaticOrder(s){ // length of the string var n = s.length; // create a character array // of the length of the string var c = new Array(n); // assign the string // to character array for (var i = 0; i < n; i++) { c[i] = s[i]; } // sort the character array c.sort(); // check if the character array // is equal to the string or not for (var i = 0; i < n; i++) if (c[i] != s[i]) return false; return true; } s = "aabbbcc"; // check whether the string is// in alphabetical order or notif (isAlphabaticOrder(s)) document.write( "Yes");else document.write( "No"); //This code is contributed by SoumikMondal</script> Yes Time Complexity: O(N*log(N)) Auxiliary Space: O(N)Efficient approach: Run a loop from 1 to (n-1) (where n is the length of the string) Check whether the element at index ‘i’ is less than the element at index ‘i-1’. If yes, then print ‘In alphabetical order ‘. Print ‘Not in alphabetical order’ otherwise. Below is the implementation of the above approach C++ Java Python 3 C# PHP Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function that checks whether// the string is in alphabetical// order or notbool isAlphabaticOrder(string s){ int n = s.length(); for (int i = 1; i < n; i++) { // if element at index 'i' is less // than the element at index 'i-1' // then the string is not sorted if (s[i] < s[i - 1]) return false; } return true;} // Driver codeint main(){ string s = "aabbbcc"; // check whether the string is // in alphabetical order or not if (isAlphabaticOrder(s)) cout << "Yes"; else cout << "No"; return 0;} // Java implementation of above approachpublic class GFG { // Function that checks whether// the string is in alphabetical// order or not static boolean isAlphabaticOrder(String s) { int n = s.length(); for (int i = 1; i < n; i++) { // if element at index 'i' is less // than the element at index 'i-1' // then the string is not sorted if (s.charAt(i) < s.charAt(i - 1)) { return false; } } return true; } // Driver code static public void main(String[] args) { String s = "aabbbcc"; // check whether the string is // in alphabetical order or not if (isAlphabaticOrder(s)) { System.out.println("Yes"); } else { System.out.println("No"); } }}//This code is contributed by PrinciRaj1992 # Python 3 implementation of above approach # Function that checks whether# the string is in alphabetical# order or notdef isAlphabaticOrder(s): n = len(s) for i in range(1, n): # if element at index 'i' is less # than the element at index 'i-1' # then the string is not sorted if (s[i] < s[i - 1]) : return False return True # Driver codeif __name__ == "__main__": s = "aabbbcc" # check whether the string is # in alphabetical order or not if (isAlphabaticOrder(s)): print("Yes") else: print("No") // C# implementation of above approachusing System; public class GFG{ // Function that checks whether// the string is in alphabetical// order or notstatic bool isAlphabaticOrder(string s){ int n = s.Length; for (int i = 1; i < n; i++) { // if element at index 'i' is less // than the element at index 'i-1' // then the string is not sorted if (s[i] < s[i - 1]) return false; } return true;} // Driver code static public void Main (){ string s = "aabbbcc"; // check whether the string is // in alphabetical order or not if (isAlphabaticOrder(s)) Console.WriteLine ("Yes"); else Console.WriteLine ("No"); }} <?php// PHP implementation of above approach // Function that checks whether// the string is in alphabetical// order or notfunction isAlphabaticOrder($s){ $n = strlen($s); for ($i = 1; $i < $n; $i++) { // if element at index 'i' is less // than the element at index 'i-1' // then the string is not sorted if ($s[$i] < $s[$i - 1]) return false; } return true;} // Driver code$s = "aabbbcc"; // check whether the string is// in alphabetical order or notif (isAlphabaticOrder($s)) echo "Yes";else echo "No"; // This code is contributed// by Sach_Code?> <script>// JavaScript implementation of above approach // Function that checks whether// the string is in alphabetical// order or notfunction isAlphabaticOrder( s){ let n = s.length; for (let i = 1; i < n; i++) { // if element at index 'i' is less // than the element at index 'i-1' // then the string is not sorted if (s[i] < s[i - 1]) return false; } return true;} // Driver codelet s = "aabbbcc";// check whether the string is// in alphabetical order or notif (isAlphabaticOrder(s)) document.write("Yes");else document.write("No");</script> Yes Time Complexity: O(N)Auxiliary Space: O(1) ankthon Shivi_Aggarwal Sach_Code princiraj1992 SURENDRA_GANGWAR ukasp subham348 SoumikMondal rohan07 Competitive Programming Sorting Strings Strings Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Bits manipulation (Important tactics) Breadth First Traversal ( BFS ) on a 2D array Remove all occurrences of a character in a string | Recursive approach String hashing using Polynomial rolling hash function Sequence Alignment problem
[ { "code": null, "e": 24579, "s": 24551, "text": "\n13 May, 2021" }, { "code": null, "e": 24727, "s": 24579, "text": "Given a string ‘s’, the task is to find if the characters of the string are in alphabetical order. The string contains only lowercase characters. " }, { "code": null, "e": 24738, "s": 24727, "text": "Examples: " }, { "code": null, "e": 24850, "s": 24738, "text": "Input: Str = \"aabbbcc\"\nOutput: In alphabetical order\n\nInput: Str = \"aabbbcca\"\nOutput: Not in alphabetical order" }, { "code": null, "e": 24870, "s": 24850, "text": "A simple approach: " }, { "code": null, "e": 24928, "s": 24870, "text": "Store the string to a character array and sort the array." }, { "code": null, "e": 25039, "s": 24928, "text": "If the characters in the sorted array are in the same order as the string then print ‘In alphabetical order ‘." }, { "code": null, "e": 25084, "s": 25039, "text": "Print ‘Not in alphabetical order’ otherwise." }, { "code": null, "e": 25138, "s": 25084, "text": "Below is the implementation of the above approach : " }, { "code": null, "e": 25142, "s": 25138, "text": "C++" }, { "code": null, "e": 25147, "s": 25142, "text": "Java" }, { "code": null, "e": 25155, "s": 25147, "text": "Python3" }, { "code": null, "e": 25158, "s": 25155, "text": "C#" }, { "code": null, "e": 25162, "s": 25158, "text": "PHP" }, { "code": null, "e": 25173, "s": 25162, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function that checks whether// the string is in alphabetical// order or notbool isAlphabaticOrder(string s){ // length of the string int n = s.length(); // create a character array // of the length of the string char c[n]; // assign the string // to character array for (int i = 0; i < n; i++) { c[i] = s[i]; } // sort the character array sort(c, c + n); // check if the character array // is equal to the string or not for (int i = 0; i < n; i++) if (c[i] != s[i]) return false; return true; } // Driver codeint main(){ string s = \"aabbbcc\"; // check whether the string is // in alphabetical order or not if (isAlphabaticOrder(s)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 26054, "s": 25173, "text": null }, { "code": "// Java implementation of above approach // import Arrays classimport java.util.Arrays; public class GFG { // Function that checks whether // the string is in alphabetical // order or not static boolean isAlphabaticOrder(String s) { // length of the string int n = s.length(); // create a character array // of the length of the string char c[] = new char [n]; // assign the string // to character array for (int i = 0; i < n; i++) { c[i] = s.charAt(i); } // sort the character array Arrays.sort(c); // check if the character array // is equal to the string or not for (int i = 0; i < n; i++) if (c[i] != s.charAt(i)) return false; return true; } public static void main(String args[]) { String s = \"aabbbcc\"; // check whether the string is // in alphabetical order or not if (isAlphabaticOrder(s)) System.out.println(\"Yes\"); else System.out.println(\"No\"); } // This Code is contributed by ANKITRAI1}", "e": 27258, "s": 26054, "text": null }, { "code": "# Python 3 implementation of above approach # Function that checks whether# the string is in alphabetical# order or notdef isAlphabaticOrder(s): # length of the string n = len(s) # create a character array # of the length of the string c = [s[i] for i in range(len(s))] # sort the character array c.sort(reverse = False) # check if the character array # is equal to the string or not for i in range(n): if (c[i] != s[i]): return False return True # Driver codeif __name__ == '__main__': s = \"aabbbcc\" # check whether the string is # in alphabetical order or not if (isAlphabaticOrder(s)): print(\"Yes\") else: print(\"No\") # This code is contributed by# Surendra_Gangwar", "e": 28024, "s": 27258, "text": null }, { "code": "// C# implementation of above approach// import Arrays class using System; public class GFG{ // Function that checks whether // the string is in alphabetical // order or not static bool isAlphabaticOrder(String s) { // length of the string int n = s.Length; // create a character array // of the length of the string char []c = new char [n]; // assign the string // to character array for (int i = 0; i < n; i++) { c[i] = s[i]; } // sort the character array Array.Sort(c); // check if the character array // is equal to the string or not for (int i = 0; i < n; i++) if (c[i] != s[i]) return false; return true; } static public void Main (){ String s = \"aabbbcc\"; // check whether the string is // in alphabetical order or not if (isAlphabaticOrder(s)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }}", "e": 29119, "s": 28024, "text": null }, { "code": "<?php// PHP implementation of above approach // Function that checks whether// the string is in alphabetical// order or notFunction isAlphabaticOrder($s){ // length of the string $n = strlen($s); $c = array(); // assign the string // to character array for ($i = 0; $i < $n; $i++) { $c[$i] = $s[$i]; } // sort the character array sort($c); // check if the character array // is equal to the string or not for ($i = 0; $i < $n; $i++) if ($c[$i] != $s[$i]) return false; return true;} // Driver code$s = \"aabbbcc\"; // check whether the string is// in alphabetical order or notif (isAlphabaticOrder($s)) echo \"Yes\";else echo \"No\"; // This Code is contributed// by Shivi_Aggarwal?>", "e": 29896, "s": 29119, "text": null }, { "code": "<script>//Javascript implementation of above approach // Function that checks whether// the string is in alphabetical// order or notfunction isAlphabaticOrder(s){ // length of the string var n = s.length; // create a character array // of the length of the string var c = new Array(n); // assign the string // to character array for (var i = 0; i < n; i++) { c[i] = s[i]; } // sort the character array c.sort(); // check if the character array // is equal to the string or not for (var i = 0; i < n; i++) if (c[i] != s[i]) return false; return true; } s = \"aabbbcc\"; // check whether the string is// in alphabetical order or notif (isAlphabaticOrder(s)) document.write( \"Yes\");else document.write( \"No\"); //This code is contributed by SoumikMondal</script>", "e": 30740, "s": 29896, "text": null }, { "code": null, "e": 30744, "s": 30740, "text": "Yes" }, { "code": null, "e": 30775, "s": 30746, "text": "Time Complexity: O(N*log(N))" }, { "code": null, "e": 30817, "s": 30775, "text": "Auxiliary Space: O(N)Efficient approach: " }, { "code": null, "e": 30882, "s": 30817, "text": "Run a loop from 1 to (n-1) (where n is the length of the string)" }, { "code": null, "e": 30962, "s": 30882, "text": "Check whether the element at index ‘i’ is less than the element at index ‘i-1’." }, { "code": null, "e": 31007, "s": 30962, "text": "If yes, then print ‘In alphabetical order ‘." }, { "code": null, "e": 31052, "s": 31007, "text": "Print ‘Not in alphabetical order’ otherwise." }, { "code": null, "e": 31103, "s": 31052, "text": "Below is the implementation of the above approach " }, { "code": null, "e": 31107, "s": 31103, "text": "C++" }, { "code": null, "e": 31112, "s": 31107, "text": "Java" }, { "code": null, "e": 31121, "s": 31112, "text": "Python 3" }, { "code": null, "e": 31124, "s": 31121, "text": "C#" }, { "code": null, "e": 31128, "s": 31124, "text": "PHP" }, { "code": null, "e": 31139, "s": 31128, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function that checks whether// the string is in alphabetical// order or notbool isAlphabaticOrder(string s){ int n = s.length(); for (int i = 1; i < n; i++) { // if element at index 'i' is less // than the element at index 'i-1' // then the string is not sorted if (s[i] < s[i - 1]) return false; } return true;} // Driver codeint main(){ string s = \"aabbbcc\"; // check whether the string is // in alphabetical order or not if (isAlphabaticOrder(s)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 31806, "s": 31139, "text": null }, { "code": "// Java implementation of above approachpublic class GFG { // Function that checks whether// the string is in alphabetical// order or not static boolean isAlphabaticOrder(String s) { int n = s.length(); for (int i = 1; i < n; i++) { // if element at index 'i' is less // than the element at index 'i-1' // then the string is not sorted if (s.charAt(i) < s.charAt(i - 1)) { return false; } } return true; } // Driver code static public void main(String[] args) { String s = \"aabbbcc\"; // check whether the string is // in alphabetical order or not if (isAlphabaticOrder(s)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } }}//This code is contributed by PrinciRaj1992", "e": 32668, "s": 31806, "text": null }, { "code": "# Python 3 implementation of above approach # Function that checks whether# the string is in alphabetical# order or notdef isAlphabaticOrder(s): n = len(s) for i in range(1, n): # if element at index 'i' is less # than the element at index 'i-1' # then the string is not sorted if (s[i] < s[i - 1]) : return False return True # Driver codeif __name__ == \"__main__\": s = \"aabbbcc\" # check whether the string is # in alphabetical order or not if (isAlphabaticOrder(s)): print(\"Yes\") else: print(\"No\")", "e": 33250, "s": 32668, "text": null }, { "code": "// C# implementation of above approachusing System; public class GFG{ // Function that checks whether// the string is in alphabetical// order or notstatic bool isAlphabaticOrder(string s){ int n = s.Length; for (int i = 1; i < n; i++) { // if element at index 'i' is less // than the element at index 'i-1' // then the string is not sorted if (s[i] < s[i - 1]) return false; } return true;} // Driver code static public void Main (){ string s = \"aabbbcc\"; // check whether the string is // in alphabetical order or not if (isAlphabaticOrder(s)) Console.WriteLine (\"Yes\"); else Console.WriteLine (\"No\"); }}", "e": 33942, "s": 33250, "text": null }, { "code": "<?php// PHP implementation of above approach // Function that checks whether// the string is in alphabetical// order or notfunction isAlphabaticOrder($s){ $n = strlen($s); for ($i = 1; $i < $n; $i++) { // if element at index 'i' is less // than the element at index 'i-1' // then the string is not sorted if ($s[$i] < $s[$i - 1]) return false; } return true;} // Driver code$s = \"aabbbcc\"; // check whether the string is// in alphabetical order or notif (isAlphabaticOrder($s)) echo \"Yes\";else echo \"No\"; // This code is contributed// by Sach_Code?>", "e": 34550, "s": 33942, "text": null }, { "code": "<script>// JavaScript implementation of above approach // Function that checks whether// the string is in alphabetical// order or notfunction isAlphabaticOrder( s){ let n = s.length; for (let i = 1; i < n; i++) { // if element at index 'i' is less // than the element at index 'i-1' // then the string is not sorted if (s[i] < s[i - 1]) return false; } return true;} // Driver codelet s = \"aabbbcc\";// check whether the string is// in alphabetical order or notif (isAlphabaticOrder(s)) document.write(\"Yes\");else document.write(\"No\");</script>", "e": 35151, "s": 34550, "text": null }, { "code": null, "e": 35155, "s": 35151, "text": "Yes" }, { "code": null, "e": 35200, "s": 35157, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 35208, "s": 35200, "text": "ankthon" }, { "code": null, "e": 35223, "s": 35208, "text": "Shivi_Aggarwal" }, { "code": null, "e": 35233, "s": 35223, "text": "Sach_Code" }, { "code": null, "e": 35247, "s": 35233, "text": "princiraj1992" }, { "code": null, "e": 35264, "s": 35247, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 35270, "s": 35264, "text": "ukasp" }, { "code": null, "e": 35280, "s": 35270, "text": "subham348" }, { "code": null, "e": 35293, "s": 35280, "text": "SoumikMondal" }, { "code": null, "e": 35301, "s": 35293, "text": "rohan07" }, { "code": null, "e": 35325, "s": 35301, "text": "Competitive Programming" }, { "code": null, "e": 35333, "s": 35325, "text": "Sorting" }, { "code": null, "e": 35341, "s": 35333, "text": "Strings" }, { "code": null, "e": 35349, "s": 35341, "text": "Strings" }, { "code": null, "e": 35357, "s": 35349, "text": "Sorting" }, { "code": null, "e": 35455, "s": 35357, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35464, "s": 35455, "text": "Comments" }, { "code": null, "e": 35477, "s": 35464, "text": "Old Comments" }, { "code": null, "e": 35515, "s": 35477, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 35561, "s": 35515, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 35632, "s": 35561, "text": "Remove all occurrences of a character in a string | Recursive approach" }, { "code": null, "e": 35686, "s": 35632, "text": "String hashing using Polynomial rolling hash function" } ]
How to create our own/custom functional interface in Java?
The functional interface is a simple interface with only one abstract method. A lambda expression can be used through a functional interface in Java 8. We can declare our own/custom functional interface by defining the Single Abstract Method (SAM) in an interface. interface CustomInterface { // abtstact method } @FunctionalInterface interface CustomFunctionalInterface { void display(); } public class FunctionInterfaceLambdaTest { public static void main(String args[]) { // Using Anonymous inner class CustomFunctionalInterface test1 = new CustomFunctionalInterface() { public void display() { System.out.println("Display using Anonymous inner class"); } }; test1.display(); // Using Lambda Expression CustomFunctionalInterface test2 = () -> { // lambda expression System.out.println("Display using Lambda Expression"); }; test2.display(); } } Display using Anonymous inner class Display using Lambda Expression
[ { "code": null, "e": 1327, "s": 1062, "text": "The functional interface is a simple interface with only one abstract method. A lambda expression can be used through a functional interface in Java 8. We can declare our own/custom\nfunctional interface by defining the Single Abstract Method (SAM) in an interface." }, { "code": null, "e": 1379, "s": 1327, "text": "interface CustomInterface {\n // abtstact method\n}" }, { "code": null, "e": 2012, "s": 1379, "text": "@FunctionalInterface\ninterface CustomFunctionalInterface {\n void display();\n}\npublic class FunctionInterfaceLambdaTest {\n public static void main(String args[]) {\n // Using Anonymous inner class\n CustomFunctionalInterface test1 = new CustomFunctionalInterface() {\n public void display() {\n System.out.println(\"Display using Anonymous inner class\");\n }\n };\n test1.display();\n // Using Lambda Expression\n CustomFunctionalInterface test2 = () -> { // lambda expression\n System.out.println(\"Display using Lambda Expression\");\n };\n test2.display();\n }\n}" }, { "code": null, "e": 2080, "s": 2012, "text": "Display using Anonymous inner class\nDisplay using Lambda Expression" } ]
C++ Program to Check if a Binary Tree is a BST
Binary Search Tree is a binary tree data structure in which we have 3 properties − The left subtree of a binary search tree of a node contains only nodes with keys lesser than the node’s key. The left subtree of a binary search tree of a node contains only nodes with keys lesser than the node’s key. The right subtree of a binary search tree node contains only nodes with keys greater than the node’s key. The right subtree of a binary search tree node contains only nodes with keys greater than the node’s key. The left and right of a subtree each must also be a binary search tree. The left and right of a subtree each must also be a binary search tree. Begin function BSTUtill() If node is equals to NULL then Return 1. If data of node is less than minimum or greater than maximum data then Return 0. Traverse left and right sub-trees recursively. End. Live Demo #include <iostream> #include <cstdlib> #include <climits> using namespace std; struct n { int d; n* l; n* r; }; int BSTUtil(n* node, int min, int max); int isBST(n* node) { return(BSTUtil(node, INT_MIN, INT_MAX)); } int BSTUtil(struct n* node, int min, int max) { if (node==NULL) return 1; if (node->d < min || node->d > max) return 0; return BSTUtil(node->l, min, node->d - 1) && BSTUtil(node->r, node->d + 1, max); } n* newN(int d) { n* nod = new n; nod->d = d; nod->l = NULL; nod->r = NULL; return nod; } int main() { n *root = newN(7); root->l = newN(6); root->r = newN(10); root->l->l = newN(2); root->l->r = newN(4); if (isBST(root)) cout<<"The Given Binary Tree is a BST"<<endl; else cout<<"The Given Binary Tree is not a BST"<<endl; n *root1 = newN(10); root1->l = newN(6); root1->r = newN(11); root1->l->l = newN(2); root1->l->r = newN(7); if (isBST(root1)) cout<<"The Given Binary Tree is a BST"<<endl; else cout<<"The Given Binary Tree is not a BST"<<endl; return 0; } The Given Binary Tree is not a BST The Given Binary Tree is a BST
[ { "code": null, "e": 1145, "s": 1062, "text": "Binary Search Tree is a binary tree data structure in which we have 3 properties −" }, { "code": null, "e": 1254, "s": 1145, "text": "The left subtree of a binary search tree of a node contains only nodes with keys lesser than the node’s key." }, { "code": null, "e": 1363, "s": 1254, "text": "The left subtree of a binary search tree of a node contains only nodes with keys lesser than the node’s key." }, { "code": null, "e": 1469, "s": 1363, "text": "The right subtree of a binary search tree node contains only nodes with keys greater than the node’s key." }, { "code": null, "e": 1575, "s": 1469, "text": "The right subtree of a binary search tree node contains only nodes with keys greater than the node’s key." }, { "code": null, "e": 1647, "s": 1575, "text": "The left and right of a subtree each must also be a binary search tree." }, { "code": null, "e": 1719, "s": 1647, "text": "The left and right of a subtree each must also be a binary search tree." }, { "code": null, "e": 1965, "s": 1719, "text": "Begin\n function BSTUtill()\n If node is equals to NULL then\n Return 1.\n If data of node is less than minimum or greater than\n maximum data then\n Return 0.\n Traverse left and right sub-trees recursively. \nEnd." }, { "code": null, "e": 1976, "s": 1965, "text": " Live Demo" }, { "code": null, "e": 3106, "s": 1976, "text": "#include <iostream>\n#include <cstdlib>\n#include <climits>\nusing namespace std;\nstruct n {\n int d;\n n* l;\n n* r;\n};\nint BSTUtil(n* node, int min, int max);\nint isBST(n* node) {\n return(BSTUtil(node, INT_MIN, INT_MAX));\n}\nint BSTUtil(struct n* node, int min, int max) {\n if (node==NULL)\n return 1;\n if (node->d < min || node->d > max)\n return 0;\n return BSTUtil(node->l, min, node->d - 1) && BSTUtil(node->r, node->d + 1, max);\n}\nn* newN(int d) {\n n* nod = new n;\n nod->d = d;\n nod->l = NULL;\n nod->r = NULL;\n return nod;\n}\nint main() {\n n *root = newN(7);\n root->l = newN(6);\n root->r = newN(10);\n root->l->l = newN(2);\n root->l->r = newN(4);\n if (isBST(root))\n cout<<\"The Given Binary Tree is a BST\"<<endl;\n else\n cout<<\"The Given Binary Tree is not a BST\"<<endl;\n n *root1 = newN(10);\n root1->l = newN(6);\n root1->r = newN(11);\n root1->l->l = newN(2);\n root1->l->r = newN(7);\n if (isBST(root1))\n cout<<\"The Given Binary Tree is a BST\"<<endl;\n else\n cout<<\"The Given Binary Tree is not a BST\"<<endl;\n return 0;\n}" }, { "code": null, "e": 3172, "s": 3106, "text": "The Given Binary Tree is not a BST\nThe Given Binary Tree is a BST" } ]
Tryit Editor v3.6 - Show React
import React from 'react'; import ReactDOM from 'react-dom/client'; const myElement = <h1>React is {5 + 5} times better with JSX</h1>; const root = ReactDOM.createRoot(document.getElementById('root')); root.render(myElement); <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
[ { "code": null, "e": 231, "s": 0, "text": "\nimport React from 'react';\nimport ReactDOM from 'react-dom/client';\n\nconst myElement = <h1>React is {5 + 5} times better with JSX</h1>;\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(myElement);\n\n" } ]