title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Introduction to Yellowbrick: A Python Library to Visualize the Prediction of your Machine Learning Model | by Khuyen Tran | Towards Data Science
|
Congratulation! You have just trained a model and improved your f1-score to 98%! But what does it really mean? Will the increase in the f1 score indicate that your model is performing better?
You know f1-score is the harmonic between recall and precision, but how many of them are false among the positive predictions? And how many of them are false among the negative predictions?
If you want to hypertune your machine learning model to improve the f1-score to 99%, which category should you focus on improving to have an increase of 1%?
Gaining these insights would help you to understand your machine learning results and know which action you should take to improve the model. One of the best ways to understand machine learning is through plots. That is when Yellowbrick becomes helpful.
Yellowbrick is a machine learning visualization libary. Essentially, Yellowbrick makes it easier for you to:
Select features
Tuning hyperparameters
Interpret the score of your models
Visualize text data
Being able to analyze your data and model with plots would make it much easier for you to understand your model and figure out the next steps to increase the scores that are meaningful to your goal.
In this article, we will play with a classification problem to learn which tools yellowbrick provides that can help you interpret your classification results.
To install Yellowbrick, type
pip install yellowbrick
We will use occupancy, the experimental data used for binary classification (room occupancy) from Temperature, Humidity, Light, and CO2. Ground-truth occupancy was obtained from time stamped pictures that were taken every minute.
How correlated are for each pair of features in the data? A two-dimensional ranking of features utilizes a ranking algorithm that takes into account pairs of features at a time. We use Pearson correlation to score to detect colinear relationships.
Based on the data, humidity is strongly correlated to the relative humidity. Light is strongly correlated to the temperature. This makes sense since these features often come hand in hand with each other.
One of the biggest challenges for classification models is the imbalance of classes in training data. Our high f1-score might be not a good evaluation score for an imbalanced class because the classifier can simply guess all the majority class to get a high score.
Thus, it is important to visualize the distribution of the class. We could utilize ClassBalance to visualize the distribution of the class with a bar chart
It seems like there are a lot more data classified as unoccupied than occupied. Knowing this, we can utilize several techniques for dealing with class imbalance such as stratified sampling, weighting to get a more informative result.
Now we come back to the question: What does the f1-score of 98% really mean? Does the increase in f1-score result in more profit for your company?
Yellowbrick provides several tools you can use to visualize the results for classification problems. Some of them you might have or have not heard of, that can be extremely helpful for interpreting your model.
What is the percentage of false predictions mong the unoccupied class? What is the percentage of false predictions among the occupied class? The confusion matrix helps us to answer this question
It seems like the occupied class is with a higher percentage of wrong predictions; thus, we could try to improve the number of the right predictions in the occupied class to improve the score.
Imagine we improve our f1 score to 99%, how do we know that it is actually better? Confusion matrix could help but instead of comparing the percentage of right prediction in each class between two models, is there an easier way to compare to the performance of two models? That is when ROC AUC would be helpful.
A ROCAUC plot allows the user to visualize the tradeoff between the classifierβs sensitivity and specificity. A ROC curve displays the true positive rate on the Y axis and the false positive rate on the X axis.
The ideal point is therefore the top-left corner of the plot: false positives are zero and true positives are one. The higher the area under the curve (AUC), the better the model generally is.
Considering that our ROC curves are near the top-left corner, the performance of our model is really good. If we observe that a different model or a different hyperparameter result in ROC curves are closer to the top left corner then our current one, we can assure that the performance of our model actually improves.
Now we understand the performance of our model, how do we go about improving the model? To improve our model, we might want to
Prevent our model from underfitting or overfitting
Find the features are the most important to the estimator
We will explore the tools provided by Yellowbrick to help us figure out how to improve our model
A model can have many hyperparameters. We might select the hyperparameters that accurately predict the training data. The good way to find the best hyperparameters is to choose a combination of those parameters with a grid search.
But how do we know that those hyperparameters will also accurately predict the test data? It is useful to plot the influence of a single hyperparameter on the training and test data to determine if the estimator is underfitting or overfitting for some hyperparameter values.
Validation Curve could help us to find the sweet spot where lower or higher value than this hyperparameter will result in underfitting or overfitting the data
As we can see from the plot, while the higher number of max depth results in the higher training score, but it also results in the lower cross-validation score. This makes sense since decision trees become more overfitting the deeper they are.
Thus, the sweet spot will be where the cross-validation score does not decrease, which is 1.
Will more data result in a better performance of the model? Not always, the estimator may be more sensitive to error due to variance. That is when the learning curve is helpful.
A learning curve shows the relationship of the training score versus the cross-validated test score for an estimator with a varying number of training samples.
From the graph, we can see that the number of training instances of around 8700 results in the best f1-score. The higher number of training instances results in a lower f1-score.
Having more features is not always equivalent to a better model. The more features the model has, the more sensitive the model is to errors due to variance. Thus, we want to select the minimum required features to produce a valid model.
A common approach to eliminate features is to eliminate the ones that are the least important to the model. Then we re-evaluate if the model actually performs better during cross-validation.
Feature importance is perfect for this task since it helps us to visualize the relative importance of the features for the model.
It seems like the light is the most important feature to DecisionTreeClassifier, followed by CO2, temperature.
Considering there are not many features in our data, we will not eliminate humidity. But if there are many features in our model, we should eliminate the ones that are not important to the model to prevent errors due to variance.
Congratulations! You have just learned how to create plots that help you to interpret the results of your model. Being able to understand your machine learning results will make it easier for you to find out the next steps to improve its performance. There are more functionalities of Yellowbrick than what I mention here. To learn more about how to use Yellowbrick to interpret your machine learning model, I encourage you to check the doc here.
The source code of this repo could be found here.
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
|
[
{
"code": null,
"e": 363,
"s": 171,
"text": "Congratulation! You have just trained a model and improved your f1-score to 98%! But what does it really mean? Will the increase in the f1 score indicate that your model is performing better?"
},
{
"code": null,
"e": 553,
"s": 363,
"text": "You know f1-score is the harmonic between recall and precision, but how many of them are false among the positive predictions? And how many of them are false among the negative predictions?"
},
{
"code": null,
"e": 710,
"s": 553,
"text": "If you want to hypertune your machine learning model to improve the f1-score to 99%, which category should you focus on improving to have an increase of 1%?"
},
{
"code": null,
"e": 964,
"s": 710,
"text": "Gaining these insights would help you to understand your machine learning results and know which action you should take to improve the model. One of the best ways to understand machine learning is through plots. That is when Yellowbrick becomes helpful."
},
{
"code": null,
"e": 1073,
"s": 964,
"text": "Yellowbrick is a machine learning visualization libary. Essentially, Yellowbrick makes it easier for you to:"
},
{
"code": null,
"e": 1089,
"s": 1073,
"text": "Select features"
},
{
"code": null,
"e": 1112,
"s": 1089,
"text": "Tuning hyperparameters"
},
{
"code": null,
"e": 1147,
"s": 1112,
"text": "Interpret the score of your models"
},
{
"code": null,
"e": 1167,
"s": 1147,
"text": "Visualize text data"
},
{
"code": null,
"e": 1366,
"s": 1167,
"text": "Being able to analyze your data and model with plots would make it much easier for you to understand your model and figure out the next steps to increase the scores that are meaningful to your goal."
},
{
"code": null,
"e": 1525,
"s": 1366,
"text": "In this article, we will play with a classification problem to learn which tools yellowbrick provides that can help you interpret your classification results."
},
{
"code": null,
"e": 1554,
"s": 1525,
"text": "To install Yellowbrick, type"
},
{
"code": null,
"e": 1578,
"s": 1554,
"text": "pip install yellowbrick"
},
{
"code": null,
"e": 1808,
"s": 1578,
"text": "We will use occupancy, the experimental data used for binary classification (room occupancy) from Temperature, Humidity, Light, and CO2. Ground-truth occupancy was obtained from time stamped pictures that were taken every minute."
},
{
"code": null,
"e": 2056,
"s": 1808,
"text": "How correlated are for each pair of features in the data? A two-dimensional ranking of features utilizes a ranking algorithm that takes into account pairs of features at a time. We use Pearson correlation to score to detect colinear relationships."
},
{
"code": null,
"e": 2261,
"s": 2056,
"text": "Based on the data, humidity is strongly correlated to the relative humidity. Light is strongly correlated to the temperature. This makes sense since these features often come hand in hand with each other."
},
{
"code": null,
"e": 2526,
"s": 2261,
"text": "One of the biggest challenges for classification models is the imbalance of classes in training data. Our high f1-score might be not a good evaluation score for an imbalanced class because the classifier can simply guess all the majority class to get a high score."
},
{
"code": null,
"e": 2682,
"s": 2526,
"text": "Thus, it is important to visualize the distribution of the class. We could utilize ClassBalance to visualize the distribution of the class with a bar chart"
},
{
"code": null,
"e": 2916,
"s": 2682,
"text": "It seems like there are a lot more data classified as unoccupied than occupied. Knowing this, we can utilize several techniques for dealing with class imbalance such as stratified sampling, weighting to get a more informative result."
},
{
"code": null,
"e": 3063,
"s": 2916,
"text": "Now we come back to the question: What does the f1-score of 98% really mean? Does the increase in f1-score result in more profit for your company?"
},
{
"code": null,
"e": 3273,
"s": 3063,
"text": "Yellowbrick provides several tools you can use to visualize the results for classification problems. Some of them you might have or have not heard of, that can be extremely helpful for interpreting your model."
},
{
"code": null,
"e": 3468,
"s": 3273,
"text": "What is the percentage of false predictions mong the unoccupied class? What is the percentage of false predictions among the occupied class? The confusion matrix helps us to answer this question"
},
{
"code": null,
"e": 3661,
"s": 3468,
"text": "It seems like the occupied class is with a higher percentage of wrong predictions; thus, we could try to improve the number of the right predictions in the occupied class to improve the score."
},
{
"code": null,
"e": 3973,
"s": 3661,
"text": "Imagine we improve our f1 score to 99%, how do we know that it is actually better? Confusion matrix could help but instead of comparing the percentage of right prediction in each class between two models, is there an easier way to compare to the performance of two models? That is when ROC AUC would be helpful."
},
{
"code": null,
"e": 4184,
"s": 3973,
"text": "A ROCAUC plot allows the user to visualize the tradeoff between the classifierβs sensitivity and specificity. A ROC curve displays the true positive rate on the Y axis and the false positive rate on the X axis."
},
{
"code": null,
"e": 4377,
"s": 4184,
"text": "The ideal point is therefore the top-left corner of the plot: false positives are zero and true positives are one. The higher the area under the curve (AUC), the better the model generally is."
},
{
"code": null,
"e": 4695,
"s": 4377,
"text": "Considering that our ROC curves are near the top-left corner, the performance of our model is really good. If we observe that a different model or a different hyperparameter result in ROC curves are closer to the top left corner then our current one, we can assure that the performance of our model actually improves."
},
{
"code": null,
"e": 4822,
"s": 4695,
"text": "Now we understand the performance of our model, how do we go about improving the model? To improve our model, we might want to"
},
{
"code": null,
"e": 4873,
"s": 4822,
"text": "Prevent our model from underfitting or overfitting"
},
{
"code": null,
"e": 4931,
"s": 4873,
"text": "Find the features are the most important to the estimator"
},
{
"code": null,
"e": 5028,
"s": 4931,
"text": "We will explore the tools provided by Yellowbrick to help us figure out how to improve our model"
},
{
"code": null,
"e": 5259,
"s": 5028,
"text": "A model can have many hyperparameters. We might select the hyperparameters that accurately predict the training data. The good way to find the best hyperparameters is to choose a combination of those parameters with a grid search."
},
{
"code": null,
"e": 5534,
"s": 5259,
"text": "But how do we know that those hyperparameters will also accurately predict the test data? It is useful to plot the influence of a single hyperparameter on the training and test data to determine if the estimator is underfitting or overfitting for some hyperparameter values."
},
{
"code": null,
"e": 5693,
"s": 5534,
"text": "Validation Curve could help us to find the sweet spot where lower or higher value than this hyperparameter will result in underfitting or overfitting the data"
},
{
"code": null,
"e": 5937,
"s": 5693,
"text": "As we can see from the plot, while the higher number of max depth results in the higher training score, but it also results in the lower cross-validation score. This makes sense since decision trees become more overfitting the deeper they are."
},
{
"code": null,
"e": 6030,
"s": 5937,
"text": "Thus, the sweet spot will be where the cross-validation score does not decrease, which is 1."
},
{
"code": null,
"e": 6208,
"s": 6030,
"text": "Will more data result in a better performance of the model? Not always, the estimator may be more sensitive to error due to variance. That is when the learning curve is helpful."
},
{
"code": null,
"e": 6368,
"s": 6208,
"text": "A learning curve shows the relationship of the training score versus the cross-validated test score for an estimator with a varying number of training samples."
},
{
"code": null,
"e": 6547,
"s": 6368,
"text": "From the graph, we can see that the number of training instances of around 8700 results in the best f1-score. The higher number of training instances results in a lower f1-score."
},
{
"code": null,
"e": 6784,
"s": 6547,
"text": "Having more features is not always equivalent to a better model. The more features the model has, the more sensitive the model is to errors due to variance. Thus, we want to select the minimum required features to produce a valid model."
},
{
"code": null,
"e": 6975,
"s": 6784,
"text": "A common approach to eliminate features is to eliminate the ones that are the least important to the model. Then we re-evaluate if the model actually performs better during cross-validation."
},
{
"code": null,
"e": 7105,
"s": 6975,
"text": "Feature importance is perfect for this task since it helps us to visualize the relative importance of the features for the model."
},
{
"code": null,
"e": 7216,
"s": 7105,
"text": "It seems like the light is the most important feature to DecisionTreeClassifier, followed by CO2, temperature."
},
{
"code": null,
"e": 7446,
"s": 7216,
"text": "Considering there are not many features in our data, we will not eliminate humidity. But if there are many features in our model, we should eliminate the ones that are not important to the model to prevent errors due to variance."
},
{
"code": null,
"e": 7893,
"s": 7446,
"text": "Congratulations! You have just learned how to create plots that help you to interpret the results of your model. Being able to understand your machine learning results will make it easier for you to find out the next steps to improve its performance. There are more functionalities of Yellowbrick than what I mention here. To learn more about how to use Yellowbrick to interpret your machine learning model, I encourage you to check the doc here."
},
{
"code": null,
"e": 7943,
"s": 7893,
"text": "The source code of this repo could be found here."
},
{
"code": null,
"e": 8103,
"s": 7943,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
}
] |
Airplanes Detection for Satellite using Faster RCNN | by Shubhankar Rawat | Towards Data Science
|
Object detection is a computer technology related to computer vision and image processing that deals with detecting instances of semantic objects of a certain class (such as humans, buildings, or cars) in digital images and videos.
Object detection is one of those fields that have witnessed great success.It is used in many areas like face detection(used by Facebook to recognize people), tumor detection(used in medical fields), etc.
Ever since the inception of deep learning in computer vision, tasks like object detection have become comparatively easier and efficient.The deep learning models provide better accuracy, less time consumption, less complexity, overall better performance than the earlier computer vision approaches.Deep learning provided outstanding results over the traditional computer vision methods for object detection, leading to the wide use of deep learning models.
One of the best performing object detection(deep learning) algorithms include :1. RCNN (Region-based Convolution Neural Network)2. Fast RCNN3. Faster RCNN4. SSD (Single Shot Multibox Detector)5. YOLO (You Look Only Once)
In this article, I will be using Faster RCNN(FRCNN) to demonstrate the eminent use of object detection.
The dataset is taken from kaggle, you can find it hereIt contains 400 training images and 100 test images. The bounding boxes are saved in both XML and CSV files.
The dataset contains computer-generated satellite images of planes.
As you can see from the dataset, some images do not contain highly differentiable objects(airplanes) from the background, i.e., the airplanes are somewhat similar to the background in terms of color, texture, and appearance. For example, consider the following image :
How many airplanes can you see??Can you even see an airplane???!!Well, this is an image from the training set and you can see how it is really hard to figure out the airplanes in the image(even for a human).
Here is the image by the way, with the bounding boxes, showing that there were 2 airplanes. (Did you figure it out??)
But will there be an effect on the model performance due to such images where it is hard to distinguish between background and object?If you have a strong computer vision background, then you must be knowing that initial approaches for object detection first converted the image to grayscale then looked for edges or gradient changes ... All this stuff would be highly affected by the appearance of the object in the image. If the image and the object were quite similar(like in the above image) then these approaches will fail. This condition is called clutter, where it becomes difficult to distinguish between the object and the background.But will it affect the deep learning models as well???What these neural nets are searching for is how they can distinguish the object from the background(recognition), so that they can enclose them in a bounding box(localization). These are called features that are responsible for object detection.Such features are hard to find if there is less variation between the object and the background.So, this dataset is a good example, for testing the performance of deep learning model-FRCNN.
You can find the python code for this problem here
To begin with, 400 images is no place to be. For deep learning models to perform at their best we need loads of data.
It is a well-known fact that the performance of deep learning models is proportional to the amount of training data. More the data, the better the performance.Models like FRCNN require huge amounts of training data to produce good results. However, there are very few (if not none) datasets for object detection which have ample training data.In this dataset also we have only 400 images, which are not enough to produce good results.So, to tackle this data augmentation comes to rescue.Again this dataset is a good example to demonstrate how data augmentation is essential for deep learning models to produce good results.
Data augmentation is a technique to artificially create new training data from existing training data.If you have been working with deep learning models for computer vision(be it image classification or localization or detection etc) then you must have encountered the term data augmentation, and realize the importance of it.
Data augmentation generates new images for training and hence improving the model performance.Why does data augmentation work?? Modern deep learning algorithms, such as the convolutional neural network, or CNN, can learn features that are invariant to their location in the image. Nevertheless, augmentation can further aid in this transform invariant approach to learning and can aid the model in learning features that are also invariant to transforms such as left-to-right to top-to-bottom ordering, light levels in photographs, and more.
There are various data augmentation techniques, the following are used in this approach :1. Horizontal flip2. Scaling3. Translation4. Rotation 5. Shearing6. Various combinations of above
Data augmentation is different for object detection when compared to image classification. In image classification, you only need to change the image accordingly, but in object detection, you need to change and adjust the bounding boxes as well. For example, if you are flipping the image horizontally then you also need to flip the bounding boxes.
Keeping the bounding box constraint in mind I implemented data augmentation and produced 4400 images in total.Still not a high number of images but because there are only 100 images to test for and only one class to detect, these many will do.But I highly recommend increasing the training data as high as possible without creating unnecessary data(which often happens during data augmentation).
Now that we have some data to train on, letβs implement the model.
I recommend you to download the code files from the GitHub repository mentioned above, to make the best of this article.
Faster RCNN is a great deep learning model that performs extremely well, which we are about to figure out.
First things first, organizing the data.The training set images were moved to a folder named train_images and the test set images were moved to folder test_images.An empty folder results _imgs was created, this folder will contain all the output images with the bounding boxes.
All the required libraries and packages were installed by executing the following line in the command prompt(with the current folder as the working directory):
pip install -r requirements.txt
Annotate file(annotate.txt) was created, which looks like :
It contains the folder name of the train set images, with the image name and the bounding box coordinates and the class of the object.Note that the bounding box coordinates have the order: xmin, ymin, xmax, and ymax.
The entries in the annotate file will vary depending upon how the data augmentation is implemented.
The model was run by executing the following line in the command prompt :
python train_frcnn.py -o simple -p annotate.txt
I have run the code for 800 epochs with 20 iterations per epoch, one can change these numbers for better accuracy, like increasing the number of epochs.
It is highly recommended to use GPU for running the above code as training can take a lot of time, especially for a high number of epochs.
After the training has completed, it is time to test the model.To get the output images, the following command was executed :
python test_frcnn.py -p test_images
As the command is executed one can see output images with the bounding boxes being saved in the results_imgs folder.
Here are some of the results I attained :
The above images show how FRCNN excels in its task of object detection.The model performance can be enhanced by generating more quality images using data augmentation and increasing the number of epochs.
Now, let us look at the results obtained when no data augmentation is done, keeping the number of epochs and iterations the same.
As one can see that the results are not as good as the previous ones, where data augmentation was implemented. The model fails to identify the airplanes correctly rather identifies non-airplane objects as airplanes. That is, the number of false positives and false negatives is high.
This shows how data augmentation helps in reducing the error and increasing the performance of the deep learning models.
Object detection is a great field to explore.I have seen many object detection models used in various places like for self-driving cars, mobile phones, security, etc but using it for satellites was somewhat new to me.
Also, Faster RCNN lives up to its name and produces great results.
My sole purpose in this article was to share the use of Faster RCNN and not how to implement it, so if you face any errors running the above code or any doubts, feel free to ask in the comment section.
|
[
{
"code": null,
"e": 404,
"s": 172,
"text": "Object detection is a computer technology related to computer vision and image processing that deals with detecting instances of semantic objects of a certain class (such as humans, buildings, or cars) in digital images and videos."
},
{
"code": null,
"e": 608,
"s": 404,
"text": "Object detection is one of those fields that have witnessed great success.It is used in many areas like face detection(used by Facebook to recognize people), tumor detection(used in medical fields), etc."
},
{
"code": null,
"e": 1065,
"s": 608,
"text": "Ever since the inception of deep learning in computer vision, tasks like object detection have become comparatively easier and efficient.The deep learning models provide better accuracy, less time consumption, less complexity, overall better performance than the earlier computer vision approaches.Deep learning provided outstanding results over the traditional computer vision methods for object detection, leading to the wide use of deep learning models."
},
{
"code": null,
"e": 1286,
"s": 1065,
"text": "One of the best performing object detection(deep learning) algorithms include :1. RCNN (Region-based Convolution Neural Network)2. Fast RCNN3. Faster RCNN4. SSD (Single Shot Multibox Detector)5. YOLO (You Look Only Once)"
},
{
"code": null,
"e": 1390,
"s": 1286,
"text": "In this article, I will be using Faster RCNN(FRCNN) to demonstrate the eminent use of object detection."
},
{
"code": null,
"e": 1553,
"s": 1390,
"text": "The dataset is taken from kaggle, you can find it hereIt contains 400 training images and 100 test images. The bounding boxes are saved in both XML and CSV files."
},
{
"code": null,
"e": 1621,
"s": 1553,
"text": "The dataset contains computer-generated satellite images of planes."
},
{
"code": null,
"e": 1890,
"s": 1621,
"text": "As you can see from the dataset, some images do not contain highly differentiable objects(airplanes) from the background, i.e., the airplanes are somewhat similar to the background in terms of color, texture, and appearance. For example, consider the following image :"
},
{
"code": null,
"e": 2098,
"s": 1890,
"text": "How many airplanes can you see??Can you even see an airplane???!!Well, this is an image from the training set and you can see how it is really hard to figure out the airplanes in the image(even for a human)."
},
{
"code": null,
"e": 2216,
"s": 2098,
"text": "Here is the image by the way, with the bounding boxes, showing that there were 2 airplanes. (Did you figure it out??)"
},
{
"code": null,
"e": 3348,
"s": 2216,
"text": "But will there be an effect on the model performance due to such images where it is hard to distinguish between background and object?If you have a strong computer vision background, then you must be knowing that initial approaches for object detection first converted the image to grayscale then looked for edges or gradient changes ... All this stuff would be highly affected by the appearance of the object in the image. If the image and the object were quite similar(like in the above image) then these approaches will fail. This condition is called clutter, where it becomes difficult to distinguish between the object and the background.But will it affect the deep learning models as well???What these neural nets are searching for is how they can distinguish the object from the background(recognition), so that they can enclose them in a bounding box(localization). These are called features that are responsible for object detection.Such features are hard to find if there is less variation between the object and the background.So, this dataset is a good example, for testing the performance of deep learning model-FRCNN."
},
{
"code": null,
"e": 3399,
"s": 3348,
"text": "You can find the python code for this problem here"
},
{
"code": null,
"e": 3517,
"s": 3399,
"text": "To begin with, 400 images is no place to be. For deep learning models to perform at their best we need loads of data."
},
{
"code": null,
"e": 4141,
"s": 3517,
"text": "It is a well-known fact that the performance of deep learning models is proportional to the amount of training data. More the data, the better the performance.Models like FRCNN require huge amounts of training data to produce good results. However, there are very few (if not none) datasets for object detection which have ample training data.In this dataset also we have only 400 images, which are not enough to produce good results.So, to tackle this data augmentation comes to rescue.Again this dataset is a good example to demonstrate how data augmentation is essential for deep learning models to produce good results."
},
{
"code": null,
"e": 4468,
"s": 4141,
"text": "Data augmentation is a technique to artificially create new training data from existing training data.If you have been working with deep learning models for computer vision(be it image classification or localization or detection etc) then you must have encountered the term data augmentation, and realize the importance of it."
},
{
"code": null,
"e": 5010,
"s": 4468,
"text": "Data augmentation generates new images for training and hence improving the model performance.Why does data augmentation work?? Modern deep learning algorithms, such as the convolutional neural network, or CNN, can learn features that are invariant to their location in the image. Nevertheless, augmentation can further aid in this transform invariant approach to learning and can aid the model in learning features that are also invariant to transforms such as left-to-right to top-to-bottom ordering, light levels in photographs, and more."
},
{
"code": null,
"e": 5197,
"s": 5010,
"text": "There are various data augmentation techniques, the following are used in this approach :1. Horizontal flip2. Scaling3. Translation4. Rotation 5. Shearing6. Various combinations of above"
},
{
"code": null,
"e": 5546,
"s": 5197,
"text": "Data augmentation is different for object detection when compared to image classification. In image classification, you only need to change the image accordingly, but in object detection, you need to change and adjust the bounding boxes as well. For example, if you are flipping the image horizontally then you also need to flip the bounding boxes."
},
{
"code": null,
"e": 5942,
"s": 5546,
"text": "Keeping the bounding box constraint in mind I implemented data augmentation and produced 4400 images in total.Still not a high number of images but because there are only 100 images to test for and only one class to detect, these many will do.But I highly recommend increasing the training data as high as possible without creating unnecessary data(which often happens during data augmentation)."
},
{
"code": null,
"e": 6009,
"s": 5942,
"text": "Now that we have some data to train on, letβs implement the model."
},
{
"code": null,
"e": 6130,
"s": 6009,
"text": "I recommend you to download the code files from the GitHub repository mentioned above, to make the best of this article."
},
{
"code": null,
"e": 6237,
"s": 6130,
"text": "Faster RCNN is a great deep learning model that performs extremely well, which we are about to figure out."
},
{
"code": null,
"e": 6515,
"s": 6237,
"text": "First things first, organizing the data.The training set images were moved to a folder named train_images and the test set images were moved to folder test_images.An empty folder results _imgs was created, this folder will contain all the output images with the bounding boxes."
},
{
"code": null,
"e": 6675,
"s": 6515,
"text": "All the required libraries and packages were installed by executing the following line in the command prompt(with the current folder as the working directory):"
},
{
"code": null,
"e": 6707,
"s": 6675,
"text": "pip install -r requirements.txt"
},
{
"code": null,
"e": 6767,
"s": 6707,
"text": "Annotate file(annotate.txt) was created, which looks like :"
},
{
"code": null,
"e": 6984,
"s": 6767,
"text": "It contains the folder name of the train set images, with the image name and the bounding box coordinates and the class of the object.Note that the bounding box coordinates have the order: xmin, ymin, xmax, and ymax."
},
{
"code": null,
"e": 7084,
"s": 6984,
"text": "The entries in the annotate file will vary depending upon how the data augmentation is implemented."
},
{
"code": null,
"e": 7158,
"s": 7084,
"text": "The model was run by executing the following line in the command prompt :"
},
{
"code": null,
"e": 7206,
"s": 7158,
"text": "python train_frcnn.py -o simple -p annotate.txt"
},
{
"code": null,
"e": 7359,
"s": 7206,
"text": "I have run the code for 800 epochs with 20 iterations per epoch, one can change these numbers for better accuracy, like increasing the number of epochs."
},
{
"code": null,
"e": 7498,
"s": 7359,
"text": "It is highly recommended to use GPU for running the above code as training can take a lot of time, especially for a high number of epochs."
},
{
"code": null,
"e": 7624,
"s": 7498,
"text": "After the training has completed, it is time to test the model.To get the output images, the following command was executed :"
},
{
"code": null,
"e": 7660,
"s": 7624,
"text": "python test_frcnn.py -p test_images"
},
{
"code": null,
"e": 7777,
"s": 7660,
"text": "As the command is executed one can see output images with the bounding boxes being saved in the results_imgs folder."
},
{
"code": null,
"e": 7819,
"s": 7777,
"text": "Here are some of the results I attained :"
},
{
"code": null,
"e": 8023,
"s": 7819,
"text": "The above images show how FRCNN excels in its task of object detection.The model performance can be enhanced by generating more quality images using data augmentation and increasing the number of epochs."
},
{
"code": null,
"e": 8153,
"s": 8023,
"text": "Now, let us look at the results obtained when no data augmentation is done, keeping the number of epochs and iterations the same."
},
{
"code": null,
"e": 8437,
"s": 8153,
"text": "As one can see that the results are not as good as the previous ones, where data augmentation was implemented. The model fails to identify the airplanes correctly rather identifies non-airplane objects as airplanes. That is, the number of false positives and false negatives is high."
},
{
"code": null,
"e": 8558,
"s": 8437,
"text": "This shows how data augmentation helps in reducing the error and increasing the performance of the deep learning models."
},
{
"code": null,
"e": 8776,
"s": 8558,
"text": "Object detection is a great field to explore.I have seen many object detection models used in various places like for self-driving cars, mobile phones, security, etc but using it for satellites was somewhat new to me."
},
{
"code": null,
"e": 8843,
"s": 8776,
"text": "Also, Faster RCNN lives up to its name and produces great results."
}
] |
Grouped, stacked and percent stacked barplot in ggplot2 - GeeksforGeeks
|
01 Apr, 2021
The ggplot is a library used for generating graphs in R language. We provide the data and specify the aesthetics as to how the specified data should be mapped. It is a very powerful library and widely used to generate comprehensive graphs and plots. It is used for creating graphics based on the βGrammar of Graphicsβ.
A Bar Plot or Bar Chart is a Data Visualization tool that is widely used to represent the relationship between a numeric and a categorical variable. The numeric variable is generally plotted on the Y-axis and the categorical variable on the horizontal X-axis. The height of the bars represents the corresponding numeric value of the categorical value. The above-mentioned come in handy when we have more than one categorical variable and a numeric variable.
In this article, we will be seeing how we can plot 3 different types of Bar Plots. These 3 different types of Bar Plots are :
Grouped Bar Plot
Stacked Bar Plot
Percent Stacked Bar Plot
The only difference in the codes of the 3 plots is the value of the βpositionβ parameter in the geom_bar() function of the ggplot library. Given below is implementation of the same.
Example :
R
# importing the ggplot2 librarylibrary(ggplot2) # creating the cities column# c() is used to combine vectors# rep() is used for replication of valuescities <- c(rep("Delhi", 3), rep("Mumbai", 3), rep("Chennai", 3), rep("Bengaluru", 3)) # creating the humidity column# contains 3 classes humidity <- rep(c("High", "Medium", "Low"), 4) # creating the temperature column# abs() is used for getting the absolute value# rnorm() is used for generating random variates# in a normal distribution# rnorm(number of samples, mean, SD)temperature <- abs(rnorm(12, 25, 10)) # dataframe consisting of the three columnsdataframe <- data.frame(cities, humidity, temperature) # calling the dataframedataframe
Grouped Bar Plots or Clustered Bar Plots are used to extend the functionalities of a single variate or single category bar plot to a multi variate bar plot. In these plots, the bars are grouped according to their categories and the colors are the differentiating factor to represent the other categorical variable. The bars are positioned catering to one group or the primary group and the colors represent the secondary category. For grouped bar plots, the value of position parameter is specified as βdodgeβ.
Approach:
Import module
Create dataframe
Plot graph with required functions
Set position parameter to dodge in geom_bar( ) function
Display plot
Syntax :
geom_bar(position = βdodgeβ , ....)
Example:
R
# importing the ggplot2 librarylibrary(ggplot2) # creating data framecities <- c(rep("Delhi", 3), rep("Mumbai", 3), rep("Chennai", 3), rep("Bengaluru", 3)) humidity <- rep(c("High", "Medium", "Low"), 4) temperature <- abs(rnorm(12, 25, 10)) dataframe <- data.frame(cities, humidity, temperature) # calling the dataframedataframe # plotting the graphggplot(dataframe, aes(fill = humidity, y = temperature, x = cities))+geom_bar(position = "dodge", stat = "identity")+ggtitle("Weather Data of 4 Cities !")+theme(plot.title = element_text(hjust = 0.5))
Output:
Grouped Bar Plot for the Weather Data Set
Stacked Bar Plots or Stacked Bar Graphs are an extension of the standard Bar Plots wherein we can represent two categorical variables with the help of a single Bar Plot. In these plots, the bars of the primary categorical variable determine the position and the varying levels of the secondary categorical variable which are differentiated on the basis of their colors are stacked on top of each other. For stacked bar plots, value of the position parameter is specified as βstackβ.
Approach:
Import module
Create dataframe
Plot graph with required functions
Set position parameter to stack in geom_bar( ) function
Display plot
Syntax :
geom_bar(position = βstackβ , ...)
Example:
R
# importing the ggplot2 librarylibrary(ggplot2) # creating data framecities <- c(rep("Delhi", 3), rep("Mumbai", 3), rep("Chennai", 3), rep("Bengaluru", 3)) humidity <- rep(c("High", "Medium", "Low"), 4) temperature <- abs(rnorm(12, 25, 10)) dataframe <- data.frame(cities, humidity, temperature) # calling the dataframedataframe # plotting graphggplot(dataframe, aes(fill = humidity, y = temperature, x = cities))+geom_bar(position = "stack", stat = "identity")+ggtitle("Weather Data of 4 Cities !")+theme(plot.title = element_text(hjust = 0.5))
Output:
Stacked Bar Plot of the Weather Data Set
The Percent Stacked Bar Plots are used to visualize the contribution or proportion of each categorical variable in while cumulatively taking the primary categorical variable. The entire bar is filled to the top and the different groups occupy the heights corresponding to their proportion in the bar. To map a percent stacked bar plot, the value of the position parameter is specified as βfillβ.
Approach:
Import module
Create dataframe
Plot graph with required functions
Set position parameter to fill in geom_bar( ) function
Display plot
Syntax :
geom_bar(position = βfillβ , ....)
Example:
R
# importing the ggplot2 librarylibrary(ggplot2) # creating data framecities <- c(rep("Delhi", 3), rep("Mumbai", 3), rep("Chennai", 3), rep("Bengaluru", 3)) humidity <- rep(c("High", "Medium", "Low"), 4) temperature <- abs(rnorm(12, 25, 10)) dataframe <- data.frame(cities, humidity, temperature) # calling the dataframedataframe # plotting graphggplot(dataframe, aes(fill = humidity, y = temperature, x = cities))+geom_bar(position = "fill", stat = "identity")+ggtitle("Weather Data of 4 Cities !")+theme(plot.title = element_text(hjust = 0.5))
Output :
Percent Stacked Bar Plot of Weather Data Set
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Time Series Analysis in R
R - if statement
|
[
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n01 Apr, 2021"
},
{
"code": null,
"e": 25561,
"s": 25242,
"text": "The ggplot is a library used for generating graphs in R language. We provide the data and specify the aesthetics as to how the specified data should be mapped. It is a very powerful library and widely used to generate comprehensive graphs and plots. It is used for creating graphics based on the βGrammar of Graphicsβ."
},
{
"code": null,
"e": 26019,
"s": 25561,
"text": "A Bar Plot or Bar Chart is a Data Visualization tool that is widely used to represent the relationship between a numeric and a categorical variable. The numeric variable is generally plotted on the Y-axis and the categorical variable on the horizontal X-axis. The height of the bars represents the corresponding numeric value of the categorical value. The above-mentioned come in handy when we have more than one categorical variable and a numeric variable."
},
{
"code": null,
"e": 26145,
"s": 26019,
"text": "In this article, we will be seeing how we can plot 3 different types of Bar Plots. These 3 different types of Bar Plots are :"
},
{
"code": null,
"e": 26162,
"s": 26145,
"text": "Grouped Bar Plot"
},
{
"code": null,
"e": 26179,
"s": 26162,
"text": "Stacked Bar Plot"
},
{
"code": null,
"e": 26204,
"s": 26179,
"text": "Percent Stacked Bar Plot"
},
{
"code": null,
"e": 26386,
"s": 26204,
"text": "The only difference in the codes of the 3 plots is the value of the βpositionβ parameter in the geom_bar() function of the ggplot library. Given below is implementation of the same."
},
{
"code": null,
"e": 26396,
"s": 26386,
"text": "Example :"
},
{
"code": null,
"e": 26398,
"s": 26396,
"text": "R"
},
{
"code": "# importing the ggplot2 librarylibrary(ggplot2) # creating the cities column# c() is used to combine vectors# rep() is used for replication of valuescities <- c(rep(\"Delhi\", 3), rep(\"Mumbai\", 3), rep(\"Chennai\", 3), rep(\"Bengaluru\", 3)) # creating the humidity column# contains 3 classes humidity <- rep(c(\"High\", \"Medium\", \"Low\"), 4) # creating the temperature column# abs() is used for getting the absolute value# rnorm() is used for generating random variates# in a normal distribution# rnorm(number of samples, mean, SD)temperature <- abs(rnorm(12, 25, 10)) # dataframe consisting of the three columnsdataframe <- data.frame(cities, humidity, temperature) # calling the dataframedataframe",
"e": 27129,
"s": 26398,
"text": null
},
{
"code": null,
"e": 27640,
"s": 27129,
"text": "Grouped Bar Plots or Clustered Bar Plots are used to extend the functionalities of a single variate or single category bar plot to a multi variate bar plot. In these plots, the bars are grouped according to their categories and the colors are the differentiating factor to represent the other categorical variable. The bars are positioned catering to one group or the primary group and the colors represent the secondary category. For grouped bar plots, the value of position parameter is specified as βdodgeβ."
},
{
"code": null,
"e": 27650,
"s": 27640,
"text": "Approach:"
},
{
"code": null,
"e": 27664,
"s": 27650,
"text": "Import module"
},
{
"code": null,
"e": 27681,
"s": 27664,
"text": "Create dataframe"
},
{
"code": null,
"e": 27716,
"s": 27681,
"text": "Plot graph with required functions"
},
{
"code": null,
"e": 27772,
"s": 27716,
"text": "Set position parameter to dodge in geom_bar( ) function"
},
{
"code": null,
"e": 27785,
"s": 27772,
"text": "Display plot"
},
{
"code": null,
"e": 27794,
"s": 27785,
"text": "Syntax :"
},
{
"code": null,
"e": 27830,
"s": 27794,
"text": "geom_bar(position = βdodgeβ , ....)"
},
{
"code": null,
"e": 27839,
"s": 27830,
"text": "Example:"
},
{
"code": null,
"e": 27841,
"s": 27839,
"text": "R"
},
{
"code": "# importing the ggplot2 librarylibrary(ggplot2) # creating data framecities <- c(rep(\"Delhi\", 3), rep(\"Mumbai\", 3), rep(\"Chennai\", 3), rep(\"Bengaluru\", 3)) humidity <- rep(c(\"High\", \"Medium\", \"Low\"), 4) temperature <- abs(rnorm(12, 25, 10)) dataframe <- data.frame(cities, humidity, temperature) # calling the dataframedataframe # plotting the graphggplot(dataframe, aes(fill = humidity, y = temperature, x = cities))+geom_bar(position = \"dodge\", stat = \"identity\")+ggtitle(\"Weather Data of 4 Cities !\")+theme(plot.title = element_text(hjust = 0.5))",
"e": 28453,
"s": 27841,
"text": null
},
{
"code": null,
"e": 28461,
"s": 28453,
"text": "Output:"
},
{
"code": null,
"e": 28504,
"s": 28461,
"text": "Grouped Bar Plot for the Weather Data Set "
},
{
"code": null,
"e": 28987,
"s": 28504,
"text": "Stacked Bar Plots or Stacked Bar Graphs are an extension of the standard Bar Plots wherein we can represent two categorical variables with the help of a single Bar Plot. In these plots, the bars of the primary categorical variable determine the position and the varying levels of the secondary categorical variable which are differentiated on the basis of their colors are stacked on top of each other. For stacked bar plots, value of the position parameter is specified as βstackβ."
},
{
"code": null,
"e": 28997,
"s": 28987,
"text": "Approach:"
},
{
"code": null,
"e": 29011,
"s": 28997,
"text": "Import module"
},
{
"code": null,
"e": 29028,
"s": 29011,
"text": "Create dataframe"
},
{
"code": null,
"e": 29063,
"s": 29028,
"text": "Plot graph with required functions"
},
{
"code": null,
"e": 29119,
"s": 29063,
"text": "Set position parameter to stack in geom_bar( ) function"
},
{
"code": null,
"e": 29132,
"s": 29119,
"text": "Display plot"
},
{
"code": null,
"e": 29141,
"s": 29132,
"text": "Syntax :"
},
{
"code": null,
"e": 29176,
"s": 29141,
"text": "geom_bar(position = βstackβ , ...)"
},
{
"code": null,
"e": 29185,
"s": 29176,
"text": "Example:"
},
{
"code": null,
"e": 29187,
"s": 29185,
"text": "R"
},
{
"code": "# importing the ggplot2 librarylibrary(ggplot2) # creating data framecities <- c(rep(\"Delhi\", 3), rep(\"Mumbai\", 3), rep(\"Chennai\", 3), rep(\"Bengaluru\", 3)) humidity <- rep(c(\"High\", \"Medium\", \"Low\"), 4) temperature <- abs(rnorm(12, 25, 10)) dataframe <- data.frame(cities, humidity, temperature) # calling the dataframedataframe # plotting graphggplot(dataframe, aes(fill = humidity, y = temperature, x = cities))+geom_bar(position = \"stack\", stat = \"identity\")+ggtitle(\"Weather Data of 4 Cities !\")+theme(plot.title = element_text(hjust = 0.5))",
"e": 29794,
"s": 29187,
"text": null
},
{
"code": null,
"e": 29802,
"s": 29794,
"text": "Output:"
},
{
"code": null,
"e": 29843,
"s": 29802,
"text": "Stacked Bar Plot of the Weather Data Set"
},
{
"code": null,
"e": 30239,
"s": 29843,
"text": "The Percent Stacked Bar Plots are used to visualize the contribution or proportion of each categorical variable in while cumulatively taking the primary categorical variable. The entire bar is filled to the top and the different groups occupy the heights corresponding to their proportion in the bar. To map a percent stacked bar plot, the value of the position parameter is specified as βfillβ."
},
{
"code": null,
"e": 30249,
"s": 30239,
"text": "Approach:"
},
{
"code": null,
"e": 30263,
"s": 30249,
"text": "Import module"
},
{
"code": null,
"e": 30280,
"s": 30263,
"text": "Create dataframe"
},
{
"code": null,
"e": 30315,
"s": 30280,
"text": "Plot graph with required functions"
},
{
"code": null,
"e": 30370,
"s": 30315,
"text": "Set position parameter to fill in geom_bar( ) function"
},
{
"code": null,
"e": 30383,
"s": 30370,
"text": "Display plot"
},
{
"code": null,
"e": 30392,
"s": 30383,
"text": "Syntax :"
},
{
"code": null,
"e": 30427,
"s": 30392,
"text": "geom_bar(position = βfillβ , ....)"
},
{
"code": null,
"e": 30436,
"s": 30427,
"text": "Example:"
},
{
"code": null,
"e": 30438,
"s": 30436,
"text": "R"
},
{
"code": "# importing the ggplot2 librarylibrary(ggplot2) # creating data framecities <- c(rep(\"Delhi\", 3), rep(\"Mumbai\", 3), rep(\"Chennai\", 3), rep(\"Bengaluru\", 3)) humidity <- rep(c(\"High\", \"Medium\", \"Low\"), 4) temperature <- abs(rnorm(12, 25, 10)) dataframe <- data.frame(cities, humidity, temperature) # calling the dataframedataframe # plotting graphggplot(dataframe, aes(fill = humidity, y = temperature, x = cities))+geom_bar(position = \"fill\", stat = \"identity\")+ggtitle(\"Weather Data of 4 Cities !\")+theme(plot.title = element_text(hjust = 0.5))",
"e": 31044,
"s": 30438,
"text": null
},
{
"code": null,
"e": 31053,
"s": 31044,
"text": "Output :"
},
{
"code": null,
"e": 31098,
"s": 31053,
"text": "Percent Stacked Bar Plot of Weather Data Set"
},
{
"code": null,
"e": 31105,
"s": 31098,
"text": "Picked"
},
{
"code": null,
"e": 31114,
"s": 31105,
"text": "R-ggplot"
},
{
"code": null,
"e": 31125,
"s": 31114,
"text": "R Language"
},
{
"code": null,
"e": 31223,
"s": 31125,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31275,
"s": 31223,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 31313,
"s": 31275,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 31348,
"s": 31313,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 31406,
"s": 31348,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 31455,
"s": 31406,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 31492,
"s": 31455,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 31542,
"s": 31492,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 31585,
"s": 31542,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 31611,
"s": 31585,
"text": "Time Series Analysis in R"
}
] |
Group List of Dictionary Data by Particular Key in Python - GeeksforGeeks
|
17 Aug, 2020
Group List of Dictionary Data by Particular Key in Python can be done using itertools.groupby() method.
This method calculates the keys for each element present in iterable. It returns key and iterable of grouped items.
Syntax: itertools.groupby(iterable, key_func)
Parameters:
iterable: Iterable can be of any kind (list, tuple, dictionary).
key_func: A function that calculates keys for each element present in iterable.
Return type: It returns consecutive keys and groups from the iterable. If the key function is not specified or is None, key defaults to an identity function and returns the element unchanged.
Letβs see the examples:Example 1: Suppose we have list of dictionary of employee and company.
INFO = [
{'employee': 'XYZ_1', 'company': 'ABC_1'},
{'employee': 'XYZ_2', 'company': 'ABC_2'},
{'employee': 'XYZ_3', 'company': 'ABC_3'},
{'employee': 'XYZ_4', 'company': 'ABC_3'},
{'employee': 'XYZ_5', 'company': 'ABC_2'},
{'employee': 'XYZ_6', 'company': 'ABC_3'},
{'employee': 'XYZ_7', 'company': 'ABC_1'},
{'employee': 'XYZ_8', 'company': 'ABC_2'},
{'employee': 'XYZ_9', 'company': 'ABC_1'}
]
Now we need to display all the data group by the βcompanyβ key name.
Code:
Python3
# import a groupby() method# from itertools modulefrom itertools import groupby # dictionaryINFO = [ {'employee': 'XYZ_1', 'company': 'ABC_1'}, {'employee': 'XYZ_2', 'company': 'ABC_2'}, {'employee': 'XYZ_3', 'company': 'ABC_3'}, {'employee': 'XYZ_4', 'company': 'ABC_3'}, {'employee': 'XYZ_5', 'company': 'ABC_2'}, {'employee': 'XYZ_6', 'company': 'ABC_3'}, {'employee': 'XYZ_7', 'company': 'ABC_1'}, {'employee': 'XYZ_8', 'company': 'ABC_2'}, {'employee': 'XYZ_9', 'company': 'ABC_1'}] # define a fuction for keydef key_func(k): return k['company'] # sort INFO data by 'company' key.INFO = sorted(INFO, key=key_func) for key, value in groupby(INFO, key_func): print(key) print(list(value))
Output:
ABC_1[{βemployeeβ: βXYZ_1β, βcompanyβ: βABC_1β²}, {βemployeeβ: βXYZ_7β, βcompanyβ: βABC_1β²}, {βemployeeβ: βXYZ_9β, βcompanyβ: βABC_1β²}]ABC_2[{βemployeeβ: βXYZ_2β, βcompanyβ: βABC_2β²}, {βemployeeβ: βXYZ_5β, βcompanyβ: βABC_2β²}, {βemployeeβ: βXYZ_8β, βcompanyβ: βABC_2β²}]ABC_3[{βemployeeβ: βXYZ_3β, βcompanyβ: βABC_3β²}, {βemployeeβ: βXYZ_4β, βcompanyβ: βABC_3β²}, {βemployeeβ: βXYZ_6β, βcompanyβ: βABC_3β}]
Example 2: Suppose we have list of dictionary of student grades and marks.
students = [
{'mark': '65','grade': 'C'},
{'mark': '86','grade': 'A'},
{'mark': '73','grade': 'B'},
{'mark': '49','grade': 'D'},
{'mark': '91','grade': 'A'},
{'mark': '79','grade': 'B'}
]
Now we need to display all the data group by the βgradeβ key.
Code:
Python3
# import required methodsfrom itertools import groupbyfrom operator import itemgetter # dictionarystudents = [ {'mark': '65', 'grade': 'C'}, {'mark': '86', 'grade': 'A'}, {'mark': '73', 'grade': 'B'}, {'mark': '49', 'grade': 'D'}, {'mark': '91', 'grade': 'A'}, {'mark': '79', 'grade': 'B'}] # Sort students data by grade key.students = sorted(students, key = itemgetter('grade')) # Display data grouped by gradefor key, value in groupby(students, key = itemgetter('grade')): print(key) for k in value: print(k)
Output:
A
{'mark': '86', 'grade': 'A'}
{'mark': '91', 'grade': 'A'}
B
{'mark': '73', 'grade': 'B'}
{'mark': '79', 'grade': 'B'}
C
{'mark': '65', 'grade': 'C'}
D
{'mark': '49', 'grade': 'D'}
Python-itertools
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
|
[
{
"code": null,
"e": 24685,
"s": 24657,
"text": "\n17 Aug, 2020"
},
{
"code": null,
"e": 24789,
"s": 24685,
"text": "Group List of Dictionary Data by Particular Key in Python can be done using itertools.groupby() method."
},
{
"code": null,
"e": 24905,
"s": 24789,
"text": "This method calculates the keys for each element present in iterable. It returns key and iterable of grouped items."
},
{
"code": null,
"e": 24951,
"s": 24905,
"text": "Syntax: itertools.groupby(iterable, key_func)"
},
{
"code": null,
"e": 24963,
"s": 24951,
"text": "Parameters:"
},
{
"code": null,
"e": 25028,
"s": 24963,
"text": "iterable: Iterable can be of any kind (list, tuple, dictionary)."
},
{
"code": null,
"e": 25108,
"s": 25028,
"text": "key_func: A function that calculates keys for each element present in iterable."
},
{
"code": null,
"e": 25300,
"s": 25108,
"text": "Return type: It returns consecutive keys and groups from the iterable. If the key function is not specified or is None, key defaults to an identity function and returns the element unchanged."
},
{
"code": null,
"e": 25394,
"s": 25300,
"text": "Letβs see the examples:Example 1: Suppose we have list of dictionary of employee and company."
},
{
"code": null,
"e": 25828,
"s": 25394,
"text": "INFO = [\n {'employee': 'XYZ_1', 'company': 'ABC_1'},\n {'employee': 'XYZ_2', 'company': 'ABC_2'},\n {'employee': 'XYZ_3', 'company': 'ABC_3'},\n {'employee': 'XYZ_4', 'company': 'ABC_3'},\n {'employee': 'XYZ_5', 'company': 'ABC_2'},\n {'employee': 'XYZ_6', 'company': 'ABC_3'},\n {'employee': 'XYZ_7', 'company': 'ABC_1'},\n {'employee': 'XYZ_8', 'company': 'ABC_2'},\n {'employee': 'XYZ_9', 'company': 'ABC_1'}\n]\n"
},
{
"code": null,
"e": 25897,
"s": 25828,
"text": "Now we need to display all the data group by the βcompanyβ key name."
},
{
"code": null,
"e": 25903,
"s": 25897,
"text": "Code:"
},
{
"code": null,
"e": 25911,
"s": 25903,
"text": "Python3"
},
{
"code": "# import a groupby() method# from itertools modulefrom itertools import groupby # dictionaryINFO = [ {'employee': 'XYZ_1', 'company': 'ABC_1'}, {'employee': 'XYZ_2', 'company': 'ABC_2'}, {'employee': 'XYZ_3', 'company': 'ABC_3'}, {'employee': 'XYZ_4', 'company': 'ABC_3'}, {'employee': 'XYZ_5', 'company': 'ABC_2'}, {'employee': 'XYZ_6', 'company': 'ABC_3'}, {'employee': 'XYZ_7', 'company': 'ABC_1'}, {'employee': 'XYZ_8', 'company': 'ABC_2'}, {'employee': 'XYZ_9', 'company': 'ABC_1'}] # define a fuction for keydef key_func(k): return k['company'] # sort INFO data by 'company' key.INFO = sorted(INFO, key=key_func) for key, value in groupby(INFO, key_func): print(key) print(list(value))",
"e": 26645,
"s": 25911,
"text": null
},
{
"code": null,
"e": 26653,
"s": 26645,
"text": "Output:"
},
{
"code": null,
"e": 27056,
"s": 26653,
"text": "ABC_1[{βemployeeβ: βXYZ_1β, βcompanyβ: βABC_1β²}, {βemployeeβ: βXYZ_7β, βcompanyβ: βABC_1β²}, {βemployeeβ: βXYZ_9β, βcompanyβ: βABC_1β²}]ABC_2[{βemployeeβ: βXYZ_2β, βcompanyβ: βABC_2β²}, {βemployeeβ: βXYZ_5β, βcompanyβ: βABC_2β²}, {βemployeeβ: βXYZ_8β, βcompanyβ: βABC_2β²}]ABC_3[{βemployeeβ: βXYZ_3β, βcompanyβ: βABC_3β²}, {βemployeeβ: βXYZ_4β, βcompanyβ: βABC_3β²}, {βemployeeβ: βXYZ_6β, βcompanyβ: βABC_3β}]"
},
{
"code": null,
"e": 27131,
"s": 27056,
"text": "Example 2: Suppose we have list of dictionary of student grades and marks."
},
{
"code": null,
"e": 27346,
"s": 27131,
"text": "students = [\n {'mark': '65','grade': 'C'},\n {'mark': '86','grade': 'A'},\n {'mark': '73','grade': 'B'},\n {'mark': '49','grade': 'D'},\n {'mark': '91','grade': 'A'},\n {'mark': '79','grade': 'B'}\n]\n\n\n"
},
{
"code": null,
"e": 27408,
"s": 27346,
"text": "Now we need to display all the data group by the βgradeβ key."
},
{
"code": null,
"e": 27414,
"s": 27408,
"text": "Code:"
},
{
"code": null,
"e": 27422,
"s": 27414,
"text": "Python3"
},
{
"code": "# import required methodsfrom itertools import groupbyfrom operator import itemgetter # dictionarystudents = [ {'mark': '65', 'grade': 'C'}, {'mark': '86', 'grade': 'A'}, {'mark': '73', 'grade': 'B'}, {'mark': '49', 'grade': 'D'}, {'mark': '91', 'grade': 'A'}, {'mark': '79', 'grade': 'B'}] # Sort students data by grade key.students = sorted(students, key = itemgetter('grade')) # Display data grouped by gradefor key, value in groupby(students, key = itemgetter('grade')): print(key) for k in value: print(k)",
"e": 28010,
"s": 27422,
"text": null
},
{
"code": null,
"e": 28018,
"s": 28010,
"text": "Output:"
},
{
"code": null,
"e": 28200,
"s": 28018,
"text": "A\n{'mark': '86', 'grade': 'A'}\n{'mark': '91', 'grade': 'A'}\nB\n{'mark': '73', 'grade': 'B'}\n{'mark': '79', 'grade': 'B'}\nC\n{'mark': '65', 'grade': 'C'}\nD\n{'mark': '49', 'grade': 'D'}"
},
{
"code": null,
"e": 28217,
"s": 28200,
"text": "Python-itertools"
},
{
"code": null,
"e": 28224,
"s": 28217,
"text": "Python"
},
{
"code": null,
"e": 28322,
"s": 28224,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28331,
"s": 28322,
"text": "Comments"
},
{
"code": null,
"e": 28344,
"s": 28331,
"text": "Old Comments"
},
{
"code": null,
"e": 28362,
"s": 28344,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28397,
"s": 28362,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28419,
"s": 28397,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28451,
"s": 28419,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28481,
"s": 28451,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28523,
"s": 28481,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28566,
"s": 28523,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28592,
"s": 28566,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28636,
"s": 28592,
"text": "Reading and Writing to text files in Python"
}
] |
How to get volley array list with custom object in android?
|
This example demonstrate about How to get volley array list with custom object in android.
Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project.
Step 2 β Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:textSize="30sp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
In the above code, we have taken text view to show custom array list object elements.
Step 3 β Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
TextView textView;
RequestQueue queue;
String URL = "http://www.mocky.io/v2/597c41390f0000d002f4dbd1";
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
final List<UserInfo> list=new ArrayList<>();
queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject object=new JSONObject(response);
JSONArray array=object.getJSONArray("users");
for(int i=0;i<array.length();i++) {
JSONObject object1=array.getJSONObject(i);
String name =object1.getString("name");
String email =object1.getString("email");
list.add(new UserInfo(name,email));
}
textView.setText("email: "+list.get(0).email+ " \nname: "+list.get(0).name);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
}
});
queue.add(request);
}
private class UserInfo {
String name,email;
public UserInfo(String name, String email) {
this.name=name;
this.email=email;
}
}
}
Step 4 β Add the following code to AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Step 5 β Add the following code to build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.myapplication"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.volley:volley:1.1.0'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β
Click here to download the project code
|
[
{
"code": null,
"e": 1153,
"s": 1062,
"text": "This example demonstrate about How to get volley array list with custom object in android."
},
{
"code": null,
"e": 1282,
"s": 1153,
"text": "Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1347,
"s": 1282,
"text": "Step 2 β Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1881,
"s": 1347,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:gravity=\"center\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/text\"\n android:textSize=\"30sp\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1967,
"s": 1881,
"text": "In the above code, we have taken text view to show custom array list object elements."
},
{
"code": null,
"e": 2024,
"s": 1967,
"text": "Step 3 β Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4310,
"s": 2024,
"text": "package com.example.myapplication;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.Log;\nimport android.widget.TextView;\nimport com.android.volley.Request;\nimport com.android.volley.RequestQueue;\nimport com.android.volley.Response;\nimport com.android.volley.VolleyError;\nimport com.android.volley.toolbox.StringRequest;\nimport com.android.volley.toolbox.Volley;\nimport org.json.JSONArray;\nimport org.json.JSONException;\nimport org.json.JSONObject;\nimport java.util.ArrayList;\nimport java.util.List;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n RequestQueue queue;\n String URL = \"http://www.mocky.io/v2/597c41390f0000d002f4dbd1\";\n @RequiresApi(api = Build.VERSION_CODES.N)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n final List<UserInfo> list=new ArrayList<>();\n queue = Volley.newRequestQueue(this);\n StringRequest request = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {\n @Override\n public void onResponse(String response) {\n try {\n JSONObject object=new JSONObject(response);\n JSONArray array=object.getJSONArray(\"users\");\n for(int i=0;i<array.length();i++) {\n JSONObject object1=array.getJSONObject(i);\n String name =object1.getString(\"name\");\n String email =object1.getString(\"email\");\n list.add(new UserInfo(name,email));\n }\n textView.setText(\"email: \"+list.get(0).email+ \" \\nname: \"+list.get(0).name);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n }, new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n Log.d(\"error\",error.toString());\n }\n });\n queue.add(request);\n }\n private class UserInfo {\n String name,email;\n public UserInfo(String name, String email) {\nthis.name=name;\nthis.email=email;\n}\n}\n}"
},
{
"code": null,
"e": 4365,
"s": 4310,
"text": "Step 4 β Add the following code to AndroidManifest.xml"
},
{
"code": null,
"e": 5187,
"s": 4365,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.myapplication\">\n <uses-permission android:name=\"android.permission.INTERNET\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <action android:name=\"android.net.conn.CONNECTIVITY_CHANGE\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n</application>\n</manifest>"
},
{
"code": null,
"e": 5235,
"s": 5187,
"text": "Step 5 β Add the following code to build.gradle"
},
{
"code": null,
"e": 6191,
"s": 5235,
"text": "apply plugin: 'com.android.application'\nandroid {\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.example.myapplication\"\n minSdkVersion 15\n targetSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.volley:volley:1.1.0'\n implementation 'com.android.support:appcompat-v7:28.0.0'\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\n}"
},
{
"code": null,
"e": 6538,
"s": 6191,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β"
},
{
"code": null,
"e": 6578,
"s": 6538,
"text": "Click here to download the project code"
}
] |
C++ Program For QuickSort On Doubly Linked List - GeeksforGeeks
|
23 Dec, 2021
Following is a typical recursive implementation of QuickSort for arrays. The implementation uses last element as pivot.
C++
/* A typical recursive implementation of Quicksort for array*/ /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */int partition (int arr[], int l, int h){ int x = arr[h]; int i = (l - 1); for (int j = l; j <= h- 1; j++) { if (arr[j] <= x) { i++; swap (&arr[i], &arr[j]); } } swap (&arr[i + 1], &arr[h]); return (i + 1);} /* A[] --> Array to be sorted, l --> Starting index, h --> Ending index */void quickSort(int A[], int l, int h){ if (l < h) { int p = partition(A, l, h); /* Partitioning index */ quickSort(A, l, p - 1); quickSort(A, p + 1, h); }}
Can we use the same algorithm for Linked List? Following is C++ implementation for the doubly linked list. The idea is simple, we first find out pointer to the last node. Once we have a pointer to the last node, we can recursively sort the linked list using pointers to first and last nodes of a linked list, similar to the above recursive function where we pass indexes of first and last array elements. The partition function for a linked list is also similar to partition for arrays. Instead of returning index of the pivot element, it returns a pointer to the pivot element. In the following implementation, quickSort() is just a wrapper function, the main recursive function is _quickSort() which is similar to quickSort() for array implementation.
C++
// A C++ program to sort a linked list using Quicksort #include <bits/stdc++.h>using namespace std; /* a node of the doubly linked list */class Node { public: int data; Node *next; Node *prev; }; /* A utility function to swap two elements */void swap ( int* a, int* b ) { int t = *a; *a = *b; *b = t; } // A utility function to find// last node of linked list Node *lastNode(Node *root) { while (root && root->next) root = root->next; return root; } /* Considers last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greaterelements to right of pivot */Node* partition(Node *l, Node *h) { // set pivot as h element int x = h->data; // similar to i = l-1 for array implementation Node *i = l->prev; // Similar to "for (int j = l; j <= h- 1; j++)" for (Node *j = l; j != h; j = j->next) { if (j->data <= x) { // Similar to i++ for array i = (i == NULL)? l : i->next; swap(&(i->data), &(j->data)); } } i = (i == NULL)? l : i->next; // Similar to i++ swap(&(i->data), &(h->data)); return i; } /* A recursive implementation of quicksort for linked list */void _quickSort(Node* l, Node *h) { if (h != NULL && l != h && l != h->next) { Node *p = partition(l, h); _quickSort(l, p->prev); _quickSort(p->next, h); } } // The main function to sort a linked list.// It mainly calls _quickSort() void quickSort(Node *head) { // Find last node Node *h = lastNode(head); // Call the recursive QuickSort _quickSort(head, h); } // A utility function to print contents of arr void printList(Node *head) { while (head) { cout << head->data << " "; head = head->next; } cout << endl; } /* Function to insert a node at the beginning of the Doubly Linked List */void push(Node** head_ref, int new_data) { Node* new_node = new Node; /* allocate node */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if ((*head_ref) != NULL) (*head_ref)->prev = new_node ; /* move the head to point to the new node */ (*head_ref) = new_node; } /* Driver code */int main() { Node *a = NULL; push(&a, 5); push(&a, 20); push(&a, 4); push(&a, 3); push(&a, 30); cout << "Linked List before sorting "; printList(a); quickSort(a); cout << "Linked List after sorting "; printList(a); return 0; } // This code is contributed by rathbhupendra
Output :
Linked List before sorting
30 3 4 20 5
Linked List after sorting
3 4 5 20 30
Time Complexity: Time complexity of the above implementation is same as time complexity of QuickSort() for arrays. It takes O(n^2) time in the worst case and O(nLogn) in average and best cases. The worst case occurs when the linked list is already sorted.Can we implement random quicksort for a linked list? Quicksort can be implemented for Linked List only when we can pick a fixed point as the pivot (like the last element in the above implementation). Random QuickSort cannot be efficiently implemented for Linked Lists by picking random pivot.
Please refer complete article on QuickSort on Doubly Linked List for more details!
doubly linked list
HSBC
Linked-List-Sorting
Quick Sort
C++ Programs
Linked List
Sorting
HSBC
Linked List
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Const keyword in C++
Program to implement Singly Linked List in C++ using class
cout in C++
Dynamic _Cast in C++
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Reverse a linked list
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node)
|
[
{
"code": null,
"e": 24606,
"s": 24578,
"text": "\n23 Dec, 2021"
},
{
"code": null,
"e": 24727,
"s": 24606,
"text": "Following is a typical recursive implementation of QuickSort for arrays. The implementation uses last element as pivot. "
},
{
"code": null,
"e": 24731,
"s": 24727,
"text": "C++"
},
{
"code": "/* A typical recursive implementation of Quicksort for array*/ /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */int partition (int arr[], int l, int h){ int x = arr[h]; int i = (l - 1); for (int j = l; j <= h- 1; j++) { if (arr[j] <= x) { i++; swap (&arr[i], &arr[j]); } } swap (&arr[i + 1], &arr[h]); return (i + 1);} /* A[] --> Array to be sorted, l --> Starting index, h --> Ending index */void quickSort(int A[], int l, int h){ if (l < h) { int p = partition(A, l, h); /* Partitioning index */ quickSort(A, l, p - 1); quickSort(A, p + 1, h); }}",
"e": 25566,
"s": 24731,
"text": null
},
{
"code": null,
"e": 26321,
"s": 25566,
"text": "Can we use the same algorithm for Linked List? Following is C++ implementation for the doubly linked list. The idea is simple, we first find out pointer to the last node. Once we have a pointer to the last node, we can recursively sort the linked list using pointers to first and last nodes of a linked list, similar to the above recursive function where we pass indexes of first and last array elements. The partition function for a linked list is also similar to partition for arrays. Instead of returning index of the pivot element, it returns a pointer to the pivot element. In the following implementation, quickSort() is just a wrapper function, the main recursive function is _quickSort() which is similar to quickSort() for array implementation. "
},
{
"code": null,
"e": 26325,
"s": 26321,
"text": "C++"
},
{
"code": "// A C++ program to sort a linked list using Quicksort #include <bits/stdc++.h>using namespace std; /* a node of the doubly linked list */class Node { public: int data; Node *next; Node *prev; }; /* A utility function to swap two elements */void swap ( int* a, int* b ) { int t = *a; *a = *b; *b = t; } // A utility function to find// last node of linked list Node *lastNode(Node *root) { while (root && root->next) root = root->next; return root; } /* Considers last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greaterelements to right of pivot */Node* partition(Node *l, Node *h) { // set pivot as h element int x = h->data; // similar to i = l-1 for array implementation Node *i = l->prev; // Similar to \"for (int j = l; j <= h- 1; j++)\" for (Node *j = l; j != h; j = j->next) { if (j->data <= x) { // Similar to i++ for array i = (i == NULL)? l : i->next; swap(&(i->data), &(j->data)); } } i = (i == NULL)? l : i->next; // Similar to i++ swap(&(i->data), &(h->data)); return i; } /* A recursive implementation of quicksort for linked list */void _quickSort(Node* l, Node *h) { if (h != NULL && l != h && l != h->next) { Node *p = partition(l, h); _quickSort(l, p->prev); _quickSort(p->next, h); } } // The main function to sort a linked list.// It mainly calls _quickSort() void quickSort(Node *head) { // Find last node Node *h = lastNode(head); // Call the recursive QuickSort _quickSort(head, h); } // A utility function to print contents of arr void printList(Node *head) { while (head) { cout << head->data << \" \"; head = head->next; } cout << endl; } /* Function to insert a node at the beginning of the Doubly Linked List */void push(Node** head_ref, int new_data) { Node* new_node = new Node; /* allocate node */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if ((*head_ref) != NULL) (*head_ref)->prev = new_node ; /* move the head to point to the new node */ (*head_ref) = new_node; } /* Driver code */int main() { Node *a = NULL; push(&a, 5); push(&a, 20); push(&a, 4); push(&a, 3); push(&a, 30); cout << \"Linked List before sorting \"; printList(a); quickSort(a); cout << \"Linked List after sorting \"; printList(a); return 0; } // This code is contributed by rathbhupendra",
"e": 29151,
"s": 26325,
"text": null
},
{
"code": null,
"e": 29160,
"s": 29151,
"text": "Output :"
},
{
"code": null,
"e": 29245,
"s": 29160,
"text": "Linked List before sorting\n30 3 4 20 5\nLinked List after sorting\n3 4 5 20 30"
},
{
"code": null,
"e": 29793,
"s": 29245,
"text": "Time Complexity: Time complexity of the above implementation is same as time complexity of QuickSort() for arrays. It takes O(n^2) time in the worst case and O(nLogn) in average and best cases. The worst case occurs when the linked list is already sorted.Can we implement random quicksort for a linked list? Quicksort can be implemented for Linked List only when we can pick a fixed point as the pivot (like the last element in the above implementation). Random QuickSort cannot be efficiently implemented for Linked Lists by picking random pivot."
},
{
"code": null,
"e": 29876,
"s": 29793,
"text": "Please refer complete article on QuickSort on Doubly Linked List for more details!"
},
{
"code": null,
"e": 29895,
"s": 29876,
"text": "doubly linked list"
},
{
"code": null,
"e": 29900,
"s": 29895,
"text": "HSBC"
},
{
"code": null,
"e": 29920,
"s": 29900,
"text": "Linked-List-Sorting"
},
{
"code": null,
"e": 29931,
"s": 29920,
"text": "Quick Sort"
},
{
"code": null,
"e": 29944,
"s": 29931,
"text": "C++ Programs"
},
{
"code": null,
"e": 29956,
"s": 29944,
"text": "Linked List"
},
{
"code": null,
"e": 29964,
"s": 29956,
"text": "Sorting"
},
{
"code": null,
"e": 29969,
"s": 29964,
"text": "HSBC"
},
{
"code": null,
"e": 29981,
"s": 29969,
"text": "Linked List"
},
{
"code": null,
"e": 29989,
"s": 29981,
"text": "Sorting"
},
{
"code": null,
"e": 30087,
"s": 29989,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30128,
"s": 30087,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 30149,
"s": 30128,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 30208,
"s": 30149,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 30220,
"s": 30208,
"text": "cout in C++"
},
{
"code": null,
"e": 30241,
"s": 30220,
"text": "Dynamic _Cast in C++"
},
{
"code": null,
"e": 30276,
"s": 30241,
"text": "Linked List | Set 1 (Introduction)"
},
{
"code": null,
"e": 30315,
"s": 30276,
"text": "Linked List | Set 2 (Inserting a node)"
},
{
"code": null,
"e": 30337,
"s": 30315,
"text": "Reverse a linked list"
},
{
"code": null,
"e": 30385,
"s": 30337,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
DATEADD or DATE_ADD in MySQL query?
|
You need to use DATE_ADD() in MySQL.
The syntax is as follows
DATE_ADD(NOW(), INTERVAL yourValue MINUTE);
Arithmetic operator can also be used.
The syntax is as follows
NOW() + INTERVAL 30 MINUTE
Here is the demo of DATE_ADD() function.
The query is as follows
mysql> select date_add(now(), interval 30 minute);
The following is the output
+-------------------------------------+
| date_add(now(), interval 30 minute) |
+-------------------------------------+
| 2019-02-27 15:38:27 |
+-------------------------------------+
1 row in set (0.00 sec)
Let us now use arithmetic + operator instead of DATE_ADD().
The query is as follows
mysql> select now();
+---------------------+
| now() |
+---------------------+
| 2019-02-27 15:09:18 |
+---------------------+
1 row in set (0.00 sec)
Now add 30 minutes in NOW().
The query is as follows
mysql> select now()+interval 30 minute;
The following is the output
+--------------------------+
| now()+interval 30 minute |
+--------------------------+
| 2019-02-27 15:39:33 |
+--------------------------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1099,
"s": 1062,
"text": "You need to use DATE_ADD() in MySQL."
},
{
"code": null,
"e": 1124,
"s": 1099,
"text": "The syntax is as follows"
},
{
"code": null,
"e": 1168,
"s": 1124,
"text": "DATE_ADD(NOW(), INTERVAL yourValue MINUTE);"
},
{
"code": null,
"e": 1206,
"s": 1168,
"text": "Arithmetic operator can also be used."
},
{
"code": null,
"e": 1231,
"s": 1206,
"text": "The syntax is as follows"
},
{
"code": null,
"e": 1258,
"s": 1231,
"text": "NOW() + INTERVAL 30 MINUTE"
},
{
"code": null,
"e": 1299,
"s": 1258,
"text": "Here is the demo of DATE_ADD() function."
},
{
"code": null,
"e": 1323,
"s": 1299,
"text": "The query is as follows"
},
{
"code": null,
"e": 1374,
"s": 1323,
"text": "mysql> select date_add(now(), interval 30 minute);"
},
{
"code": null,
"e": 1402,
"s": 1374,
"text": "The following is the output"
},
{
"code": null,
"e": 1626,
"s": 1402,
"text": "+-------------------------------------+\n| date_add(now(), interval 30 minute) |\n+-------------------------------------+\n| 2019-02-27 15:38:27 |\n+-------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 1686,
"s": 1626,
"text": "Let us now use arithmetic + operator instead of DATE_ADD()."
},
{
"code": null,
"e": 1710,
"s": 1686,
"text": "The query is as follows"
},
{
"code": null,
"e": 1875,
"s": 1710,
"text": "mysql> select now();\n+---------------------+\n| now() |\n+---------------------+\n| 2019-02-27 15:09:18 |\n+---------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 1904,
"s": 1875,
"text": "Now add 30 minutes in NOW()."
},
{
"code": null,
"e": 1928,
"s": 1904,
"text": "The query is as follows"
},
{
"code": null,
"e": 1968,
"s": 1928,
"text": "mysql> select now()+interval 30 minute;"
},
{
"code": null,
"e": 1996,
"s": 1968,
"text": "The following is the output"
},
{
"code": null,
"e": 2165,
"s": 1996,
"text": "+--------------------------+\n| now()+interval 30 minute |\n+--------------------------+\n| 2019-02-27 15:39:33 |\n+--------------------------+\n1 row in set (0.00 sec)"
}
] |
How to slice a string in AngularJS ? - GeeksforGeeks
|
14 Oct, 2020
Given a string and the task is to make a slice of given string using AngularJS.
Approach 1 Using slice() method: The approach is to use the slice() method which accepts 2 parameters start and end. In the first example, only 1 parameter is used and in the second example 2 parameters are used.
Example 1:
<!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.str = "This is GeeksForGeeks"; $scope.res = ''; $scope.sliceStr = function () { $scope.res = $scope.str.slice(8); } }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to slice a string in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> String - '{{str}}'<br><br> <button type="button" ng-click="sliceStr()"> Click Me </button> <p>Result = '{{res}}'</p> </div> </div></body> </html>
Output:
Example 2:
<!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.str = "A Computer Science portal"; $scope.res = ''; $scope.sliceStr = function () { $scope.res = $scope.str.slice(2, 18); } }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to slice a string in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> String - '{{str}}'<br><br> <button type="button" ng-click="sliceStr()"> Click Me </button> <p>Result = '{{res}}'</p> </div> </div></body> </html>
Output:
Approach 2 Using substr() method: The approach is to use the substr() method. It takes 2 parameters, one is the start and another is length(optional). In the first example only one parameter is used. And in the second example both parameters are used.
Example 1:
<!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.str = "This is GeeksForGeeks"; $scope.res = ''; $scope.subStr = function () { $scope.res = $scope.str.substr(8); } }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to slice a string using substr() method in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> String - '{{str}}'<br><br> <button type="button" ng-click="subStr()"> Click Me </button> <p>Result = '{{res}}'</p> </div> </div></body> </html>
Output:
Example 2:
<!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.str = "A Computer Science portal"; $scope.res = ''; $scope.subStr = function () { $scope.res = $scope.str.substr(2, 16); } }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to slice a string using substr() method in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> String - '{{str}}'<br><br> <button type="button" ng-click="subStr()"> Click Me </button> <p>Result = '{{res}}'</p> </div> </div></body> </html>
Output:
Attention reader! Donβt stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
AngularJS-Misc
HTML-Misc
AngularJS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Auth Guards in Angular 9/10/11
How to bundle an Angular app for production?
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
How to set focus on input field automatically on page load in AngularJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 24308,
"s": 24280,
"text": "\n14 Oct, 2020"
},
{
"code": null,
"e": 24388,
"s": 24308,
"text": "Given a string and the task is to make a slice of given string using AngularJS."
},
{
"code": null,
"e": 24601,
"s": 24388,
"text": "Approach 1 Using slice() method: The approach is to use the slice() method which accepts 2 parameters start and end. In the first example, only 1 parameter is used and in the second example 2 parameters are used."
},
{
"code": null,
"e": 24612,
"s": 24601,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.str = \"This is GeeksForGeeks\"; $scope.res = ''; $scope.sliceStr = function () { $scope.res = $scope.str.slice(8); } }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to slice a string in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> String - '{{str}}'<br><br> <button type=\"button\" ng-click=\"sliceStr()\"> Click Me </button> <p>Result = '{{res}}'</p> </div> </div></body> </html> ",
"e": 25550,
"s": 24612,
"text": null
},
{
"code": null,
"e": 25558,
"s": 25550,
"text": "Output:"
},
{
"code": null,
"e": 25569,
"s": 25558,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.str = \"A Computer Science portal\"; $scope.res = ''; $scope.sliceStr = function () { $scope.res = $scope.str.slice(2, 18); } }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to slice a string in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> String - '{{str}}'<br><br> <button type=\"button\" ng-click=\"sliceStr()\"> Click Me </button> <p>Result = '{{res}}'</p> </div> </div></body> </html>",
"e": 26466,
"s": 25569,
"text": null
},
{
"code": null,
"e": 26474,
"s": 26466,
"text": "Output:"
},
{
"code": null,
"e": 26727,
"s": 26474,
"text": "Approach 2 Using substr() method: The approach is to use the substr() method. It takes 2 parameters, one is the start and another is length(optional). In the first example only one parameter is used. And in the second example both parameters are used. "
},
{
"code": null,
"e": 26738,
"s": 26727,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.str = \"This is GeeksForGeeks\"; $scope.res = ''; $scope.subStr = function () { $scope.res = $scope.str.substr(8); } }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to slice a string using substr() method in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> String - '{{str}}'<br><br> <button type=\"button\" ng-click=\"subStr()\"> Click Me </button> <p>Result = '{{res}}'</p> </div> </div></body> </html> ",
"e": 27685,
"s": 26738,
"text": null
},
{
"code": null,
"e": 27693,
"s": 27685,
"text": "Output:"
},
{
"code": null,
"e": 27704,
"s": 27693,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.str = \"A Computer Science portal\"; $scope.res = ''; $scope.subStr = function () { $scope.res = $scope.str.substr(2, 16); } }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to slice a string using substr() method in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> String - '{{str}}'<br><br> <button type=\"button\" ng-click=\"subStr()\"> Click Me </button> <p>Result = '{{res}}'</p> </div> </div></body> </html> ",
"e": 28665,
"s": 27704,
"text": null
},
{
"code": null,
"e": 28673,
"s": 28665,
"text": "Output:"
},
{
"code": null,
"e": 28810,
"s": 28673,
"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": 28825,
"s": 28810,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 28835,
"s": 28825,
"text": "HTML-Misc"
},
{
"code": null,
"e": 28845,
"s": 28835,
"text": "AngularJS"
},
{
"code": null,
"e": 28850,
"s": 28845,
"text": "HTML"
},
{
"code": null,
"e": 28867,
"s": 28850,
"text": "Web Technologies"
},
{
"code": null,
"e": 28894,
"s": 28867,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28899,
"s": 28894,
"text": "HTML"
},
{
"code": null,
"e": 28997,
"s": 28899,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29006,
"s": 28997,
"text": "Comments"
},
{
"code": null,
"e": 29019,
"s": 29006,
"text": "Old Comments"
},
{
"code": null,
"e": 29050,
"s": 29019,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 29095,
"s": 29050,
"text": "How to bundle an Angular app for production?"
},
{
"code": null,
"e": 29137,
"s": 29095,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 29172,
"s": 29137,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 29246,
"s": 29172,
"text": "How to set focus on input field automatically on page load in AngularJS ?"
},
{
"code": null,
"e": 29308,
"s": 29246,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29358,
"s": 29308,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 29418,
"s": 29358,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 29466,
"s": 29418,
"text": "How to update Node.js and NPM to next version ?"
}
] |
How to fetch data from localserver database and display on HTML table using PHP ?
|
06 Jun, 2022
In this article, we will see how we can display the records in an HTML table by fetching them from the MySQL database using PHP.
Approach: Make sure you have XAMPP or WAMP server installed on your machine. In this article, we will be using the WAMP server.
WAMP Server is open-source software for the Microsoft Windows operating system, developed by Romain Bourdon. It is composed of an Apache web server, OpenSSL for SSL support, MySQL database and PHP programming language. Here, before going through the program, we need to create a MySQL database in our localhost server. Then, we are supposed to make an HTML table that is linked with PHP codes. PHP is used to connect with the localhost server and to fetch the data from the database table present in our localhost server by evaluating the MySQL queries. WAMP server helps to start Apache and MySQL and connect them with the PHP file.
Follow the steps given below:
1. Creating Database: First, we will create a database named βgeeksforgeeksβ. You can use your existing database or create a new one.
create database βgeeksforgeeksβ
2. Create Table: Create a table named βuserdataβ. The table contains four fields:
username β varchar(100)
problems β int(11)
score β int(11)
articles β int(11)
Your table structure should look like this:
the table structure of βuserdataβ
Or you can create a table by copying and pasting the following code into the SQL panel of your PHPMyAdmin.
CREATE TABLE IF NOT EXISTS `userdata` (
`username` varchar(100) NOT NULL,
`problems` int(11) NOT NULL,
`score` int(11) NOT NULL,
`articles` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
To do this from the SQL panel refer to the following screenshot:
create a table βuserdataβ from the SQL panel
Insert records: We will now insert some records into our table. Here we are inserting 5 records. You can add multiple records.
Or copy and paste the following code into the SQL panel to insert records in the table.
INSERT INTO `userdata`
(`username`, `problems`, `score`, `articles`)
VALUES ('User-2', '100', '75', '30'), ('User-1', '150', '100', '30'), ('User-3', '200', '50', '10'), ('User-4', '50', '5', '2'), ('User-5', '0', '0', '1');
To do this from the SQL panel refer to the following screenshot:
inserting records
Creating folder and files:
We will now create our project folder named βGeeksForGeeksβ. Create an index.php file. Keep your main project folder (for example here.. GeeksForGeeks) in the βC://wamp64/www/β, if you are using WAMP or βC://xampp/htdocs/β folder if you are using the XAMPP server respectively. The folder structure should look like this:
folder structure
Now, we have a database named geeksforgeeks, and a table named userdata. Now, here is the PHP code to fetch data from the database and display it in an HTML table.
Example:
php
<!-- PHP code to establish connection with the localserver --><?php // Username is root$user = 'root';$password = ''; // Database name is geeksforgeeks$database = 'geeksforgeeks'; // Server is localhost with// port number 3306$servername='localhost:3306';$mysqli = new mysqli($servername, $user, $password, $database); // Checking for connectionsif ($mysqli->connect_error) { die('Connect Error (' . $mysqli->connect_errno . ') '. $mysqli->connect_error);} // SQL query to select data from database$sql = " SELECT * FROM userdata ORDER BY score DESC ";$result = $mysqli->query($sql);$mysqli->close();?><!-- HTML code to display data in tabular format --><!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>GFG User Details</title> <!-- CSS FOR STYLING THE PAGE --> <style> table { margin: 0 auto; font-size: large; border: 1px solid black; } h1 { text-align: center; color: #006600; font-size: xx-large; font-family: 'Gill Sans', 'Gill Sans MT', ' Calibri', 'Trebuchet MS', 'sans-serif'; } td { background-color: #E4F5D4; border: 1px solid black; } th, td { font-weight: bold; border: 1px solid black; padding: 10px; text-align: center; } td { font-weight: lighter; } </style></head> <body> <section> <h1>GeeksForGeeks</h1> <!-- TABLE CONSTRUCTION --> <table> <tr> <th>GFG UserHandle</th> <th>Practice Problems</th> <th>Coding Score</th> <th>GFG Articles</th> </tr> <!-- PHP CODE TO FETCH DATA FROM ROWS --> <?php // LOOP TILL END OF DATA while($rows=$result->fetch_assoc()) { ?> <tr> <!-- FETCHING DATA FROM EACH ROW OF EVERY COLUMN --> <td><?php echo $rows['username'];?></td> <td><?php echo $rows['problems'];?></td> <td><?php echo $rows['score'];?></td> <td><?php echo $rows['articles'];?></td> </tr> <?php } ?> </table> </section></body> </html>
Output: Finally, you should be able to display the records in an HTML table by fetching them from the database.
output
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
hardikkoriintern
sanjyotpanure
CSS-Misc
HTML-Misc
PHP-Misc
CSS
HTML
PHP
PHP Programs
Web Technologies
Web technologies Questions
HTML
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet)
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jun, 2022"
},
{
"code": null,
"e": 158,
"s": 28,
"text": "In this article, we will see how we can display the records in an HTML table by fetching them from the MySQL database using PHP. "
},
{
"code": null,
"e": 286,
"s": 158,
"text": "Approach: Make sure you have XAMPP or WAMP server installed on your machine. In this article, we will be using the WAMP server."
},
{
"code": null,
"e": 921,
"s": 286,
"text": "WAMP Server is open-source software for the Microsoft Windows operating system, developed by Romain Bourdon. It is composed of an Apache web server, OpenSSL for SSL support, MySQL database and PHP programming language. Here, before going through the program, we need to create a MySQL database in our localhost server. Then, we are supposed to make an HTML table that is linked with PHP codes. PHP is used to connect with the localhost server and to fetch the data from the database table present in our localhost server by evaluating the MySQL queries. WAMP server helps to start Apache and MySQL and connect them with the PHP file. "
},
{
"code": null,
"e": 951,
"s": 921,
"text": "Follow the steps given below:"
},
{
"code": null,
"e": 1085,
"s": 951,
"text": "1. Creating Database: First, we will create a database named βgeeksforgeeksβ. You can use your existing database or create a new one."
},
{
"code": null,
"e": 1117,
"s": 1085,
"text": "create database βgeeksforgeeksβ"
},
{
"code": null,
"e": 1199,
"s": 1117,
"text": "2. Create Table: Create a table named βuserdataβ. The table contains four fields:"
},
{
"code": null,
"e": 1223,
"s": 1199,
"text": "username β varchar(100)"
},
{
"code": null,
"e": 1242,
"s": 1223,
"text": "problems β int(11)"
},
{
"code": null,
"e": 1258,
"s": 1242,
"text": "score β int(11)"
},
{
"code": null,
"e": 1277,
"s": 1258,
"text": "articles β int(11)"
},
{
"code": null,
"e": 1321,
"s": 1277,
"text": "Your table structure should look like this:"
},
{
"code": null,
"e": 1355,
"s": 1321,
"text": "the table structure of βuserdataβ"
},
{
"code": null,
"e": 1462,
"s": 1355,
"text": "Or you can create a table by copying and pasting the following code into the SQL panel of your PHPMyAdmin."
},
{
"code": null,
"e": 1663,
"s": 1462,
"text": "CREATE TABLE IF NOT EXISTS `userdata` (\n `username` varchar(100) NOT NULL,\n `problems` int(11) NOT NULL,\n `score` int(11) NOT NULL,\n `articles` int(11) NOT NULL\n) ENGINE=MyISAM DEFAULT CHARSET=latin1;"
},
{
"code": null,
"e": 1728,
"s": 1663,
"text": "To do this from the SQL panel refer to the following screenshot:"
},
{
"code": null,
"e": 1773,
"s": 1728,
"text": "create a table βuserdataβ from the SQL panel"
},
{
"code": null,
"e": 1900,
"s": 1773,
"text": "Insert records: We will now insert some records into our table. Here we are inserting 5 records. You can add multiple records."
},
{
"code": null,
"e": 1988,
"s": 1900,
"text": "Or copy and paste the following code into the SQL panel to insert records in the table."
},
{
"code": null,
"e": 2215,
"s": 1988,
"text": "INSERT INTO `userdata` \n(`username`, `problems`, `score`, `articles`) \nVALUES ('User-2', '100', '75', '30'), ('User-1', '150', '100', '30'), ('User-3', '200', '50', '10'), ('User-4', '50', '5', '2'), ('User-5', '0', '0', '1');"
},
{
"code": null,
"e": 2280,
"s": 2215,
"text": "To do this from the SQL panel refer to the following screenshot:"
},
{
"code": null,
"e": 2298,
"s": 2280,
"text": "inserting records"
},
{
"code": null,
"e": 2325,
"s": 2298,
"text": "Creating folder and files:"
},
{
"code": null,
"e": 2647,
"s": 2325,
"text": "We will now create our project folder named βGeeksForGeeksβ. Create an index.php file. Keep your main project folder (for example here.. GeeksForGeeks) in the βC://wamp64/www/β, if you are using WAMP or βC://xampp/htdocs/β folder if you are using the XAMPP server respectively. The folder structure should look like this:"
},
{
"code": null,
"e": 2664,
"s": 2647,
"text": "folder structure"
},
{
"code": null,
"e": 2829,
"s": 2664,
"text": "Now, we have a database named geeksforgeeks, and a table named userdata. Now, here is the PHP code to fetch data from the database and display it in an HTML table. "
},
{
"code": null,
"e": 2839,
"s": 2829,
"text": "Example: "
},
{
"code": null,
"e": 2843,
"s": 2839,
"text": "php"
},
{
"code": "<!-- PHP code to establish connection with the localserver --><?php // Username is root$user = 'root';$password = ''; // Database name is geeksforgeeks$database = 'geeksforgeeks'; // Server is localhost with// port number 3306$servername='localhost:3306';$mysqli = new mysqli($servername, $user, $password, $database); // Checking for connectionsif ($mysqli->connect_error) { die('Connect Error (' . $mysqli->connect_errno . ') '. $mysqli->connect_error);} // SQL query to select data from database$sql = \" SELECT * FROM userdata ORDER BY score DESC \";$result = $mysqli->query($sql);$mysqli->close();?><!-- HTML code to display data in tabular format --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>GFG User Details</title> <!-- CSS FOR STYLING THE PAGE --> <style> table { margin: 0 auto; font-size: large; border: 1px solid black; } h1 { text-align: center; color: #006600; font-size: xx-large; font-family: 'Gill Sans', 'Gill Sans MT', ' Calibri', 'Trebuchet MS', 'sans-serif'; } td { background-color: #E4F5D4; border: 1px solid black; } th, td { font-weight: bold; border: 1px solid black; padding: 10px; text-align: center; } td { font-weight: lighter; } </style></head> <body> <section> <h1>GeeksForGeeks</h1> <!-- TABLE CONSTRUCTION --> <table> <tr> <th>GFG UserHandle</th> <th>Practice Problems</th> <th>Coding Score</th> <th>GFG Articles</th> </tr> <!-- PHP CODE TO FETCH DATA FROM ROWS --> <?php // LOOP TILL END OF DATA while($rows=$result->fetch_assoc()) { ?> <tr> <!-- FETCHING DATA FROM EACH ROW OF EVERY COLUMN --> <td><?php echo $rows['username'];?></td> <td><?php echo $rows['problems'];?></td> <td><?php echo $rows['score'];?></td> <td><?php echo $rows['articles'];?></td> </tr> <?php } ?> </table> </section></body> </html>",
"e": 5243,
"s": 2843,
"text": null
},
{
"code": null,
"e": 5355,
"s": 5243,
"text": "Output: Finally, you should be able to display the records in an HTML table by fetching them from the database."
},
{
"code": null,
"e": 5362,
"s": 5355,
"text": "output"
},
{
"code": null,
"e": 5531,
"s": 5362,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 5548,
"s": 5531,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 5562,
"s": 5548,
"text": "sanjyotpanure"
},
{
"code": null,
"e": 5571,
"s": 5562,
"text": "CSS-Misc"
},
{
"code": null,
"e": 5581,
"s": 5571,
"text": "HTML-Misc"
},
{
"code": null,
"e": 5590,
"s": 5581,
"text": "PHP-Misc"
},
{
"code": null,
"e": 5594,
"s": 5590,
"text": "CSS"
},
{
"code": null,
"e": 5599,
"s": 5594,
"text": "HTML"
},
{
"code": null,
"e": 5603,
"s": 5599,
"text": "PHP"
},
{
"code": null,
"e": 5616,
"s": 5603,
"text": "PHP Programs"
},
{
"code": null,
"e": 5633,
"s": 5616,
"text": "Web Technologies"
},
{
"code": null,
"e": 5660,
"s": 5633,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 5665,
"s": 5660,
"text": "HTML"
},
{
"code": null,
"e": 5669,
"s": 5665,
"text": "PHP"
},
{
"code": null,
"e": 5767,
"s": 5669,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5804,
"s": 5767,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 5843,
"s": 5804,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 5882,
"s": 5843,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 5946,
"s": 5882,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 6007,
"s": 5946,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 6031,
"s": 6007,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 6084,
"s": 6031,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 6144,
"s": 6084,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 6205,
"s": 6144,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Maximum number of people that can be killed with strength P
|
30 May, 2022
There are infinite people standing in a row, indexed from 1. A person having index i has strength of i2. You have strength P and the task is to tell what is the maximum number of people you can kill with strength P. You can only kill a person with strength X if P β₯ X and after killing him, your strength decreases by X.
Examples:
Input: P = 14 Output: 3 Explaination: First person will have strength 12 = 1 which is < P P gets reduced to 13 after the first kill. Second kill, P = 13 β 22 = 9 Third kill, P = 9 β 32 = 0
Input: P = 58 Output: 5
Naive approach: Check every single kill starting from 1 until the strength P is greater than or equal to the strength of the person being killed.
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum number of people that can// be killedint maxPeople(int p){ int tmp = 0, count = 0; // Loop will break when the ith person cannot be killed for (int i = 1; i * i <= p; i++) { tmp = tmp + (i * i); if (tmp <= p) count++; else break; } return count;} // Driver codeint main(){ int p = 14; cout << maxPeople(p); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C implementation of the approach#include <stdio.h> // Function to return the maximum number of people that can// be killedint maxPeople(int p){ int tmp = 0, count = 0; // Loop will break when the ith person cannot be killed for (int i = 1; i * i <= p; i++) { tmp = tmp + (i * i); if (tmp <= p) count++; else break; } return count;} // Driver codeint main(){ int p = 14; printf("%d", maxPeople(p)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java implementation of the approachimport java.util.*; class GFG { // Function to return the maximum number of people that // can be killed static int maxPeople(int p) { int tmp = 0, count = 0; // Loop will break when the ith person cannot be // killed for (int i = 1; i * i <= p; i++) { tmp = tmp + (i * i); if (tmp <= p) count++; else break; } return count; } // Driver code public static void main(String args[]) { int p = 14; System.out.println(maxPeople(p)); }} // This code is contributed by Aditya Kumar (adityakumar129)
# Python3 implementation of the approach from math import sqrt # Function to return the maximum# number of people that can be killeddef maxPeople(p) : tmp = 0; count = 0; # Loop will break when the ith person # cannot be killed for i in range(1, int(sqrt(p)) + 1) : tmp = tmp + (i * i); if (tmp <= p) : count += 1; else : break; return count; # Driver codeif __name__ == "__main__" : p = 14; print(maxPeople(p)); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG{ // Function to return the maximum// number of people that can be killedstatic int maxPeople(int p){ int tmp = 0, count = 0; // Loop will break when the ith person // cannot be killed for (int i = 1; i * i <= p; i++) { tmp = tmp + (i * i); if (tmp <= p) count++; else break; } return count;} // Driver codepublic static void Main(){ int p = 14; Console.WriteLine(maxPeople(p));}} // This code is contributed by anuj_67..
<script> // javascript implementation of the approach // Function to return the maximum// number of people that can be killedfunction maxPeople(p){ var tmp = 0, count = 0; // Loop will break when the ith person // cannot be killed for (var i = 1; i * i <= p; i++) { tmp = tmp + (i * i); if (tmp <= p) count++; else break; } return count;} // Driver code var p = 14;document.write(maxPeople(p)); // This code is contributed by Amit Katiyar </script>
3
Time Complexity: O(sqrt(N)), where N is the initial strength.Auxiliary Space: O(1)
Efficient approach: We can see if we kill ith person then we have already killed (i β 1)th person. This means it is a monotonic function f whose domain is the set of integers. Now we can apply binary search on this monotonic function in which instead of array lookup we are now looking for some x such that f(x) is equal to the target value. Time complexity reduces to O(Log(n)).
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <algorithm>#include <bits/stdc++.h>using namespace std;#define ll long long static constexpr int kN = 1000000; // Function to return the maximum// number of people that can be killedint maxPeople(int p){ // Storing the sum beforehand so that // it can be used in each query ll sums[kN]; sums[0] = 0; for (int i = 1; i < kN; i++) sums[i] = (ll)(i * i) + sums[i - 1]; // lower_bound returns an iterator pointing to the // first element greater than or equal to your val auto it = std::lower_bound(sums, sums + kN, p); if (*it > p) { // Previous value --it; } // Returns the index in array upto which // killing is possible with strength P return (it - sums);} // Driver codeint main(){ int p = 14; cout << maxPeople(p); return 0;}
// Java implementation of the approachclass GFG{ static int kN = 1000000; // Function to return the maximum// number of people that can be killedstatic int maxPeople(int p){ // Storing the sum beforehand so that // it can be used in each query long []sums = new long[kN]; sums[0] = 0; for (int i = 1; i < kN; i++) sums[i] = (long)(i * i) + sums[i - 1]; // lower_bound returns an iterator pointing to the // first element greater than or equal to your val int it = lower_bound(sums, 0, kN, p); if (sums[it] > p) { // Previous value --it; } // Returns the index in array upto which // killing is possible with strength P return it;}private static int lower_bound(long[] a, int low, int high, int element){ while(low < high) { int middle = low + (high - low)/2; if(element > a[middle]) low = middle + 1; else high = middle; } return low;} // Driver codepublic static void main(String[] args){ int p = 14; System.out.println(maxPeople(p));}} /* This code is contributed by PrinciRaj1992 */
# Python3 implementation of the approachkN = 1000000; # Function to return the maximum# number of people that can be killeddef maxPeople(p): # Storing the sum beforehand so that # it can be used in each query sums = [0] * kN; sums[0] = 0; for i in range(1, kN): sums[i] = (i * i) + sums[i - 1]; # lower_bound returns an iterator # pointing to the first element # greater than or equal to your val it = lower_bound(sums, 0, kN, p); if (it > p): # Previous value it -= 1; # Returns the index in array upto which # killing is possible with strength P return it; def lower_bound(a, low, high, element): while(low < high): middle = int(low + (high - low) / 2); if(element > a[middle]): low = middle + 1; else: high = middle; return low; # Driver codeif __name__ == '__main__': p = 14; print(maxPeople(p)); # This code contributed by Rajput-Ji
// C# implementation of the approachusing System; public class GFG{ static int kN = 1000000; // Function to return the maximum// number of people that can be killedstatic int maxPeople(int p){ // Storing the sum beforehand so that // it can be used in each query long []sums = new long[kN]; sums[0] = 0; for (int i = 1; i < kN; i++) sums[i] = (long)(i * i) + sums[i - 1]; // lower_bound returns an iterator pointing to the // first element greater than or equal to your val int it = lower_bound(sums, 0, kN, p); if (it > p) { // Previous value --it; } // Returns the index in array upto which // killing is possible with strength P return it;}private static int lower_bound(long[] a, int low, int high, int element){ while(low < high) { int middle = low + (high - low)/2; if(element > a[middle]) low = middle + 1; else high = middle; } return low;} // Driver codepublic static void Main(String[] args){ int p = 14; Console.WriteLine(maxPeople(p));}} // This code has been contributed by 29AjayKumar
<script>// Javascript implementation of the approach const kN = 1000000; // Function to return the maximum// number of people that can be killedfunction maxPeople(p){ // Storing the sum beforehand so that // it can be used in each query let sums = new Array(kN); sums[0] = 0; for (let i = 1; i < kN; i++) sums[i] = (i * i) + sums[i - 1]; // lower_bound returns an iterator pointing to the // first element greater than or equal to your val let it = lower_bound(sums, 0, kN, p); if (it > p) { // Previous value --it; } // Returns the index in array upto which // killing is possible with strength P return it;} function lower_bound(a, low, high, element){ while(low < high) { let middle = low + parseInt((high - low)/2); if(element > a[middle]) low = middle + 1; else high = middle; } return low;} // Driver code let p = 14; document.write(maxPeople(p)); </script>
3
Time Complexity: O(1000000)
Auxiliary Space: O(1000000)
More Efficient Approach : We can do the same problem in time complexity O(logn) and Space Complexity in O(1). Start your binary search by considering the value of low as 0 and high as 10^15. We will calculate the mid-value and according to mid, we will change the position of low and high.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <algorithm>#include <bits/stdc++.h>using namespace std; // Helper function which returns the sum// of series (1^2 + 2^2 +...+ n^2)long squareSeries(long n){ return(n * (n + 1) * (2 * n + 1)) / 6;} // maxPeople function which returns// appropriate value using Binary Search// in O(logn)long maxPeople(long n){ // Set the lower and higher values long low = 0; long high = 1000000L; long ans = 0L; while (low <= high) { // Calculate the mid using // low and high long mid = low + ((high - low) / 2); long value = squareSeries(mid); // Compare value with n if (value <= n) { ans = mid; low = mid + 1; } else { high = mid - 1; } } // Return the ans return ans;} // Driver codeint main(){ long p = 14; cout<<maxPeople(p); return 0;} // This code contributed by shikhasingrajput
// Java implementation of the approachclass GFG{ // Helper function which returns the sum// of series (1^2 + 2^2 +...+ n^2)static long squareSeries(long n){ return(n * (n + 1) * (2 * n + 1)) / 6;} // maxPeople function which returns// appropriate value using Binary Search// in O(logn)static long maxPeople(long n){ // Set the lower and higher values long low = 0; long high = 1000000L; long ans = 0L; while (low <= high) { // Calculate the mid using // low and high long mid = low + ((high - low) / 2); long value = squareSeries(mid); // Compare value with n if (value <= n) { ans = mid; low = mid + 1; } else { high = mid - 1; } } // Return the ans return ans;} // Driver codepublic static void main(String[] args){ long p = 14; System.out.println(maxPeople(p));}} // This code is contributed by 29AjayKumar
# Python3 implementation of the approach # helper function which returns the sum# of series (1^2 + 2^2 +...+ n^2)def squareSeries(n): return (n*(n+1)*(2*n+1))//6 # maxPeople function which returns# appropriate value using Binary Search# in O(logn) def maxPeople(n): # Set the lower and higher values low = 0 high = 1000000000000000 while low<=high: # calculate the mid using # low and high mid = low + ((high-low)//2) value = squareSeries(mid) #compare value with n if value<=n: ans = mid low = mid+1 else: high = mid-1 # return the ans return ans if __name__=='__main__': p=14 print(maxPeople(p)) # This code is contributed bu chaudhary_19# (* Mayank Chaudhary)
// C# implementation of the approachusing System; class GFG{ // Helper function which returns the sum// of series (1^2 + 2^2 +...+ n^2)static long squareSeries(long n){ return(n * (n + 1) * (2 * n + 1)) / 6;} // maxPeople function which returns// appropriate value using Binary Search// in O(logn)static long maxPeople(long n){ // Set the lower and higher values long low = 0; long high = 1000000L; long ans = 0L; while (low <= high) { // Calculate the mid using // low and high long mid = low + ((high - low) / 2); long value = squareSeries(mid); // Compare value with n if (value <= n) { ans = mid; low = mid + 1; } else { high = mid - 1; } } // Return the ans return ans;} // Driver codepublic static void Main(String[] args){ long p = 14; Console.Write(maxPeople(p));}} // This code is contributed by shivanisinghss2110
<script>// Javascript implementation of the approach // Helper function which returns the sum// of series (1^2 + 2^2 +...+ n^2)function squareSeries(n){ return Math.floor((n * (n + 1) * (2 * n + 1)) / 6);} // maxPeople function which returns// appropriate value using Binary Search// in O(logn)function maxPeople(n){ // Set the lower and higher values let low = 0; let high = 1000000; let ans = 0; while (low <= high) { // Calculate the mid using // low and high let mid = low + Math.floor((high - low) / 2); let value = squareSeries(mid); // Compare value with n if (value <= n) { ans = mid; low = mid + 1; } else { high = mid - 1; } } // Return the ans return ans;} // Driver codelet p = 14; document.write(maxPeople(p)); // This code is contributed by avanitrachhadiya2155</script>
3
Time Complexity: O(Log(1000000)) Auxiliary Space: O(1)
andrew1234
vt_m
ankthon
princiraj1992
29AjayKumar
Rajput-Ji
chaudhary_19
ishita081
amit143katiyar
subham348
ayush71994
shivanisinghss2110
avanitrachhadiya2155
shikhasingrajput
harendrakumar123
adityakumar129
vansikasharma1329
Constructive Algorithms
Natural Numbers
Numbers
Mathematical
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 May, 2022"
},
{
"code": null,
"e": 376,
"s": 54,
"text": "There are infinite people standing in a row, indexed from 1. A person having index i has strength of i2. You have strength P and the task is to tell what is the maximum number of people you can kill with strength P. You can only kill a person with strength X if P β₯ X and after killing him, your strength decreases by X. "
},
{
"code": null,
"e": 387,
"s": 376,
"text": "Examples: "
},
{
"code": null,
"e": 576,
"s": 387,
"text": "Input: P = 14 Output: 3 Explaination: First person will have strength 12 = 1 which is < P P gets reduced to 13 after the first kill. Second kill, P = 13 β 22 = 9 Third kill, P = 9 β 32 = 0"
},
{
"code": null,
"e": 601,
"s": 576,
"text": "Input: P = 58 Output: 5 "
},
{
"code": null,
"e": 747,
"s": 601,
"text": "Naive approach: Check every single kill starting from 1 until the strength P is greater than or equal to the strength of the person being killed."
},
{
"code": null,
"e": 800,
"s": 747,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 804,
"s": 800,
"text": "C++"
},
{
"code": null,
"e": 806,
"s": 804,
"text": "C"
},
{
"code": null,
"e": 811,
"s": 806,
"text": "Java"
},
{
"code": null,
"e": 819,
"s": 811,
"text": "Python3"
},
{
"code": null,
"e": 822,
"s": 819,
"text": "C#"
},
{
"code": null,
"e": 833,
"s": 822,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum number of people that can// be killedint maxPeople(int p){ int tmp = 0, count = 0; // Loop will break when the ith person cannot be killed for (int i = 1; i * i <= p; i++) { tmp = tmp + (i * i); if (tmp <= p) count++; else break; } return count;} // Driver codeint main(){ int p = 14; cout << maxPeople(p); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 1397,
"s": 833,
"text": null
},
{
"code": "// C implementation of the approach#include <stdio.h> // Function to return the maximum number of people that can// be killedint maxPeople(int p){ int tmp = 0, count = 0; // Loop will break when the ith person cannot be killed for (int i = 1; i * i <= p; i++) { tmp = tmp + (i * i); if (tmp <= p) count++; else break; } return count;} // Driver codeint main(){ int p = 14; printf(\"%d\", maxPeople(p)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 1939,
"s": 1397,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG { // Function to return the maximum number of people that // can be killed static int maxPeople(int p) { int tmp = 0, count = 0; // Loop will break when the ith person cannot be // killed for (int i = 1; i * i <= p; i++) { tmp = tmp + (i * i); if (tmp <= p) count++; else break; } return count; } // Driver code public static void main(String args[]) { int p = 14; System.out.println(maxPeople(p)); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 2618,
"s": 1939,
"text": null
},
{
"code": "# Python3 implementation of the approach from math import sqrt # Function to return the maximum# number of people that can be killeddef maxPeople(p) : tmp = 0; count = 0; # Loop will break when the ith person # cannot be killed for i in range(1, int(sqrt(p)) + 1) : tmp = tmp + (i * i); if (tmp <= p) : count += 1; else : break; return count; # Driver codeif __name__ == \"__main__\" : p = 14; print(maxPeople(p)); # This code is contributed by AnkitRai01",
"e": 3153,
"s": 2618,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the maximum// number of people that can be killedstatic int maxPeople(int p){ int tmp = 0, count = 0; // Loop will break when the ith person // cannot be killed for (int i = 1; i * i <= p; i++) { tmp = tmp + (i * i); if (tmp <= p) count++; else break; } return count;} // Driver codepublic static void Main(){ int p = 14; Console.WriteLine(maxPeople(p));}} // This code is contributed by anuj_67..",
"e": 3709,
"s": 3153,
"text": null
},
{
"code": "<script> // javascript implementation of the approach // Function to return the maximum// number of people that can be killedfunction maxPeople(p){ var tmp = 0, count = 0; // Loop will break when the ith person // cannot be killed for (var i = 1; i * i <= p; i++) { tmp = tmp + (i * i); if (tmp <= p) count++; else break; } return count;} // Driver code var p = 14;document.write(maxPeople(p)); // This code is contributed by Amit Katiyar </script>",
"e": 4225,
"s": 3709,
"text": null
},
{
"code": null,
"e": 4227,
"s": 4225,
"text": "3"
},
{
"code": null,
"e": 4310,
"s": 4227,
"text": "Time Complexity: O(sqrt(N)), where N is the initial strength.Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4690,
"s": 4310,
"text": "Efficient approach: We can see if we kill ith person then we have already killed (i β 1)th person. This means it is a monotonic function f whose domain is the set of integers. Now we can apply binary search on this monotonic function in which instead of array lookup we are now looking for some x such that f(x) is equal to the target value. Time complexity reduces to O(Log(n))."
},
{
"code": null,
"e": 4743,
"s": 4690,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 4747,
"s": 4743,
"text": "C++"
},
{
"code": null,
"e": 4752,
"s": 4747,
"text": "Java"
},
{
"code": null,
"e": 4760,
"s": 4752,
"text": "Python3"
},
{
"code": null,
"e": 4763,
"s": 4760,
"text": "C#"
},
{
"code": null,
"e": 4774,
"s": 4763,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <algorithm>#include <bits/stdc++.h>using namespace std;#define ll long long static constexpr int kN = 1000000; // Function to return the maximum// number of people that can be killedint maxPeople(int p){ // Storing the sum beforehand so that // it can be used in each query ll sums[kN]; sums[0] = 0; for (int i = 1; i < kN; i++) sums[i] = (ll)(i * i) + sums[i - 1]; // lower_bound returns an iterator pointing to the // first element greater than or equal to your val auto it = std::lower_bound(sums, sums + kN, p); if (*it > p) { // Previous value --it; } // Returns the index in array upto which // killing is possible with strength P return (it - sums);} // Driver codeint main(){ int p = 14; cout << maxPeople(p); return 0;}",
"e": 5622,
"s": 4774,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ static int kN = 1000000; // Function to return the maximum// number of people that can be killedstatic int maxPeople(int p){ // Storing the sum beforehand so that // it can be used in each query long []sums = new long[kN]; sums[0] = 0; for (int i = 1; i < kN; i++) sums[i] = (long)(i * i) + sums[i - 1]; // lower_bound returns an iterator pointing to the // first element greater than or equal to your val int it = lower_bound(sums, 0, kN, p); if (sums[it] > p) { // Previous value --it; } // Returns the index in array upto which // killing is possible with strength P return it;}private static int lower_bound(long[] a, int low, int high, int element){ while(low < high) { int middle = low + (high - low)/2; if(element > a[middle]) low = middle + 1; else high = middle; } return low;} // Driver codepublic static void main(String[] args){ int p = 14; System.out.println(maxPeople(p));}} /* This code is contributed by PrinciRaj1992 */",
"e": 6762,
"s": 5622,
"text": null
},
{
"code": "# Python3 implementation of the approachkN = 1000000; # Function to return the maximum# number of people that can be killeddef maxPeople(p): # Storing the sum beforehand so that # it can be used in each query sums = [0] * kN; sums[0] = 0; for i in range(1, kN): sums[i] = (i * i) + sums[i - 1]; # lower_bound returns an iterator # pointing to the first element # greater than or equal to your val it = lower_bound(sums, 0, kN, p); if (it > p): # Previous value it -= 1; # Returns the index in array upto which # killing is possible with strength P return it; def lower_bound(a, low, high, element): while(low < high): middle = int(low + (high - low) / 2); if(element > a[middle]): low = middle + 1; else: high = middle; return low; # Driver codeif __name__ == '__main__': p = 14; print(maxPeople(p)); # This code contributed by Rajput-Ji",
"e": 7719,
"s": 6762,
"text": null
},
{
"code": "// C# implementation of the approachusing System; public class GFG{ static int kN = 1000000; // Function to return the maximum// number of people that can be killedstatic int maxPeople(int p){ // Storing the sum beforehand so that // it can be used in each query long []sums = new long[kN]; sums[0] = 0; for (int i = 1; i < kN; i++) sums[i] = (long)(i * i) + sums[i - 1]; // lower_bound returns an iterator pointing to the // first element greater than or equal to your val int it = lower_bound(sums, 0, kN, p); if (it > p) { // Previous value --it; } // Returns the index in array upto which // killing is possible with strength P return it;}private static int lower_bound(long[] a, int low, int high, int element){ while(low < high) { int middle = low + (high - low)/2; if(element > a[middle]) low = middle + 1; else high = middle; } return low;} // Driver codepublic static void Main(String[] args){ int p = 14; Console.WriteLine(maxPeople(p));}} // This code has been contributed by 29AjayKumar",
"e": 8880,
"s": 7719,
"text": null
},
{
"code": "<script>// Javascript implementation of the approach const kN = 1000000; // Function to return the maximum// number of people that can be killedfunction maxPeople(p){ // Storing the sum beforehand so that // it can be used in each query let sums = new Array(kN); sums[0] = 0; for (let i = 1; i < kN; i++) sums[i] = (i * i) + sums[i - 1]; // lower_bound returns an iterator pointing to the // first element greater than or equal to your val let it = lower_bound(sums, 0, kN, p); if (it > p) { // Previous value --it; } // Returns the index in array upto which // killing is possible with strength P return it;} function lower_bound(a, low, high, element){ while(low < high) { let middle = low + parseInt((high - low)/2); if(element > a[middle]) low = middle + 1; else high = middle; } return low;} // Driver code let p = 14; document.write(maxPeople(p)); </script>",
"e": 9868,
"s": 8880,
"text": null
},
{
"code": null,
"e": 9870,
"s": 9868,
"text": "3"
},
{
"code": null,
"e": 9898,
"s": 9870,
"text": "Time Complexity: O(1000000)"
},
{
"code": null,
"e": 9926,
"s": 9898,
"text": "Auxiliary Space: O(1000000)"
},
{
"code": null,
"e": 10217,
"s": 9926,
"text": "More Efficient Approach : We can do the same problem in time complexity O(logn) and Space Complexity in O(1). Start your binary search by considering the value of low as 0 and high as 10^15. We will calculate the mid-value and according to mid, we will change the position of low and high. "
},
{
"code": null,
"e": 10269,
"s": 10217,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 10273,
"s": 10269,
"text": "C++"
},
{
"code": null,
"e": 10278,
"s": 10273,
"text": "Java"
},
{
"code": null,
"e": 10286,
"s": 10278,
"text": "Python3"
},
{
"code": null,
"e": 10289,
"s": 10286,
"text": "C#"
},
{
"code": null,
"e": 10300,
"s": 10289,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <algorithm>#include <bits/stdc++.h>using namespace std; // Helper function which returns the sum// of series (1^2 + 2^2 +...+ n^2)long squareSeries(long n){ return(n * (n + 1) * (2 * n + 1)) / 6;} // maxPeople function which returns// appropriate value using Binary Search// in O(logn)long maxPeople(long n){ // Set the lower and higher values long low = 0; long high = 1000000L; long ans = 0L; while (low <= high) { // Calculate the mid using // low and high long mid = low + ((high - low) / 2); long value = squareSeries(mid); // Compare value with n if (value <= n) { ans = mid; low = mid + 1; } else { high = mid - 1; } } // Return the ans return ans;} // Driver codeint main(){ long p = 14; cout<<maxPeople(p); return 0;} // This code contributed by shikhasingrajput",
"e": 11302,
"s": 10300,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Helper function which returns the sum// of series (1^2 + 2^2 +...+ n^2)static long squareSeries(long n){ return(n * (n + 1) * (2 * n + 1)) / 6;} // maxPeople function which returns// appropriate value using Binary Search// in O(logn)static long maxPeople(long n){ // Set the lower and higher values long low = 0; long high = 1000000L; long ans = 0L; while (low <= high) { // Calculate the mid using // low and high long mid = low + ((high - low) / 2); long value = squareSeries(mid); // Compare value with n if (value <= n) { ans = mid; low = mid + 1; } else { high = mid - 1; } } // Return the ans return ans;} // Driver codepublic static void main(String[] args){ long p = 14; System.out.println(maxPeople(p));}} // This code is contributed by 29AjayKumar",
"e": 12292,
"s": 11302,
"text": null
},
{
"code": "# Python3 implementation of the approach # helper function which returns the sum# of series (1^2 + 2^2 +...+ n^2)def squareSeries(n): return (n*(n+1)*(2*n+1))//6 # maxPeople function which returns# appropriate value using Binary Search# in O(logn) def maxPeople(n): # Set the lower and higher values low = 0 high = 1000000000000000 while low<=high: # calculate the mid using # low and high mid = low + ((high-low)//2) value = squareSeries(mid) #compare value with n if value<=n: ans = mid low = mid+1 else: high = mid-1 # return the ans return ans if __name__=='__main__': p=14 print(maxPeople(p)) # This code is contributed bu chaudhary_19# (* Mayank Chaudhary)",
"e": 13069,
"s": 12292,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Helper function which returns the sum// of series (1^2 + 2^2 +...+ n^2)static long squareSeries(long n){ return(n * (n + 1) * (2 * n + 1)) / 6;} // maxPeople function which returns// appropriate value using Binary Search// in O(logn)static long maxPeople(long n){ // Set the lower and higher values long low = 0; long high = 1000000L; long ans = 0L; while (low <= high) { // Calculate the mid using // low and high long mid = low + ((high - low) / 2); long value = squareSeries(mid); // Compare value with n if (value <= n) { ans = mid; low = mid + 1; } else { high = mid - 1; } } // Return the ans return ans;} // Driver codepublic static void Main(String[] args){ long p = 14; Console.Write(maxPeople(p));}} // This code is contributed by shivanisinghss2110",
"e": 14073,
"s": 13069,
"text": null
},
{
"code": "<script>// Javascript implementation of the approach // Helper function which returns the sum// of series (1^2 + 2^2 +...+ n^2)function squareSeries(n){ return Math.floor((n * (n + 1) * (2 * n + 1)) / 6);} // maxPeople function which returns// appropriate value using Binary Search// in O(logn)function maxPeople(n){ // Set the lower and higher values let low = 0; let high = 1000000; let ans = 0; while (low <= high) { // Calculate the mid using // low and high let mid = low + Math.floor((high - low) / 2); let value = squareSeries(mid); // Compare value with n if (value <= n) { ans = mid; low = mid + 1; } else { high = mid - 1; } } // Return the ans return ans;} // Driver codelet p = 14; document.write(maxPeople(p)); // This code is contributed by avanitrachhadiya2155</script>",
"e": 15023,
"s": 14073,
"text": null
},
{
"code": null,
"e": 15025,
"s": 15023,
"text": "3"
},
{
"code": null,
"e": 15081,
"s": 15025,
"text": "Time Complexity: O(Log(1000000)) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 15092,
"s": 15081,
"text": "andrew1234"
},
{
"code": null,
"e": 15097,
"s": 15092,
"text": "vt_m"
},
{
"code": null,
"e": 15105,
"s": 15097,
"text": "ankthon"
},
{
"code": null,
"e": 15119,
"s": 15105,
"text": "princiraj1992"
},
{
"code": null,
"e": 15131,
"s": 15119,
"text": "29AjayKumar"
},
{
"code": null,
"e": 15141,
"s": 15131,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 15154,
"s": 15141,
"text": "chaudhary_19"
},
{
"code": null,
"e": 15164,
"s": 15154,
"text": "ishita081"
},
{
"code": null,
"e": 15179,
"s": 15164,
"text": "amit143katiyar"
},
{
"code": null,
"e": 15189,
"s": 15179,
"text": "subham348"
},
{
"code": null,
"e": 15200,
"s": 15189,
"text": "ayush71994"
},
{
"code": null,
"e": 15219,
"s": 15200,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 15240,
"s": 15219,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 15257,
"s": 15240,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 15274,
"s": 15257,
"text": "harendrakumar123"
},
{
"code": null,
"e": 15289,
"s": 15274,
"text": "adityakumar129"
},
{
"code": null,
"e": 15307,
"s": 15289,
"text": "vansikasharma1329"
},
{
"code": null,
"e": 15331,
"s": 15307,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 15347,
"s": 15331,
"text": "Natural Numbers"
},
{
"code": null,
"e": 15355,
"s": 15347,
"text": "Numbers"
},
{
"code": null,
"e": 15368,
"s": 15355,
"text": "Mathematical"
},
{
"code": null,
"e": 15381,
"s": 15368,
"text": "Mathematical"
},
{
"code": null,
"e": 15389,
"s": 15381,
"text": "Numbers"
}
] |
jQuery | disable/enable an input element
|
28 Mar, 2019
The disable/enable an input element in jQuery can be done by using prop() method. The prop() method is used to set or return properties and values for the selected elements.
Example 1: This example uses prop() method to disable the input text field.
<!DOCTYPE html> <html> <head> <title> JavaScript enable/disable an input element </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <input id = "input" type="text" name="input"/> <button onclick="enable_disable()"> Enable/Disable </button> <!-- Script to disable input text area --> <script> function enable_disable() { $("input").prop('disabled', true); } </script> </body> </html>
Output:
Before clicking the button:
After clicking the button:
Example 2: This example uses prop() method to enable the input text field.
<!DOCTYPE html> <html> <head> <title> JavaScript enable/disable an input element </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <input id = "input" type="text" name="input" disabled/> <button onclick="enable_disable()"> Enable/Disable </button> <!-- Script to enable input text fields --> <script> function enable_disable() { $("input").prop('disabled', false); } </script> </body> </html>
Output:
Before clicking the button:
After clicking the button:
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Mar, 2019"
},
{
"code": null,
"e": 202,
"s": 28,
"text": "The disable/enable an input element in jQuery can be done by using prop() method. The prop() method is used to set or return properties and values for the selected elements."
},
{
"code": null,
"e": 278,
"s": 202,
"text": "Example 1: This example uses prop() method to disable the input text field."
},
{
"code": "<!DOCTYPE html> <html> <head> <title> JavaScript enable/disable an input element </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <input id = \"input\" type=\"text\" name=\"input\"/> <button onclick=\"enable_disable()\"> Enable/Disable </button> <!-- Script to disable input text area --> <script> function enable_disable() { $(\"input\").prop('disabled', true); } </script> </body> </html>",
"e": 963,
"s": 278,
"text": null
},
{
"code": null,
"e": 971,
"s": 963,
"text": "Output:"
},
{
"code": null,
"e": 999,
"s": 971,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 1026,
"s": 999,
"text": "After clicking the button:"
},
{
"code": null,
"e": 1101,
"s": 1026,
"text": "Example 2: This example uses prop() method to enable the input text field."
},
{
"code": "<!DOCTYPE html> <html> <head> <title> JavaScript enable/disable an input element </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <input id = \"input\" type=\"text\" name=\"input\" disabled/> <button onclick=\"enable_disable()\"> Enable/Disable </button> <!-- Script to enable input text fields --> <script> function enable_disable() { $(\"input\").prop('disabled', false); } </script> </body> </html>",
"e": 1787,
"s": 1101,
"text": null
},
{
"code": null,
"e": 1795,
"s": 1787,
"text": "Output:"
},
{
"code": null,
"e": 1823,
"s": 1795,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 1850,
"s": 1823,
"text": "After clicking the button:"
},
{
"code": null,
"e": 1857,
"s": 1850,
"text": "JQuery"
},
{
"code": null,
"e": 1874,
"s": 1857,
"text": "Web Technologies"
},
{
"code": null,
"e": 1901,
"s": 1874,
"text": "Web technologies Questions"
}
] |
Overriding the save method β Django Models
|
09 Jul, 2021
The save method is an inherited method from models.Model which is executed to save an instance into a particular Model. Whenever one tries to create an instance of a model either from admin interface or django shell, save() function is run. We can override save function before storing the data in the database to apply some constraint or fill some ready only fields like SlugField. Technically it is not recommended to override the save method to implement such functionalities because any error in save method lets to crash of whole database. So either if you are perfect at writing save method and error handling or donβt try save method and try to implement these functionalities either in forms, views, models, etc.
Illustration of overriding the save method using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into models.py file of geeks app. We will be using CharField for experimenting for all field options. We will override the save method to fill up the SlugField automatically.
Python3
from django.db import models # importing slugify from djangofrom django.utils.text import slugify # Create your models here.class GeeksModel(models.Model): title = models.CharField(max_length = 200) slug = models.SlugField() def save(self, *args, **kwargs): self.slug = slugify(self.title) super(GeeksModel, self).save(*args, **kwargs)
Let us explain what happens in above code. save() method from its parent class is to be overridden so we use super keyword. slugify is a function that converts any string into a slug. so we are converting the title to form a slug basically. Let us try to create an instance with βGfg is the best websiteβ.
Let us check what we have created in admin interface.
As defined in the starting of this article it is often not recommended to override the save method. Let us check why? The above code recreates the slug every time the save method is used or if any change is done to the model. The second reason is if one needs to change the title only but not slug since slug is redirecting to a particular link and is ranking on some search engine. A great issue would be created in a production server. This makes the use of this method of validation unfortunately incorrect. There can be multiple ways to solve above problem, one can declare slug as read-only field and then before making any changes to slug in overridden method we can check if it is empty. This may resolve the problem. So as recommended until you are able to handle errors in save method, donβt override it.
sweetyty
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 776,
"s": 54,
"text": "The save method is an inherited method from models.Model which is executed to save an instance into a particular Model. Whenever one tries to create an instance of a model either from admin interface or django shell, save() function is run. We can override save function before storing the data in the database to apply some constraint or fill some ready only fields like SlugField. Technically it is not recommended to override the save method to implement such functionalities because any error in save method lets to crash of whole database. So either if you are perfect at writing save method and error handling or donβt try save method and try to implement these functionalities either in forms, views, models, etc. "
},
{
"code": null,
"e": 905,
"s": 776,
"text": "Illustration of overriding the save method using an Example. Consider a project named geeksforgeeks having an app named geeks. "
},
{
"code": null,
"e": 994,
"s": 905,
"text": "Refer to the following articles to check how to create a project and an app in Django. "
},
{
"code": null,
"e": 1045,
"s": 994,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 1078,
"s": 1045,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 1280,
"s": 1078,
"text": "Enter the following code into models.py file of geeks app. We will be using CharField for experimenting for all field options. We will override the save method to fill up the SlugField automatically. "
},
{
"code": null,
"e": 1288,
"s": 1280,
"text": "Python3"
},
{
"code": "from django.db import models # importing slugify from djangofrom django.utils.text import slugify # Create your models here.class GeeksModel(models.Model): title = models.CharField(max_length = 200) slug = models.SlugField() def save(self, *args, **kwargs): self.slug = slugify(self.title) super(GeeksModel, self).save(*args, **kwargs)",
"e": 1648,
"s": 1288,
"text": null
},
{
"code": null,
"e": 1956,
"s": 1648,
"text": "Let us explain what happens in above code. save() method from its parent class is to be overridden so we use super keyword. slugify is a function that converts any string into a slug. so we are converting the title to form a slug basically. Let us try to create an instance with βGfg is the best websiteβ. "
},
{
"code": null,
"e": 2012,
"s": 1956,
"text": "Let us check what we have created in admin interface. "
},
{
"code": null,
"e": 2829,
"s": 2014,
"text": "As defined in the starting of this article it is often not recommended to override the save method. Let us check why? The above code recreates the slug every time the save method is used or if any change is done to the model. The second reason is if one needs to change the title only but not slug since slug is redirecting to a particular link and is ranking on some search engine. A great issue would be created in a production server. This makes the use of this method of validation unfortunately incorrect. There can be multiple ways to solve above problem, one can declare slug as read-only field and then before making any changes to slug in overridden method we can check if it is empty. This may resolve the problem. So as recommended until you are able to handle errors in save method, donβt override it. "
},
{
"code": null,
"e": 2838,
"s": 2829,
"text": "sweetyty"
},
{
"code": null,
"e": 2852,
"s": 2838,
"text": "Django-models"
},
{
"code": null,
"e": 2866,
"s": 2852,
"text": "Python Django"
},
{
"code": null,
"e": 2873,
"s": 2866,
"text": "Python"
}
] |
Difference between Console.Read and Console.ReadLine in C#
|
05 Apr, 2022
In C#, to take input from the standard input device, the following method are used β Console.Read() and Console.ReadLine() method. Console is a predefined class of System namespace. While Read() and ReadLine() both are the Console Class methods.
The only difference between the Read() and ReadLine() is that Console.Read is used to read only single character from the standard output device, while Console.ReadLine is used to read a line or string from the standard output device.
Program 1: Example of Console.Read() in C#.
C#
// C# program to show the difference// between Console.Read() and// Console.ReadLine() method using System; public class GFG{ static void Main(string[] args) { // use of Read() method Console.Write(Convert.ToChar(Console.Read())); Console.Write(Convert.ToChar(Console.Read())); Console.Write(Convert.ToChar(Console.Read())); }}
Input:
Geeks
Output:
Gee
Program 2: Example of Console.ReadLine() in C#.
C#
// C# program to show the difference// between Console.Read() and// Console.ReadLine() method using System; public class GFG{ static void Main(string[] args) { // use of ReadLine() method Console.Write(Console.ReadLine()); Console.Write(Console.ReadLine()); Console.Write(Console.ReadLine()); }}
Input:
Geeks
For
Geeks
Output:
GeeksForGeeks
In the above code, program 1 shows that it will read only single character and program 2 shows it will read string until new line character is not found.
Let us see the differences in Tabular Form -:
Its syntax is -:
public static int Read ();
Its syntax is -:
public static string ReadLine ();
mayank007rawa
C#
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Apr, 2022"
},
{
"code": null,
"e": 274,
"s": 28,
"text": "In C#, to take input from the standard input device, the following method are used β Console.Read() and Console.ReadLine() method. Console is a predefined class of System namespace. While Read() and ReadLine() both are the Console Class methods."
},
{
"code": null,
"e": 509,
"s": 274,
"text": "The only difference between the Read() and ReadLine() is that Console.Read is used to read only single character from the standard output device, while Console.ReadLine is used to read a line or string from the standard output device."
},
{
"code": null,
"e": 553,
"s": 509,
"text": "Program 1: Example of Console.Read() in C#."
},
{
"code": null,
"e": 556,
"s": 553,
"text": "C#"
},
{
"code": "// C# program to show the difference// between Console.Read() and// Console.ReadLine() method using System; public class GFG{ static void Main(string[] args) { // use of Read() method Console.Write(Convert.ToChar(Console.Read())); Console.Write(Convert.ToChar(Console.Read())); Console.Write(Convert.ToChar(Console.Read())); }}",
"e": 926,
"s": 556,
"text": null
},
{
"code": null,
"e": 933,
"s": 926,
"text": "Input:"
},
{
"code": null,
"e": 939,
"s": 933,
"text": "Geeks"
},
{
"code": null,
"e": 947,
"s": 939,
"text": "Output:"
},
{
"code": null,
"e": 951,
"s": 947,
"text": "Gee"
},
{
"code": null,
"e": 999,
"s": 951,
"text": "Program 2: Example of Console.ReadLine() in C#."
},
{
"code": null,
"e": 1002,
"s": 999,
"text": "C#"
},
{
"code": "// C# program to show the difference// between Console.Read() and// Console.ReadLine() method using System; public class GFG{ static void Main(string[] args) { // use of ReadLine() method Console.Write(Console.ReadLine()); Console.Write(Console.ReadLine()); Console.Write(Console.ReadLine()); }}",
"e": 1340,
"s": 1002,
"text": null
},
{
"code": null,
"e": 1347,
"s": 1340,
"text": "Input:"
},
{
"code": null,
"e": 1363,
"s": 1347,
"text": "Geeks\nFor\nGeeks"
},
{
"code": null,
"e": 1371,
"s": 1363,
"text": "Output:"
},
{
"code": null,
"e": 1385,
"s": 1371,
"text": "GeeksForGeeks"
},
{
"code": null,
"e": 1539,
"s": 1385,
"text": "In the above code, program 1 shows that it will read only single character and program 2 shows it will read string until new line character is not found."
},
{
"code": null,
"e": 1585,
"s": 1539,
"text": "Let us see the differences in Tabular Form -:"
},
{
"code": null,
"e": 1602,
"s": 1585,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 1629,
"s": 1602,
"text": "public static int Read ();"
},
{
"code": null,
"e": 1646,
"s": 1629,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 1680,
"s": 1646,
"text": "public static string ReadLine ();"
},
{
"code": null,
"e": 1694,
"s": 1680,
"text": "mayank007rawa"
},
{
"code": null,
"e": 1697,
"s": 1694,
"text": "C#"
},
{
"code": null,
"e": 1716,
"s": 1697,
"text": "Difference Between"
}
] |
GATE | GATE-CS-2001 | Question 32
|
28 Jun, 2021
Consider the following problem X.
Given a Turing machine M over the input alphabet Ξ£, any
state q of M And a word wβΞ£*, does the computation of M
on w visit the state q?
Which of the following statements about X is correct?(A) X is decidable(B) X is undecidable but partially decidable(C) X is undecidable and not even partially decidable(D) X is not a decision problemAnswer: (B)Explanation:This problem is a State Entry Problem. State entry problem can be reduced to halting problem.We construct a turing machine M with final state βqβ. We run a turing machine R (for state entry problem)with inputs : M, q, w .We give βwβ as input to M.If M halts in the final state βqβ then R accepts the input. So, the given problem is partially decidable.
If M goes in an infinite loop then M can not output anything. So, R rejects the input. So, the given problem becomes undecidable. Thus, option (B) is the answer. Please comment below if you find anything wrong in the above post.Quiz of this Question
GATE-CS-2001
GATE-GATE-CS-2001
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 62,
"s": 28,
"text": "Consider the following problem X."
},
{
"code": null,
"e": 199,
"s": 62,
"text": "Given a Turing machine M over the input alphabet Ξ£, any\nstate q of M And a word wβΞ£*, does the computation of M\non w visit the state q? "
},
{
"code": null,
"e": 774,
"s": 199,
"text": "Which of the following statements about X is correct?(A) X is decidable(B) X is undecidable but partially decidable(C) X is undecidable and not even partially decidable(D) X is not a decision problemAnswer: (B)Explanation:This problem is a State Entry Problem. State entry problem can be reduced to halting problem.We construct a turing machine M with final state βqβ. We run a turing machine R (for state entry problem)with inputs : M, q, w .We give βwβ as input to M.If M halts in the final state βqβ then R accepts the input. So, the given problem is partially decidable."
},
{
"code": null,
"e": 1024,
"s": 774,
"text": "If M goes in an infinite loop then M can not output anything. So, R rejects the input. So, the given problem becomes undecidable. Thus, option (B) is the answer. Please comment below if you find anything wrong in the above post.Quiz of this Question"
},
{
"code": null,
"e": 1037,
"s": 1024,
"text": "GATE-CS-2001"
},
{
"code": null,
"e": 1055,
"s": 1037,
"text": "GATE-GATE-CS-2001"
},
{
"code": null,
"e": 1060,
"s": 1055,
"text": "GATE"
}
] |
How to check whether specified values are present in NumPy array?
|
22 Sep, 2020
Sometimes we need to test whether certain values are present in an array. Using Numpy array, we can easily find whether specific values are present or not. For this purpose, we use the βinβ operator. βinβ operator is used to check whether certain element and values are present in a given sequence and hence return Boolean values βTrueβ and βFalseβ.
Example 1:
Python3
# importing Numpy packageimport numpy as np # creating a Numpy arrayn_array = np.array([[2, 3, 0], [4, 1, 6]]) print("Given array:")print(n_array) # Checking whether specific values# are present in "n_array" or notprint(2 in n_array)print(0 in n_array)print(6 in n_array)print(50 in n_array)print(10 in n_array)
Output:
Given array:
[[2 3 0]
[4 1 6]]
True
True
True
False
False
In the above example, we check whether values 2, 0, 6, 50, 10 are present in Numpy array βn_arrayβ using the βinβ operator.
Example 2:
Python3
# importing Numpy packageimport numpy as np # creating a Numpy arrayn_array = np.array([[2.14, 3, 0.5], [4.5, 1.2, 6.2], [20.2, 5.9, 8.8]]) print("Given array:")print(n_array) # Checking whether specific values# are present in "n_array" or notprint(2.14 in n_array)print(5.28 in n_array)print(6.2 in n_array)print(5.9 in n_array)print(8.5 in n_array)
Output:
Given array:
[[ 2.14 3. 0.5 ]
[ 4.5 1.2 6.2 ]
[20.2 5.9 8.8 ]]
True
False
True
True
False
In the above example, we check whether values 2.14, 5.28, 6.2, 5.9, 8.5 are present in Numpy array βn_arrayβ.
Example 3:
Python3
# importing Numpy packageimport numpy as np # creating a Numpy arrayn_array = np.array([[4, 5.5, 7, 6.9, 10], [7.1, 5.3, 40, 8.8, 1], [4.4, 9.3, 6, 2.2, 11], [7.1, 4, 5, 9, 10.5]]) print("Given array:")print(n_array) # Checking whether specific values# are present in "n_array" or notprint(2.14 in n_array)print(5.28 in n_array)print(8.5 in n_array)
Output:
Given array:
[[ 4. 5.5 7. 6.9 10. ]
[ 7.1 5.3 40. 8.8 1. ]
[ 4.4 9.3 6. 2.2 11. ]
[ 7.1 4. 5. 9. 10.5]]
False
False
False
In the above example, we check whether values 2.14, 5.28, 8.5 are present in Numpy array βn_arrayβ.
Python numpy-arrayManipulation
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 | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Sep, 2020"
},
{
"code": null,
"e": 378,
"s": 28,
"text": "Sometimes we need to test whether certain values are present in an array. Using Numpy array, we can easily find whether specific values are present or not. For this purpose, we use the βinβ operator. βinβ operator is used to check whether certain element and values are present in a given sequence and hence return Boolean values βTrueβ and βFalseβ."
},
{
"code": null,
"e": 389,
"s": 378,
"text": "Example 1:"
},
{
"code": null,
"e": 397,
"s": 389,
"text": "Python3"
},
{
"code": "# importing Numpy packageimport numpy as np # creating a Numpy arrayn_array = np.array([[2, 3, 0], [4, 1, 6]]) print(\"Given array:\")print(n_array) # Checking whether specific values# are present in \"n_array\" or notprint(2 in n_array)print(0 in n_array)print(6 in n_array)print(50 in n_array)print(10 in n_array)",
"e": 731,
"s": 397,
"text": null
},
{
"code": null,
"e": 739,
"s": 731,
"text": "Output:"
},
{
"code": null,
"e": 798,
"s": 739,
"text": "Given array:\n[[2 3 0]\n[4 1 6]]\nTrue\nTrue\nTrue\nFalse\nFalse\n"
},
{
"code": null,
"e": 922,
"s": 798,
"text": "In the above example, we check whether values 2, 0, 6, 50, 10 are present in Numpy array βn_arrayβ using the βinβ operator."
},
{
"code": null,
"e": 934,
"s": 922,
"text": "Example 2: "
},
{
"code": null,
"e": 942,
"s": 934,
"text": "Python3"
},
{
"code": "# importing Numpy packageimport numpy as np # creating a Numpy arrayn_array = np.array([[2.14, 3, 0.5], [4.5, 1.2, 6.2], [20.2, 5.9, 8.8]]) print(\"Given array:\")print(n_array) # Checking whether specific values# are present in \"n_array\" or notprint(2.14 in n_array)print(5.28 in n_array)print(6.2 in n_array)print(5.9 in n_array)print(8.5 in n_array)",
"e": 1334,
"s": 942,
"text": null
},
{
"code": null,
"e": 1342,
"s": 1334,
"text": "Output:"
},
{
"code": null,
"e": 1445,
"s": 1342,
"text": "Given array:\n[[ 2.14 3. 0.5 ]\n[ 4.5 1.2 6.2 ]\n[20.2 5.9 8.8 ]]\nTrue\nFalse\nTrue\nTrue\nFalse\n"
},
{
"code": null,
"e": 1555,
"s": 1445,
"text": "In the above example, we check whether values 2.14, 5.28, 6.2, 5.9, 8.5 are present in Numpy array βn_arrayβ."
},
{
"code": null,
"e": 1566,
"s": 1555,
"text": "Example 3:"
},
{
"code": null,
"e": 1574,
"s": 1566,
"text": "Python3"
},
{
"code": "# importing Numpy packageimport numpy as np # creating a Numpy arrayn_array = np.array([[4, 5.5, 7, 6.9, 10], [7.1, 5.3, 40, 8.8, 1], [4.4, 9.3, 6, 2.2, 11], [7.1, 4, 5, 9, 10.5]]) print(\"Given array:\")print(n_array) # Checking whether specific values# are present in \"n_array\" or notprint(2.14 in n_array)print(5.28 in n_array)print(8.5 in n_array)",
"e": 1986,
"s": 1574,
"text": null
},
{
"code": null,
"e": 1994,
"s": 1986,
"text": "Output:"
},
{
"code": null,
"e": 2136,
"s": 1994,
"text": "Given array:\n[[ 4. 5.5 7. 6.9 10. ]\n[ 7.1 5.3 40. 8.8 1. ]\n[ 4.4 9.3 6. 2.2 11. ]\n[ 7.1 4. 5. 9. 10.5]]\nFalse\nFalse\nFalse\n"
},
{
"code": null,
"e": 2236,
"s": 2136,
"text": "In the above example, we check whether values 2.14, 5.28, 8.5 are present in Numpy array βn_arrayβ."
},
{
"code": null,
"e": 2267,
"s": 2236,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 2280,
"s": 2267,
"text": "Python-numpy"
},
{
"code": null,
"e": 2287,
"s": 2280,
"text": "Python"
},
{
"code": null,
"e": 2385,
"s": 2287,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2417,
"s": 2385,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2444,
"s": 2417,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2475,
"s": 2444,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2498,
"s": 2475,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2519,
"s": 2498,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2575,
"s": 2519,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2617,
"s": 2575,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2659,
"s": 2617,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2698,
"s": 2659,
"text": "Python | Get unique values from a list"
}
] |
SSTable in Apache Cassandra
|
10 Jul, 2020
In this article, we are going to discuss SSTable which is one of the storage engines in Cassandra and SSTable components and also, we will cover what type of information kept in different database file in SSTable. Letβs discuss one by one.
SSTable :It is one of the storage engines in Apache Cassandra i.e storage for Immutable data file for row storage. In Cassandra, SSTable uses for persisting data on disk.
Key points :
In Apache Cassandra, as you will check how data stores then data in SSTables and SSTables are flushed to disk from Memtables or are streamed from other nodes.
In Cassandra, while inserting data the timestamp is included in every write when it was written.
In Cassandra, compaction is a concept that combines multiple SSTable into one big SSTable, and once new SSTable has been written after that old SSTables can be removed.only, the latest timestamp is kept.
Components of SSTable :In Cassandra, SSTable has multiple components that stored in multiple files as following.
Data.db βIn SSTable, Data.db stores the actual data, i.e. the contents of rows.
Index.db βIt is the component of SSTable in which an index from partition keys to positions in the Data.db file. It may also include an index to rows within a partition.
Summary.db βIn Cassandra, SSTable component Summary.db has a sampling of (by default) every 128th entry in the Index.db file.
Filter.db βIn SSTable, It is a Bloom Filter of the partition keys.
CompressionInfo.db βIn SSTable, It is the component that kept the Metadata about the offsets. CompressionInfo.db kept the lengths of compression chunks in the Data.db file.
Statistics.db βIt is one of the important components in SSTable which kept the statistics of data. In Cassandra, It is an SSTable component that Stores metadata about the SSTable and including information about timestamps, tombstones, clustering keys, compaction, repair, compression, Time to Live (TTL) values, and more.
Digest.crc32 βIn Cassandra, this SSTable component has a CRC-32 digest of the Data.db file.
TOC.txt βIn Cassandra, this SSTable component has a plain text list of the component files for the SSTable. In SSTable, Within the Data.db file, rows are organized by partition. These partitions are stored in token order such that by a hash of the partition key when Murmur3Partition chosen rows are stored in the order of their clustering keys.
Note βIn Apache Cassandra, SSTables can be optionally compressed using block-based compression.
Apache
NoSQL
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 293,
"s": 53,
"text": "In this article, we are going to discuss SSTable which is one of the storage engines in Cassandra and SSTable components and also, we will cover what type of information kept in different database file in SSTable. Letβs discuss one by one."
},
{
"code": null,
"e": 464,
"s": 293,
"text": "SSTable :It is one of the storage engines in Apache Cassandra i.e storage for Immutable data file for row storage. In Cassandra, SSTable uses for persisting data on disk."
},
{
"code": null,
"e": 477,
"s": 464,
"text": "Key points :"
},
{
"code": null,
"e": 636,
"s": 477,
"text": "In Apache Cassandra, as you will check how data stores then data in SSTables and SSTables are flushed to disk from Memtables or are streamed from other nodes."
},
{
"code": null,
"e": 733,
"s": 636,
"text": "In Cassandra, while inserting data the timestamp is included in every write when it was written."
},
{
"code": null,
"e": 937,
"s": 733,
"text": "In Cassandra, compaction is a concept that combines multiple SSTable into one big SSTable, and once new SSTable has been written after that old SSTables can be removed.only, the latest timestamp is kept."
},
{
"code": null,
"e": 1050,
"s": 937,
"text": "Components of SSTable :In Cassandra, SSTable has multiple components that stored in multiple files as following."
},
{
"code": null,
"e": 1130,
"s": 1050,
"text": "Data.db βIn SSTable, Data.db stores the actual data, i.e. the contents of rows."
},
{
"code": null,
"e": 1300,
"s": 1130,
"text": "Index.db βIt is the component of SSTable in which an index from partition keys to positions in the Data.db file. It may also include an index to rows within a partition."
},
{
"code": null,
"e": 1426,
"s": 1300,
"text": "Summary.db βIn Cassandra, SSTable component Summary.db has a sampling of (by default) every 128th entry in the Index.db file."
},
{
"code": null,
"e": 1493,
"s": 1426,
"text": "Filter.db βIn SSTable, It is a Bloom Filter of the partition keys."
},
{
"code": null,
"e": 1666,
"s": 1493,
"text": "CompressionInfo.db βIn SSTable, It is the component that kept the Metadata about the offsets. CompressionInfo.db kept the lengths of compression chunks in the Data.db file."
},
{
"code": null,
"e": 1988,
"s": 1666,
"text": "Statistics.db βIt is one of the important components in SSTable which kept the statistics of data. In Cassandra, It is an SSTable component that Stores metadata about the SSTable and including information about timestamps, tombstones, clustering keys, compaction, repair, compression, Time to Live (TTL) values, and more."
},
{
"code": null,
"e": 2080,
"s": 1988,
"text": "Digest.crc32 βIn Cassandra, this SSTable component has a CRC-32 digest of the Data.db file."
},
{
"code": null,
"e": 2426,
"s": 2080,
"text": "TOC.txt βIn Cassandra, this SSTable component has a plain text list of the component files for the SSTable. In SSTable, Within the Data.db file, rows are organized by partition. These partitions are stored in token order such that by a hash of the partition key when Murmur3Partition chosen rows are stored in the order of their clustering keys."
},
{
"code": null,
"e": 2522,
"s": 2426,
"text": "Note βIn Apache Cassandra, SSTables can be optionally compressed using block-based compression."
},
{
"code": null,
"e": 2529,
"s": 2522,
"text": "Apache"
},
{
"code": null,
"e": 2535,
"s": 2529,
"text": "NoSQL"
},
{
"code": null,
"e": 2540,
"s": 2535,
"text": "DBMS"
},
{
"code": null,
"e": 2545,
"s": 2540,
"text": "DBMS"
}
] |
How to split a string in C/C++, Python and Java?
|
08 Jul, 2022
Splitting a string by some delimiter is a very common task. For example, we have a comma-separated list of items from a file and we want individual items in an array. Almost all programming languages, provide a function split a string by some delimiter.
// Splits str[] according to given delimiters.
// and returns next token. It needs to be called
// in a loop to get all tokens. It returns NULL
// when there are no more tokens.
char * strtok(char str[], const char *delims);
C
// A C/C++ program for splitting a string// using strtok()#include <stdio.h>#include <string.h> int main(){ char str[] = "Geeks-for-Geeks"; // Returns first token char *token = strtok(str, "-"); // Keep printing tokens while one of the // delimiters present in str[]. while (token != NULL) { printf("%s\n", token); token = strtok(NULL, "-"); } return 0;}
Output: Geeks
for
Geeks
Time complexity : O(n)
Auxiliary Space: O(n)
Note: The main disadvantage of strtok() is that it only works for C style strings.
Therefore we need to explicitly convert C++ string into a char array.
Many programmers are unaware that C++ has two additional APIs which are more elegant
and works with C++ string.
Prerequisite: stringstream API
Stringstream object can be initialized using a string object, it automatically tokenizes strings on space char. Just like βcinβ stream stringstream allows you to read a string as a stream of words.
Some of the Most Common used functions of StringStream.
clear() β flushes the stream
str() β converts a stream of words into a C++ string object.
operator << β pushes a string object into the stream.
operator >> β extracts a word from the stream.
The code below demonstrates it.
C++
#include <bits/stdc++.h>using namespace std; // A quick way to split strings separated via spaces.void simple_tokenizer(string s){ stringstream ss(s); string word; while (ss >> word) { cout << word << endl; }} int main(int argc, char const* argv[]){ string a = "How do you do!"; // Takes only space separated C++ strings. simple_tokenizer(a); cout << endl; return 0;}
Output : How
do
you
do!
Prerequisite: find function and substr().
This method is more robust and can parse a string with any delimiter, not just spaces(though the default behavior is to separate on spaces.) The logic is pretty simple to understand from the code below.
C++
#include <bits/stdc++.h>using namespace std; void tokenize(string s, string del = " "){ int start = 0; int end = s.find(del); while (end != -1) { cout << s.substr(start, end - start) << endl; start = end + del.size(); end = s.find(del, start); } cout << s.substr(start, end - start);}int main(int argc, char const* argv[]){ // Takes C++ string with any separator string a = "Hi$%do$%you$%do$%!"; tokenize(a, "$%"); cout << endl; return 0;}
Output: Hi
do
you
do
!
Method 3: Using temporary string
If you are given that the length of the delimiter is 1, then you can simply use a temp string to split the string. This will save the function overhead time in the case of method 2.
C++
#include <iostream>using namespace std; void split(string str, char del){ // declaring temp string to store the curr "word" upto del string temp = ""; for(int i=0; i<(int)str.size(); i++){ // If cur char is not del, then append it to the cur "word", otherwise // you have completed the word, print it, and start a new word. if(str[i] != del){ temp += str[i]; } else{ cout << temp << " "; temp = ""; } } cout << temp;} int main() { string str = "geeks_for_geeks"; // string to be split char del = '_'; // delimiter around which string is to be split split(str, del); return 0;}
geeks for geeks
Time complexity : O(n)
Auxiliary Space: O(n)
In Java : In Java, split() is a method in String class.
// expregexp is the delimiting regular expression;
// limit is the number of returned strings
public String[] split(String regexp, int limit);
// We can call split() without limit also
public String[] split(String regexp)
Java
// A Java program for splitting a string// using split()import java.io.*;public class Test{ public static void main(String args[]) { String Str = new String("Geeks-for-Geeks"); // Split above string in at-most two strings for (String val: Str.split("-", 2)) System.out.println(val); System.out.println(""); // Splits Str into all possible tokens for (String val: Str.split("-")) System.out.println(val); }}
Output:
Geeks
for-Geeks
Geeks
for
Geeks
In Python: The split() method in Python returns a list of strings after breaking the given string by the specified separator.
// regexp is the delimiting regular expression;
// limit is limit the number of splits to be made
str.split(regexp = "", limit = string.count(str))
Python3
line = "Geek1 \nGeek2 \nGeek3"print(line.split())print(line.split(' ', 1))
Output:
['Geek1', 'Geek2', 'Geek3']
['Geek1', '\nGeek2 \nGeek3']
Python Programming Tutorial - Logical Operations and Splitting in Strings | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersPython Programming Tutorial - Logical Operations and Splitting in Strings | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:31β’Liveβ’<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=m9iv9aM6Om8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Aarti_Rathi and Aditya Chatterjee. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
arun singh
suman_1729
saurabh1990aror
hitesh19426
mohit singh 13
amartyaghoshgfg
adi1212
CPP-Library
cpp-string
Java-String-Programs
C Language
C++
Java
Python
Strings
Strings
Java
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 307,
"s": 52,
"text": "Splitting a string by some delimiter is a very common task. For example, we have a comma-separated list of items from a file and we want individual items in an array. Almost all programming languages, provide a function split a string by some delimiter. "
},
{
"code": null,
"e": 532,
"s": 307,
"text": "// Splits str[] according to given delimiters.\n// and returns next token. It needs to be called\n// in a loop to get all tokens. It returns NULL\n// when there are no more tokens.\nchar * strtok(char str[], const char *delims);"
},
{
"code": null,
"e": 534,
"s": 532,
"text": "C"
},
{
"code": "// A C/C++ program for splitting a string// using strtok()#include <stdio.h>#include <string.h> int main(){ char str[] = \"Geeks-for-Geeks\"; // Returns first token char *token = strtok(str, \"-\"); // Keep printing tokens while one of the // delimiters present in str[]. while (token != NULL) { printf(\"%s\\n\", token); token = strtok(NULL, \"-\"); } return 0;}",
"e": 935,
"s": 534,
"text": null
},
{
"code": null,
"e": 967,
"s": 935,
"text": "Output: Geeks\n for\n Geeks"
},
{
"code": null,
"e": 990,
"s": 967,
"text": "Time complexity : O(n)"
},
{
"code": null,
"e": 1012,
"s": 990,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 1300,
"s": 1012,
"text": "Note: The main disadvantage of strtok() is that it only works for C style strings.\n Therefore we need to explicitly convert C++ string into a char array.\n Many programmers are unaware that C++ has two additional APIs which are more elegant\n and works with C++ string. "
},
{
"code": null,
"e": 1333,
"s": 1300,
"text": "Prerequisite: stringstream API "
},
{
"code": null,
"e": 1531,
"s": 1333,
"text": "Stringstream object can be initialized using a string object, it automatically tokenizes strings on space char. Just like βcinβ stream stringstream allows you to read a string as a stream of words."
},
{
"code": null,
"e": 1780,
"s": 1531,
"text": "Some of the Most Common used functions of StringStream.\nclear() β flushes the stream \nstr() β converts a stream of words into a C++ string object.\noperator << β pushes a string object into the stream.\noperator >> β extracts a word from the stream."
},
{
"code": null,
"e": 1814,
"s": 1780,
"text": " The code below demonstrates it. "
},
{
"code": null,
"e": 1818,
"s": 1814,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // A quick way to split strings separated via spaces.void simple_tokenizer(string s){ stringstream ss(s); string word; while (ss >> word) { cout << word << endl; }} int main(int argc, char const* argv[]){ string a = \"How do you do!\"; // Takes only space separated C++ strings. simple_tokenizer(a); cout << endl; return 0;}",
"e": 2220,
"s": 1818,
"text": null
},
{
"code": null,
"e": 2261,
"s": 2220,
"text": "Output : How \n do \n you\n do!"
},
{
"code": null,
"e": 2303,
"s": 2261,
"text": "Prerequisite: find function and substr()."
},
{
"code": null,
"e": 2506,
"s": 2303,
"text": "This method is more robust and can parse a string with any delimiter, not just spaces(though the default behavior is to separate on spaces.) The logic is pretty simple to understand from the code below."
},
{
"code": null,
"e": 2510,
"s": 2506,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h>using namespace std; void tokenize(string s, string del = \" \"){ int start = 0; int end = s.find(del); while (end != -1) { cout << s.substr(start, end - start) << endl; start = end + del.size(); end = s.find(del, start); } cout << s.substr(start, end - start);}int main(int argc, char const* argv[]){ // Takes C++ string with any separator string a = \"Hi$%do$%you$%do$%!\"; tokenize(a, \"$%\"); cout << endl; return 0;}",
"e": 3002,
"s": 2510,
"text": null
},
{
"code": null,
"e": 3043,
"s": 3002,
"text": "Output: Hi \n do \n you\n do\n !"
},
{
"code": null,
"e": 3077,
"s": 3043,
"text": "Method 3: Using temporary string"
},
{
"code": null,
"e": 3259,
"s": 3077,
"text": "If you are given that the length of the delimiter is 1, then you can simply use a temp string to split the string. This will save the function overhead time in the case of method 2."
},
{
"code": null,
"e": 3263,
"s": 3259,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; void split(string str, char del){ // declaring temp string to store the curr \"word\" upto del string temp = \"\"; for(int i=0; i<(int)str.size(); i++){ // If cur char is not del, then append it to the cur \"word\", otherwise // you have completed the word, print it, and start a new word. if(str[i] != del){ temp += str[i]; } else{ cout << temp << \" \"; temp = \"\"; } } cout << temp;} int main() { string str = \"geeks_for_geeks\"; // string to be split char del = '_'; // delimiter around which string is to be split split(str, del); return 0;}",
"e": 3983,
"s": 3263,
"text": null
},
{
"code": null,
"e": 3999,
"s": 3983,
"text": "geeks for geeks"
},
{
"code": null,
"e": 4022,
"s": 3999,
"text": "Time complexity : O(n)"
},
{
"code": null,
"e": 4044,
"s": 4022,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 4101,
"s": 4044,
"text": "In Java : In Java, split() is a method in String class. "
},
{
"code": null,
"e": 4325,
"s": 4101,
"text": "// expregexp is the delimiting regular expression; \n// limit is the number of returned strings\npublic String[] split(String regexp, int limit);\n\n// We can call split() without limit also\npublic String[] split(String regexp)"
},
{
"code": null,
"e": 4330,
"s": 4325,
"text": "Java"
},
{
"code": "// A Java program for splitting a string// using split()import java.io.*;public class Test{ public static void main(String args[]) { String Str = new String(\"Geeks-for-Geeks\"); // Split above string in at-most two strings for (String val: Str.split(\"-\", 2)) System.out.println(val); System.out.println(\"\"); // Splits Str into all possible tokens for (String val: Str.split(\"-\")) System.out.println(val); }}",
"e": 4816,
"s": 4330,
"text": null
},
{
"code": null,
"e": 4825,
"s": 4816,
"text": "Output: "
},
{
"code": null,
"e": 4858,
"s": 4825,
"text": "Geeks\nfor-Geeks\n\nGeeks\nfor\nGeeks"
},
{
"code": null,
"e": 4986,
"s": 4858,
"text": "In Python: The split() method in Python returns a list of strings after breaking the given string by the specified separator. "
},
{
"code": null,
"e": 5146,
"s": 4986,
"text": " \n // regexp is the delimiting regular expression; \n // limit is limit the number of splits to be made \n str.split(regexp = \"\", limit = string.count(str)) "
},
{
"code": null,
"e": 5154,
"s": 5146,
"text": "Python3"
},
{
"code": "line = \"Geek1 \\nGeek2 \\nGeek3\"print(line.split())print(line.split(' ', 1))",
"e": 5229,
"s": 5154,
"text": null
},
{
"code": null,
"e": 5238,
"s": 5229,
"text": "Output: "
},
{
"code": null,
"e": 5296,
"s": 5238,
"text": "['Geek1', 'Geek2', 'Geek3']\n['Geek1', '\\nGeek2 \\nGeek3'] "
},
{
"code": null,
"e": 6260,
"s": 5296,
"text": "Python Programming Tutorial - Logical Operations and Splitting in Strings | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersPython Programming Tutorial - Logical Operations and Splitting in Strings | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:31β’Liveβ’<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=m9iv9aM6Om8\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 6673,
"s": 6260,
"text": "This article is contributed by Aarti_Rathi and Aditya Chatterjee. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 6684,
"s": 6673,
"text": "arun singh"
},
{
"code": null,
"e": 6695,
"s": 6684,
"text": "suman_1729"
},
{
"code": null,
"e": 6711,
"s": 6695,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 6723,
"s": 6711,
"text": "hitesh19426"
},
{
"code": null,
"e": 6738,
"s": 6723,
"text": "mohit singh 13"
},
{
"code": null,
"e": 6754,
"s": 6738,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 6762,
"s": 6754,
"text": "adi1212"
},
{
"code": null,
"e": 6774,
"s": 6762,
"text": "CPP-Library"
},
{
"code": null,
"e": 6785,
"s": 6774,
"text": "cpp-string"
},
{
"code": null,
"e": 6806,
"s": 6785,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 6817,
"s": 6806,
"text": "C Language"
},
{
"code": null,
"e": 6821,
"s": 6817,
"text": "C++"
},
{
"code": null,
"e": 6826,
"s": 6821,
"text": "Java"
},
{
"code": null,
"e": 6833,
"s": 6826,
"text": "Python"
},
{
"code": null,
"e": 6841,
"s": 6833,
"text": "Strings"
},
{
"code": null,
"e": 6849,
"s": 6841,
"text": "Strings"
},
{
"code": null,
"e": 6854,
"s": 6849,
"text": "Java"
},
{
"code": null,
"e": 6858,
"s": 6854,
"text": "CPP"
}
] |
Python | Part of Speech Tagging using TextBlob
|
11 Apr, 2022
TextBlob module is used for building programs for text analysis. One of the more powerful aspects of the TextBlob module is the Part of Speech tagging. Install TextBlob run the following commands:
$ pip install -U textblob
$ python -m textblob.download_corpora
This will install TextBlob and download the necessary NLTK corpora. The above installation will take quite some time due to the massive amount of tokenizers, chunkers, other algorithms, and all of the corpora to be downloaded.
Letβs knock out some quick vocabulary: Corpus : Body of text, singular. Corpora is the plural of this. Lexicon : Words and their meanings. Token : Each βentityβ that is a part of whatever was split up based on rules.
In corpus linguistics, part-of-speech tagging (POS tagging or PoS tagging or POST), also called Grammatical tagging or Word-category disambiguation.
Input: Everything is all about money.
Output: [('Everything', 'NN'), ('is', 'VBZ'),
('all', 'DT'), ('about', 'IN'),
('money', 'NN')]
Hereβs a list of the tags, what they mean, and some examples:
CC coordinating conjunction
CD cardinal digit
DT determiner
EX existential there (like: βthere isβ ... think of it like βthere existsβ)
FW foreign word
IN preposition/subordinating conjunction
JJ adjective βbigβ
JJR adjective, comparative βbiggerβ
JJS adjective, superlative βbiggestβ
LS list marker 1)
MD modal could, will
NN noun, singular βdeskβ
NNS noun plural βdesksβ
NNP proper noun, singular βHarrisonβ
NNPS proper noun, plural βAmericansβ
PDT predeterminer βall the kidsβ
POS possessive ending parentβs
PRP personal pronoun I, he, she
PRP$ possessive pronoun my, his, hers
RB adverb very, silently,
RBR adverb, comparative better
RBS adverb, superlative best
RP particle give up
TO to go βtoβ the store.
UH interjection errrrrrrrm
VB verb, base form take
VBD verb, past tense took
VBG verb, gerund/present participle taking
VBN verb, past participle taken
VBP verb, sing. present, non-3d take
VBZ verb, 3rd person sing. present takes
WDT wh-determiner which
WP wh-pronoun who, what
WP$ possessive wh-pronoun whose
WRB wh-adverb where, when
Python3
# from textblob lib import TextBlob methodfrom textblob import TextBlob text = ("Sukanya, Rajib and Naba are my good friends. " + "Sukanya is getting married next year. " + "Marriage is a big step in oneβs life." + "It is both exciting and frightening. " + "But friendship is a sacred bond between people." + "It is a special kind of love between us. " + "Many of you must have tried searching for a friend "+ "but never found the right one.") # create a textblob objectblob_object = TextBlob(text) # Part-of-speech tags can be accessed# through the tags property of blob object.' # print word with pos tag.print(blob_object.tags)
Output :
[('Sukanya', 'NNP'),
('Rajib', 'NNP'),
('and', 'CC'),
('Naba', 'NNP'),
('are', 'VBP'),
('my', 'PRP$'),
('good', 'JJ'),
('friends', 'NNS'),
('Sukanya', 'NNP'),
('is', 'VBZ'),
('getting', 'VBG'),
('married', 'VBN'),
('next', 'JJ'),
('year', 'NN'),
('Marriage', 'NN'),
('is', 'VBZ'),
('a', 'DT'),
('big', 'JJ'),
('step', 'NN'),
('in', 'IN'),
('one', 'CD'),
('β', 'NN'),
('s', 'NN'),
('life.It', 'NN'),
('is', 'VBZ'),
('both', 'DT'),
('exciting', 'VBG'),
('and', 'CC'),
('frightening', 'NN'),
('But', 'CC'),
('friendship', 'NN'),
('is', 'VBZ'),
('a', 'DT'),
('sacred', 'JJ'),
('bond', 'NN'),
('between', 'IN'),
('people.It', 'NN'),
('is', 'VBZ'),
('a', 'DT'),
('special', 'JJ'),
('kind', 'NN'),
('of', 'IN'),
('love', 'NN'),
('between', 'IN'),
('us', 'PRP'),
('Many', 'JJ'),
('of', 'IN'),
('you', 'PRP'),
('must', 'MD'),
('have', 'VB'),
('tried', 'VBN'),
('searching', 'VBG'),
('for', 'IN'),
('a', 'DT'),
('friend', 'NN'),
('but', 'CC'),
('never', 'RB'),
('found', 'VBD'),
('the', 'DT'),
('right', 'JJ'),
('one', 'NN')]
Basically, the goal of a POS tagger is to assign linguistic (mostly grammatical) information to sub-sentential units. Such units are called tokens and, most of the time, correspond to words and symbols (e.g. punctuation).
rkbhola5
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Supervised and Unsupervised learning
Search Algorithms in AI
Decision Tree Introduction with example
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": 54,
"s": 26,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 251,
"s": 54,
"text": "TextBlob module is used for building programs for text analysis. One of the more powerful aspects of the TextBlob module is the Part of Speech tagging. Install TextBlob run the following commands:"
},
{
"code": null,
"e": 315,
"s": 251,
"text": "$ pip install -U textblob\n$ python -m textblob.download_corpora"
},
{
"code": null,
"e": 542,
"s": 315,
"text": "This will install TextBlob and download the necessary NLTK corpora. The above installation will take quite some time due to the massive amount of tokenizers, chunkers, other algorithms, and all of the corpora to be downloaded."
},
{
"code": null,
"e": 759,
"s": 542,
"text": "Letβs knock out some quick vocabulary: Corpus : Body of text, singular. Corpora is the plural of this. Lexicon : Words and their meanings. Token : Each βentityβ that is a part of whatever was split up based on rules."
},
{
"code": null,
"e": 908,
"s": 759,
"text": "In corpus linguistics, part-of-speech tagging (POS tagging or PoS tagging or POST), also called Grammatical tagging or Word-category disambiguation."
},
{
"code": null,
"e": 1087,
"s": 908,
"text": "Input: Everything is all about money.\nOutput: [('Everything', 'NN'), ('is', 'VBZ'), \n ('all', 'DT'), ('about', 'IN'), \n ('money', 'NN')] "
},
{
"code": null,
"e": 1149,
"s": 1087,
"text": "Hereβs a list of the tags, what they mean, and some examples:"
},
{
"code": null,
"e": 2197,
"s": 1149,
"text": "CC coordinating conjunction\nCD cardinal digit\nDT determiner\nEX existential there (like: βthere isβ ... think of it like βthere existsβ)\nFW foreign word\nIN preposition/subordinating conjunction\nJJ adjective βbigβ\nJJR adjective, comparative βbiggerβ\nJJS adjective, superlative βbiggestβ\nLS list marker 1)\nMD modal could, will\nNN noun, singular βdeskβ\nNNS noun plural βdesksβ\nNNP proper noun, singular βHarrisonβ\nNNPS proper noun, plural βAmericansβ\nPDT predeterminer βall the kidsβ\nPOS possessive ending parentβs\nPRP personal pronoun I, he, she\nPRP$ possessive pronoun my, his, hers\nRB adverb very, silently,\nRBR adverb, comparative better\nRBS adverb, superlative best\nRP particle give up\nTO to go βtoβ the store.\nUH interjection errrrrrrrm\nVB verb, base form take\nVBD verb, past tense took\nVBG verb, gerund/present participle taking\nVBN verb, past participle taken\nVBP verb, sing. present, non-3d take\nVBZ verb, 3rd person sing. present takes\nWDT wh-determiner which\nWP wh-pronoun who, what\nWP$ possessive wh-pronoun whose\nWRB wh-adverb where, when"
},
{
"code": null,
"e": 2205,
"s": 2197,
"text": "Python3"
},
{
"code": "# from textblob lib import TextBlob methodfrom textblob import TextBlob text = (\"Sukanya, Rajib and Naba are my good friends. \" + \"Sukanya is getting married next year. \" + \"Marriage is a big step in oneβs life.\" + \"It is both exciting and frightening. \" + \"But friendship is a sacred bond between people.\" + \"It is a special kind of love between us. \" + \"Many of you must have tried searching for a friend \"+ \"but never found the right one.\") # create a textblob objectblob_object = TextBlob(text) # Part-of-speech tags can be accessed# through the tags property of blob object.' # print word with pos tag.print(blob_object.tags)",
"e": 2857,
"s": 2205,
"text": null
},
{
"code": null,
"e": 2866,
"s": 2857,
"text": "Output :"
},
{
"code": null,
"e": 3942,
"s": 2866,
"text": "[('Sukanya', 'NNP'),\n ('Rajib', 'NNP'),\n ('and', 'CC'),\n ('Naba', 'NNP'),\n ('are', 'VBP'),\n ('my', 'PRP$'),\n ('good', 'JJ'),\n ('friends', 'NNS'),\n ('Sukanya', 'NNP'),\n ('is', 'VBZ'),\n ('getting', 'VBG'),\n ('married', 'VBN'),\n ('next', 'JJ'),\n ('year', 'NN'),\n ('Marriage', 'NN'),\n ('is', 'VBZ'),\n ('a', 'DT'),\n ('big', 'JJ'),\n ('step', 'NN'),\n ('in', 'IN'),\n ('one', 'CD'),\n ('β', 'NN'),\n ('s', 'NN'),\n ('life.It', 'NN'),\n ('is', 'VBZ'),\n ('both', 'DT'),\n ('exciting', 'VBG'),\n ('and', 'CC'),\n ('frightening', 'NN'),\n ('But', 'CC'),\n ('friendship', 'NN'),\n ('is', 'VBZ'),\n ('a', 'DT'),\n ('sacred', 'JJ'),\n ('bond', 'NN'),\n ('between', 'IN'),\n ('people.It', 'NN'),\n ('is', 'VBZ'),\n ('a', 'DT'),\n ('special', 'JJ'),\n ('kind', 'NN'),\n ('of', 'IN'),\n ('love', 'NN'),\n ('between', 'IN'),\n ('us', 'PRP'),\n ('Many', 'JJ'),\n ('of', 'IN'),\n ('you', 'PRP'),\n ('must', 'MD'),\n ('have', 'VB'),\n ('tried', 'VBN'),\n ('searching', 'VBG'),\n ('for', 'IN'),\n ('a', 'DT'),\n ('friend', 'NN'),\n ('but', 'CC'),\n ('never', 'RB'),\n ('found', 'VBD'),\n ('the', 'DT'),\n ('right', 'JJ'),\n ('one', 'NN')]"
},
{
"code": null,
"e": 4164,
"s": 3942,
"text": "Basically, the goal of a POS tagger is to assign linguistic (mostly grammatical) information to sub-sentential units. Such units are called tokens and, most of the time, correspond to words and symbols (e.g. punctuation)."
},
{
"code": null,
"e": 4173,
"s": 4164,
"text": "rkbhola5"
},
{
"code": null,
"e": 4190,
"s": 4173,
"text": "Machine Learning"
},
{
"code": null,
"e": 4197,
"s": 4190,
"text": "Python"
},
{
"code": null,
"e": 4214,
"s": 4197,
"text": "Machine Learning"
},
{
"code": null,
"e": 4312,
"s": 4214,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4335,
"s": 4312,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 4358,
"s": 4335,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 4395,
"s": 4358,
"text": "Supervised and Unsupervised learning"
},
{
"code": null,
"e": 4419,
"s": 4395,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 4459,
"s": 4419,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 4487,
"s": 4459,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 4537,
"s": 4487,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 4559,
"s": 4537,
"text": "Python map() function"
}
] |
Program to find the angles of a quadrilateral
|
16 Jun, 2022
Given that all the angles of a quadrilateral are in AP having common difference βdβ, the task is to find all the angles.Examples:
Input: d = 10
Output: 75, 85, 95, 105
Input: d = 20
Output: 60, 80, 100, 120
Approach:
We know that the angles of the quadrilateral are in AP and having the common difference βdβ. So, if we assume the first angle to be βaβ then the other angles can be calculated as, βa+dβ, βa+2dβ and βa+3dβ And, from the properties of quadrilaterals, the sum of all the angles of a quadrilateral is 360. So, (a) + (a + d) + (a + 2*d) + (a + 3*d) = 360 4*a + 6*d = 360 a = (360 β (6*d)) / 4 where βaβ is the angle assumed in the beginning and βdβ is the common difference.
Below is the implementation of the above approach:
C++
Java
Python
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>#define ll long long intusing namespace std; // Driver codeint main(){ int d = 10; double a; // according to formula derived above a = (double)(360 - (6 * d)) / 4; // print all the angles cout << a << ", " << a + d << ", " << a + (2 * d) << ", " << a + (3 * d) << endl; return 0;}
// java implementation of the approach import java.io.*; class GFG { // Driver code public static void main (String[] args) { int d = 10; double a; // according to formula derived above a = (double)(360 - (6 * d)) / 4; // print all the angles System.out.print( a + ", " + (a + d) + ", " + (a + (2 * d)) + ", " + (a + (3 * d))); }}//This code is contributed//by inder_verma
# Python implementation# of the approachd = 10a = 0.0 # according to formula# derived abovea=(360 - (6 * d)) / 4 # print all the anglesprint(a,",", a + d, ",", a + 2 * d, ",", a + 3 * d, sep = ' ') # This code is contributed# by sahilshelangia
// C# implementation of the approachusing System; class GFG{ // Driver codepublic static void Main (){ int d = 10; double a; // according to formula derived above a = (double)(360 - (6 * d)) / 4; // print all the angles Console.WriteLine( a + ", " + (a + d) + ", " + (a + (2 * d)) + ", " + (a + (3 * d)));}} // This code is contributed// by anuj_67
<?php// PHP implementation of the approach // Driver code$d = 10; // according to formula// derived above$a = (360 - (6 * $d)) / 4 ; // print all the anglesecho $a, ", ", $a + $d , ", ", $a + (2 * $d), ", ", $a + (3 * $d); // This code is contributed// by ANKITRAI1?>
<script> // Javascript implementation of the approach // Driver codevar d = 10;var a; // according to formula derived abovea = parseInt((360 - (6 * d)) / 4); // print all the anglesdocument.write( a + ", " + (a + d) + ", " + (a + (2 * d)) + ", " + (a + (3 * d))); </script>
Time complexity: O(1)
Auxiliary Space: O(1)
sahilshelangia
inderDuMCA
ankthon
vt_m
rutvik_56
hasani
arithmetic progression
Competitive Programming
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Most important type of Algorithms
The Ultimate Beginner's Guide For DSA
Find two numbers from their sum and XOR
Equal Sum and XOR of three Numbers
C++: Methods of code shortening in competitive programming
Program for distance between two points on earth
Closest Pair of Points using Divide and Conquer algorithm
How to check if a given point lies inside or outside a polygon?
How to check if two given line segments intersect?
Optimum location of point to minimize total distance
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 160,
"s": 28,
"text": "Given that all the angles of a quadrilateral are in AP having common difference βdβ, the task is to find all the angles.Examples: "
},
{
"code": null,
"e": 238,
"s": 160,
"text": "Input: d = 10\nOutput: 75, 85, 95, 105\n\nInput: d = 20\nOutput: 60, 80, 100, 120"
},
{
"code": null,
"e": 251,
"s": 240,
"text": "Approach: "
},
{
"code": null,
"e": 723,
"s": 251,
"text": "We know that the angles of the quadrilateral are in AP and having the common difference βdβ. So, if we assume the first angle to be βaβ then the other angles can be calculated as, βa+dβ, βa+2dβ and βa+3dβ And, from the properties of quadrilaterals, the sum of all the angles of a quadrilateral is 360. So, (a) + (a + d) + (a + 2*d) + (a + 3*d) = 360 4*a + 6*d = 360 a = (360 β (6*d)) / 4 where βaβ is the angle assumed in the beginning and βdβ is the common difference. "
},
{
"code": null,
"e": 776,
"s": 723,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 780,
"s": 776,
"text": "C++"
},
{
"code": null,
"e": 785,
"s": 780,
"text": "Java"
},
{
"code": null,
"e": 792,
"s": 785,
"text": "Python"
},
{
"code": null,
"e": 795,
"s": 792,
"text": "C#"
},
{
"code": null,
"e": 799,
"s": 795,
"text": "PHP"
},
{
"code": null,
"e": 810,
"s": 799,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>#define ll long long intusing namespace std; // Driver codeint main(){ int d = 10; double a; // according to formula derived above a = (double)(360 - (6 * d)) / 4; // print all the angles cout << a << \", \" << a + d << \", \" << a + (2 * d) << \", \" << a + (3 * d) << endl; return 0;}",
"e": 1183,
"s": 810,
"text": null
},
{
"code": "// java implementation of the approach import java.io.*; class GFG { // Driver code public static void main (String[] args) { int d = 10; double a; // according to formula derived above a = (double)(360 - (6 * d)) / 4; // print all the angles System.out.print( a + \", \" + (a + d) + \", \" + (a + (2 * d)) + \", \" + (a + (3 * d))); }}//This code is contributed//by inder_verma",
"e": 1600,
"s": 1183,
"text": null
},
{
"code": "# Python implementation# of the approachd = 10a = 0.0 # according to formula# derived abovea=(360 - (6 * d)) / 4 # print all the anglesprint(a,\",\", a + d, \",\", a + 2 * d, \",\", a + 3 * d, sep = ' ') # This code is contributed# by sahilshelangia",
"e": 1851,
"s": 1600,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Driver codepublic static void Main (){ int d = 10; double a; // according to formula derived above a = (double)(360 - (6 * d)) / 4; // print all the angles Console.WriteLine( a + \", \" + (a + d) + \", \" + (a + (2 * d)) + \", \" + (a + (3 * d)));}} // This code is contributed// by anuj_67",
"e": 2280,
"s": 1851,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Driver code$d = 10; // according to formula// derived above$a = (360 - (6 * $d)) / 4 ; // print all the anglesecho $a, \", \", $a + $d , \", \", $a + (2 * $d), \", \", $a + (3 * $d); // This code is contributed// by ANKITRAI1?>",
"e": 2552,
"s": 2280,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Driver codevar d = 10;var a; // according to formula derived abovea = parseInt((360 - (6 * d)) / 4); // print all the anglesdocument.write( a + \", \" + (a + d) + \", \" + (a + (2 * d)) + \", \" + (a + (3 * d))); </script>",
"e": 2830,
"s": 2552,
"text": null
},
{
"code": null,
"e": 2852,
"s": 2830,
"text": "Time complexity: O(1)"
},
{
"code": null,
"e": 2874,
"s": 2852,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 2889,
"s": 2874,
"text": "sahilshelangia"
},
{
"code": null,
"e": 2900,
"s": 2889,
"text": "inderDuMCA"
},
{
"code": null,
"e": 2908,
"s": 2900,
"text": "ankthon"
},
{
"code": null,
"e": 2913,
"s": 2908,
"text": "vt_m"
},
{
"code": null,
"e": 2923,
"s": 2913,
"text": "rutvik_56"
},
{
"code": null,
"e": 2930,
"s": 2923,
"text": "hasani"
},
{
"code": null,
"e": 2953,
"s": 2930,
"text": "arithmetic progression"
},
{
"code": null,
"e": 2977,
"s": 2953,
"text": "Competitive Programming"
},
{
"code": null,
"e": 2987,
"s": 2977,
"text": "Geometric"
},
{
"code": null,
"e": 3000,
"s": 2987,
"text": "Mathematical"
},
{
"code": null,
"e": 3013,
"s": 3000,
"text": "Mathematical"
},
{
"code": null,
"e": 3023,
"s": 3013,
"text": "Geometric"
},
{
"code": null,
"e": 3121,
"s": 3023,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3155,
"s": 3121,
"text": "Most important type of Algorithms"
},
{
"code": null,
"e": 3193,
"s": 3155,
"text": "The Ultimate Beginner's Guide For DSA"
},
{
"code": null,
"e": 3233,
"s": 3193,
"text": "Find two numbers from their sum and XOR"
},
{
"code": null,
"e": 3268,
"s": 3233,
"text": "Equal Sum and XOR of three Numbers"
},
{
"code": null,
"e": 3327,
"s": 3268,
"text": "C++: Methods of code shortening in competitive programming"
},
{
"code": null,
"e": 3376,
"s": 3327,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 3434,
"s": 3376,
"text": "Closest Pair of Points using Divide and Conquer algorithm"
},
{
"code": null,
"e": 3498,
"s": 3434,
"text": "How to check if a given point lies inside or outside a polygon?"
},
{
"code": null,
"e": 3549,
"s": 3498,
"text": "How to check if two given line segments intersect?"
}
] |
How to create hash from string in JavaScript ?
|
14 Aug, 2019
In order to create a unique hash from a specific string, it can be implemented using their own string to hash converting function. It will return the hash equivalent of a string. Also, a library named Crypto can be used to generate various types of hashes like SHA1, MD5, SHA256 and many more.
Note: The hash value of an empty string is always zero.
Example 1:
<!DOCTYPE html><html> <head> <title> How to convert hash from string in JavaScript ? </title> <style> h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Creating hash from string in JavaScript?</h3> <p>The hash value of string "GeeksforGeeks" is .</p> <p id="geek"></p> <script> // Convert to 32bit integer function stringToHash(string) { var hash = 0; if (string.length == 0) return hash; for (i = 0; i < string.length; i++) { char = string.charCodeAt(i); hash = ((hash << 5) - hash) + char; hash = hash & hash; } return hash; } // String printing in hash var gfg = "GeeksforGeeks" document.getElementById("geek").innerHTML = stringToHash(gfg); </script> </center></body> </html>
Output:Example 2:
<script> // Importing 'crypto' module const crypto = require('crypto'), // Returns the names of supported hash algorithms // such as SHA1,MD5 hash = crypto.getHashes(); // Create hash of SHA1 type x = "Geek" // 'digest' is the output of hash function containing // only hexadecimal digits hashPwd = crypto.createHash('sha1').update(x).digest('hex'); console.log(hash); </script>
Output:
321cca8846c784b6f2d6ba628f8502a5fb0683ae
javascript-string
Picked
JavaScript
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
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Aug, 2019"
},
{
"code": null,
"e": 346,
"s": 52,
"text": "In order to create a unique hash from a specific string, it can be implemented using their own string to hash converting function. It will return the hash equivalent of a string. Also, a library named Crypto can be used to generate various types of hashes like SHA1, MD5, SHA256 and many more."
},
{
"code": null,
"e": 402,
"s": 346,
"text": "Note: The hash value of an empty string is always zero."
},
{
"code": null,
"e": 413,
"s": 402,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to convert hash from string in JavaScript ? </title> <style> h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Creating hash from string in JavaScript?</h3> <p>The hash value of string \"GeeksforGeeks\" is .</p> <p id=\"geek\"></p> <script> // Convert to 32bit integer function stringToHash(string) { var hash = 0; if (string.length == 0) return hash; for (i = 0; i < string.length; i++) { char = string.charCodeAt(i); hash = ((hash << 5) - hash) + char; hash = hash & hash; } return hash; } // String printing in hash var gfg = \"GeeksforGeeks\" document.getElementById(\"geek\").innerHTML = stringToHash(gfg); </script> </center></body> </html>",
"e": 1570,
"s": 413,
"text": null
},
{
"code": null,
"e": 1588,
"s": 1570,
"text": "Output:Example 2:"
},
{
"code": "<script> // Importing 'crypto' module const crypto = require('crypto'), // Returns the names of supported hash algorithms // such as SHA1,MD5 hash = crypto.getHashes(); // Create hash of SHA1 type x = \"Geek\" // 'digest' is the output of hash function containing // only hexadecimal digits hashPwd = crypto.createHash('sha1').update(x).digest('hex'); console.log(hash); </script>",
"e": 2012,
"s": 1588,
"text": null
},
{
"code": null,
"e": 2020,
"s": 2012,
"text": "Output:"
},
{
"code": null,
"e": 2061,
"s": 2020,
"text": "321cca8846c784b6f2d6ba628f8502a5fb0683ae"
},
{
"code": null,
"e": 2079,
"s": 2061,
"text": "javascript-string"
},
{
"code": null,
"e": 2086,
"s": 2079,
"text": "Picked"
},
{
"code": null,
"e": 2097,
"s": 2086,
"text": "JavaScript"
},
{
"code": null,
"e": 2114,
"s": 2097,
"text": "Web Technologies"
},
{
"code": null,
"e": 2141,
"s": 2114,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2239,
"s": 2141,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2300,
"s": 2239,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2372,
"s": 2300,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2412,
"s": 2372,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2465,
"s": 2412,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2517,
"s": 2465,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 2579,
"s": 2517,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2612,
"s": 2579,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2673,
"s": 2612,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2723,
"s": 2673,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
File getParent() method in Java with Examples
|
30 Jan, 2019
The getParent() method is a part of File class. This function returns the Parent of the given file object. The function returns a string object which contains the Parent of the given file object.If the abstract path does not contain any Parent then a null string is returned.
Function Signature:
public String getParent()
Function Syntax:
file.getParent()
Parameters: This function does not accept any parameters.
Return value: The function returns a String value which is the Parent of the given File object.
Below programs will illustrate the use of the getParent() function:
Example 1: We are given a file object of a file, we have to get the Parent of the file object.
// Java program to demonstrate the// use of getParent() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File("c:\\users\\program.txt"); // Get the Parent // of the given file f String Parent = f.getParent(); // Display the file Parent // of the file object System.out.println("File Parent : " + Parent); } catch (Exception e) { System.err.println(e.getMessage()); } }}
Output:
File Parent : c:\users
Example 2: We are given a file object of a directory, we have to get the Parent of the file object.
// Java program to demonstrate the// use of getParent() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File("c:\\users\\program"); // Get the Parent // of the given file f String Parent = f.getParent(); // Display the file Parent // of the file object System.out.println("File Parent : " + Parent); } catch (Exception e) { System.err.println(e.getMessage()); } }}
Output:
File Parent : c:\users
The programs might not run in an online IDE. please use an offline IDE and set the Parent of the file
Java-File Class
Java-Functions
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jan, 2019"
},
{
"code": null,
"e": 304,
"s": 28,
"text": "The getParent() method is a part of File class. This function returns the Parent of the given file object. The function returns a string object which contains the Parent of the given file object.If the abstract path does not contain any Parent then a null string is returned."
},
{
"code": null,
"e": 324,
"s": 304,
"text": "Function Signature:"
},
{
"code": null,
"e": 350,
"s": 324,
"text": "public String getParent()"
},
{
"code": null,
"e": 367,
"s": 350,
"text": "Function Syntax:"
},
{
"code": null,
"e": 384,
"s": 367,
"text": "file.getParent()"
},
{
"code": null,
"e": 442,
"s": 384,
"text": "Parameters: This function does not accept any parameters."
},
{
"code": null,
"e": 538,
"s": 442,
"text": "Return value: The function returns a String value which is the Parent of the given File object."
},
{
"code": null,
"e": 606,
"s": 538,
"text": "Below programs will illustrate the use of the getParent() function:"
},
{
"code": null,
"e": 701,
"s": 606,
"text": "Example 1: We are given a file object of a file, we have to get the Parent of the file object."
},
{
"code": "// Java program to demonstrate the// use of getParent() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File(\"c:\\\\users\\\\program.txt\"); // Get the Parent // of the given file f String Parent = f.getParent(); // Display the file Parent // of the file object System.out.println(\"File Parent : \" + Parent); } catch (Exception e) { System.err.println(e.getMessage()); } }}",
"e": 1395,
"s": 701,
"text": null
},
{
"code": null,
"e": 1403,
"s": 1395,
"text": "Output:"
},
{
"code": null,
"e": 1427,
"s": 1403,
"text": "File Parent : c:\\users\n"
},
{
"code": null,
"e": 1527,
"s": 1427,
"text": "Example 2: We are given a file object of a directory, we have to get the Parent of the file object."
},
{
"code": "// Java program to demonstrate the// use of getParent() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File(\"c:\\\\users\\\\program\"); // Get the Parent // of the given file f String Parent = f.getParent(); // Display the file Parent // of the file object System.out.println(\"File Parent : \" + Parent); } catch (Exception e) { System.err.println(e.getMessage()); } }}",
"e": 2217,
"s": 1527,
"text": null
},
{
"code": null,
"e": 2225,
"s": 2217,
"text": "Output:"
},
{
"code": null,
"e": 2249,
"s": 2225,
"text": "File Parent : c:\\users\n"
},
{
"code": null,
"e": 2351,
"s": 2249,
"text": "The programs might not run in an online IDE. please use an offline IDE and set the Parent of the file"
},
{
"code": null,
"e": 2367,
"s": 2351,
"text": "Java-File Class"
},
{
"code": null,
"e": 2382,
"s": 2367,
"text": "Java-Functions"
},
{
"code": null,
"e": 2398,
"s": 2382,
"text": "Java-IO package"
},
{
"code": null,
"e": 2403,
"s": 2398,
"text": "Java"
},
{
"code": null,
"e": 2408,
"s": 2403,
"text": "Java"
}
] |
How to print N times without using loops or recursion ?
|
07 Jul, 2022
How to print βHelloβ N times (where N is user input) without using loop or recursion or goto.
Input : N, that represent the number of times you want to print the statement. Output : Statement for N times
First, we create a class. After that, we need to initialize the constructor of the class by writing the statement you want to print inside a cout/print statement. The basic idea used here that βThe no. of times you create the object of the class, the constructor of that class is called that many times.β
CPP
// CPP program to print a sentence N times// without loop and recursion.// Author : Rohan Prasad#include <iostream>using namespace std;class Print { public: Print() { cout << "Hello" << endl; }}; int main(){ int N = 5; Print a[N]; return 0;}
Hello
Hello
Hello
Hello
Hello
Time Complexity: O(N) Auxiliary Space: O(1), no extra space is required, so it is a constant.
manthu
jayanth_mkv
cpp-constructor
cpp-puzzle
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set in C++ Standard Template Library (STL)
Bitwise Operators in C/C++
Priority Queue in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Const keyword in C++
Processing strings using std::istringstream
Sorting a Map by value in C++ STL
Expression must have class type error in C++
C++ Program For Merge Sort Of Linked Lists
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 146,
"s": 52,
"text": "How to print βHelloβ N times (where N is user input) without using loop or recursion or goto."
},
{
"code": null,
"e": 256,
"s": 146,
"text": "Input : N, that represent the number of times you want to print the statement. Output : Statement for N times"
},
{
"code": null,
"e": 562,
"s": 256,
"text": "First, we create a class. After that, we need to initialize the constructor of the class by writing the statement you want to print inside a cout/print statement. The basic idea used here that βThe no. of times you create the object of the class, the constructor of that class is called that many times.β "
},
{
"code": null,
"e": 566,
"s": 562,
"text": "CPP"
},
{
"code": "// CPP program to print a sentence N times// without loop and recursion.// Author : Rohan Prasad#include <iostream>using namespace std;class Print { public: Print() { cout << \"Hello\" << endl; }}; int main(){ int N = 5; Print a[N]; return 0;}",
"e": 817,
"s": 566,
"text": null
},
{
"code": null,
"e": 847,
"s": 817,
"text": "Hello\nHello\nHello\nHello\nHello"
},
{
"code": null,
"e": 941,
"s": 847,
"text": "Time Complexity: O(N) Auxiliary Space: O(1), no extra space is required, so it is a constant."
},
{
"code": null,
"e": 948,
"s": 941,
"text": "manthu"
},
{
"code": null,
"e": 960,
"s": 948,
"text": "jayanth_mkv"
},
{
"code": null,
"e": 976,
"s": 960,
"text": "cpp-constructor"
},
{
"code": null,
"e": 987,
"s": 976,
"text": "cpp-puzzle"
},
{
"code": null,
"e": 991,
"s": 987,
"text": "C++"
},
{
"code": null,
"e": 1004,
"s": 991,
"text": "C++ Programs"
},
{
"code": null,
"e": 1008,
"s": 1004,
"text": "CPP"
},
{
"code": null,
"e": 1106,
"s": 1008,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1149,
"s": 1106,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1176,
"s": 1149,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 1230,
"s": 1176,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1264,
"s": 1230,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 1289,
"s": 1264,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 1310,
"s": 1289,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 1354,
"s": 1310,
"text": "Processing strings using std::istringstream"
},
{
"code": null,
"e": 1388,
"s": 1354,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 1433,
"s": 1388,
"text": "Expression must have class type error in C++"
}
] |
GATE | GATE CS 2019 | Question 59
|
20 Feb, 2019
What is the minimum number of 2-input NOR gates required to implement 4-variable function expressed in sum-of-minterms from as f = Ξ£(0, 2, 5, 7, 8, 10, 13, 15)? Assume that all the inputs and their complements are available. Answer ________ .
Note: This was Numerical Type question.(A) 3(B) 4(C) 5(D) 6Answer: (A)Explanation: K-map for given,
f = Ξ£(0, 2, 5, 7, 8, 10, 13, 15)
Therefore,
f = BD +B'D'
= (B' + D).(B + D')
Since all the inputs and their complements are available, so circuit implementation using NOR gate:
F can be implemented using 3 NOR gates.
So, option (A) is correct.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 46
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 49
GATE | GATE-CS-2004 | Question 31
GATE | GATE CS 1996 | Question 63
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n20 Feb, 2019"
},
{
"code": null,
"e": 296,
"s": 53,
"text": "What is the minimum number of 2-input NOR gates required to implement 4-variable function expressed in sum-of-minterms from as f = Ξ£(0, 2, 5, 7, 8, 10, 13, 15)? Assume that all the inputs and their complements are available. Answer ________ ."
},
{
"code": null,
"e": 396,
"s": 296,
"text": "Note: This was Numerical Type question.(A) 3(B) 4(C) 5(D) 6Answer: (A)Explanation: K-map for given,"
},
{
"code": null,
"e": 429,
"s": 396,
"text": "f = Ξ£(0, 2, 5, 7, 8, 10, 13, 15)"
},
{
"code": null,
"e": 440,
"s": 429,
"text": "Therefore,"
},
{
"code": null,
"e": 474,
"s": 440,
"text": "f = BD +B'D' \n= (B' + D).(B + D')"
},
{
"code": null,
"e": 574,
"s": 474,
"text": "Since all the inputs and their complements are available, so circuit implementation using NOR gate:"
},
{
"code": null,
"e": 614,
"s": 574,
"text": "F can be implemented using 3 NOR gates."
},
{
"code": null,
"e": 662,
"s": 614,
"text": "So, option (A) is correct.Quiz of this Question"
},
{
"code": null,
"e": 667,
"s": 662,
"text": "GATE"
},
{
"code": null,
"e": 765,
"s": 667,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 807,
"s": 765,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 869,
"s": 807,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 911,
"s": 869,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 20"
},
{
"code": null,
"e": 945,
"s": 911,
"text": "GATE | GATE CS 2008 | Question 46"
},
{
"code": null,
"e": 979,
"s": 945,
"text": "GATE | GATE CS 2008 | Question 40"
},
{
"code": null,
"e": 1021,
"s": 979,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 1063,
"s": 1021,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 1097,
"s": 1063,
"text": "GATE | GATE CS 2011 | Question 49"
},
{
"code": null,
"e": 1131,
"s": 1097,
"text": "GATE | GATE-CS-2004 | Question 31"
}
] |
JavaScript contextmenu MouseEvent
|
06 Oct, 2021
When we click the right mouse button on our desktop, a menu-like box appears and this box is called the context menu. In JavaScript, a context menu event runs when a user tries to open a context menu. This can be done by clicking the right mouse button.
This article demonstrates executing any operation when we click the right mouse button. For example, we want to change the background color of a box when we click the right mouse button.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> <!-- Adding some CSS --> <style> .context { border: 1px solid black; background: gREEN; width: 200px; padding: 10px; color: white; } </style> <body> <div class="context"> <p>Click right mouse button</p> </div> <!-- JavaScript code to change content when we click right mouse button --> <script> // To prevent default operation of right mouse click document.addEventListener("contextmenu", (e) => { e.preventDefault(); }); const contextMenu = document.querySelector(".context"); contextMenu.addEventListener("contextmenu", (e) => { e.preventDefault(); contextMenu.textContent = "GeeksForGeeks"; }); </script> </body></html>
Output : The following output will be shown in the browser and when we click the right mouse button on the box in the above image.
Before right click:
After right click:
Note: Using this method we can perform a lot of things, we can add a menu on our right-click.
prachisoda1234
JavaScript-Events
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 309,
"s": 54,
"text": "When we click the right mouse button on our desktop, a menu-like box appears and this box is called the context menu. In JavaScript, a context menu event runs when a user tries to open a context menu. This can be done by clicking the right mouse button. "
},
{
"code": null,
"e": 496,
"s": 309,
"text": "This article demonstrates executing any operation when we click the right mouse button. For example, we want to change the background color of a box when we click the right mouse button."
},
{
"code": null,
"e": 501,
"s": 496,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> </head> <!-- Adding some CSS --> <style> .context { border: 1px solid black; background: gREEN; width: 200px; padding: 10px; color: white; } </style> <body> <div class=\"context\"> <p>Click right mouse button</p> </div> <!-- JavaScript code to change content when we click right mouse button --> <script> // To prevent default operation of right mouse click document.addEventListener(\"contextmenu\", (e) => { e.preventDefault(); }); const contextMenu = document.querySelector(\".context\"); contextMenu.addEventListener(\"contextmenu\", (e) => { e.preventDefault(); contextMenu.textContent = \"GeeksForGeeks\"; }); </script> </body></html>",
"e": 1480,
"s": 501,
"text": null
},
{
"code": null,
"e": 1611,
"s": 1480,
"text": "Output : The following output will be shown in the browser and when we click the right mouse button on the box in the above image."
},
{
"code": null,
"e": 1633,
"s": 1611,
"text": "Before right click: "
},
{
"code": null,
"e": 1654,
"s": 1633,
"text": "After right click: "
},
{
"code": null,
"e": 1748,
"s": 1654,
"text": "Note: Using this method we can perform a lot of things, we can add a menu on our right-click."
},
{
"code": null,
"e": 1763,
"s": 1748,
"text": "prachisoda1234"
},
{
"code": null,
"e": 1781,
"s": 1763,
"text": "JavaScript-Events"
},
{
"code": null,
"e": 1788,
"s": 1781,
"text": "Picked"
},
{
"code": null,
"e": 1799,
"s": 1788,
"text": "JavaScript"
},
{
"code": null,
"e": 1816,
"s": 1799,
"text": "Web Technologies"
},
{
"code": null,
"e": 1914,
"s": 1816,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1975,
"s": 1914,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2015,
"s": 1975,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2056,
"s": 2015,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2098,
"s": 2056,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2120,
"s": 2098,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 2182,
"s": 2120,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2215,
"s": 2182,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2276,
"s": 2215,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2326,
"s": 2276,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python Math Module
|
18 Aug, 2021
Sometimes when working with some kind of financial or scientific projects it becomes necessary to implement mathematical calculations in the project. Python provides the math module to deal with such calculations. Math module provides functions to deal with both basic operations such as addition(+), subtraction(-), multiplication(*), division(/) and advance operations like trigonometric, logarithmic, exponential functions.
In this article, we learn about the math module from basics to advance using the help of a huge dataset containing functions explained with the help of good examples.
Math module provides various the value of various constants like pi, tau. Having such constants saves the time of writing the value of each constant every time we want to use it and that too with great precision. Constants provided by the math module are β
Eulerβs Number
Pi
Tau
Infinity
Not a Number (NaN)
Letβs see each constant in detail.
The math.e constant returns the Eulerβs number: 2.71828182846.
Syntax:
math.e
Example:
Python3
# Import math Libraryimport math # Print the value of Euler eprint (math.e)
Output:
2.718281828459045
You all must be familiar with pi. The pi is depicted as either 22/7 or 3.14. math.pi provides a more precise value for the pi.
Syntax:
math.pi
Example 1:
Python3
# Import math Libraryimport math # Print the value of piprint (math.pi)
Output:
3.141592653589793
Example 2: Letβs find the area of the circle
Python3
# Import math Libraryimport math # radius of the circler = 4 # value of piepie = math.pi # area of the circleprint(pie * r * r)
Output:
50.26548245743669
Tau is defined as the ratio of the circumference to the radius of a circle. The math.tau constant returns the value tau: 6.283185307179586.
Syntax:
math.tau
Example:
Python3
# Import math Libraryimport math # Print the value of tauprint (math.tau)
Output:
6.283185307179586
Infinity basically means something which is never-ending or boundless from both directions i.e. negative and positive. It cannot be depicted by a number. The math.inf constant returns of positive infinity. For negative infinity, use -math.inf.
Syntax:
math.inf
Example 1:
Python3
# Import math Libraryimport math # Print the positive infinityprint (math.inf) # Print the negative infinityprint (-math.inf)
Output:
inf
-inf
Example 2: Comparing the values of infinity with the maximum floating point value
Python3
# Import math Libraryimport math print (math.inf > 10e108)print (-math.inf < -10e108)
Output:
True
True
The math.nan constant returns a floating-point nan (Not a Number) value. This value is not a legal number. The nan constant is equivalent to float(βnanβ).
Example:
Python3
# Import math Libraryimport math # Print the value of nanprint (math.nan)
Output:
nan
In this section, we will deal with the functions that are used with number theory as well as representation theory such as finding the factorial of a number.
Ceil value means the smallest integral value greater than the number and the floor value means the greatest integral value smaller than the number. This can be easily calculated using the ceil() and floor() method respectively.
Example:
Python3
# Python code to demonstrate the working of# ceil() and floor() # importing "math" for mathematical operationsimport math a = 2.3 # returning the ceil of 2.3print ("The ceil of 2.3 is : ", end="")print (math.ceil(a)) # returning the floor of 2.3print ("The floor of 2.3 is : ", end="")print (math.floor(a))
Output:
The ceil of 2.3 is : 3
The floor of 2.3 is : 2
Using the factorial() function we can find the factorial of a number in a single line of the code. An error message is displayed if number is not integral.
Example:
Python3
# Python code to demonstrate the working of# factorial() # importing "math" for mathematical operationsimport math a = 5 # returning the factorial of 5print("The factorial of 5 is : ", end="")print(math.factorial(a))
Output:
The factorial of 5 is : 120
gcd() function is used to find the greatest common divisor of two numbers passed as the arguments.
Example:
Python3
# Python code to demonstrate the working of# gcd() # importing "math" for mathematical operationsimport math a = 15b = 5 # returning the gcd of 15 and 5print ("The gcd of 5 and 15 is : ", end="")print (math.gcd(b, a))
Output:
The gcd of 5 and 15 is : 5
fabs() function returns the absolute value of the number.
Example:
Python3
# Python code to demonstrate the working of# fabs() # importing "math" for mathematical operationsimport math a = -10 # returning the absolute value.print ("The absolute value of -10 is : ", end="")print (math.fabs(a))
Output:
The absolute value of -10 is : 10.0
Refer to the below article to get detailed information about the numeric functions.
Mathematical Functions in Python | Set 1 (Numeric Functions)
Power functions can be expressed as x^n where n is the power of x whereas logarithmic functions are considered as the inverse of exponential functions.
exp() method is used to calculate the power of e i.e. or we can say exponential of y.
Example:
Python3
# Python3 code to demonstrate# the working of exp()import math # initializing the valuetest_int = 4test_neg_int = -3test_float = 0.00 # checking exp() values# with different numbersprint (math.exp(test_int))print (math.exp(test_neg_int))print (math.exp(test_float))
Output:
54.598150033144236
0.049787068367863944
1.0
pow() function computes x**y. This function first converts its arguments into float and then computes the power.
Example:
Python3
# Python code to demonstrate pow()# version 1 print ("The value of 3**4 is : ",end="") # Returns 81print (pow(3,4))
Output:
The value of 3**4 is : 81.0
log() function returns the logarithmic value of a with base b. If the base is not mentioned, the computed value is of the natural log.
log2(a) function computes value of log a with base 2. This value is more accurate than the value of the function discussed above.
log10(a) function computes value of log a with base 10. This value is more accurate than the value of the function discussed above.
Python3
# Python code to demonstrate the working of# logarithm # importing "math" for mathematical operationsimport math # returning the log of 2,3print ("The value of log 2 with base 3 is : ", end="")print (math.log(2,3)) # returning the log2 of 16print ("The value of log2 of 16 is : ", end="")print (math.log2(16)) # returning the log10 of 10000print ("The value of log10 of 10000 is : ", end="")print (math.log10(10000))
Output:
The value of log 2 with base 3 is : 0.6309297535714574
The value of log2 of 16 is : 4.0
The value of log10 of 10000 is : 4.0
sqrt() function returns the square root of the number.
Example:
Python3
# Python3 program to demonstrate the# sqrt() method # import the math moduleimport math # print the square root of 0print(math.sqrt(0)) # print the square root of 4print(math.sqrt(4)) # print the square root of 3.5print(math.sqrt(3.5))
Output:
0.0
2.0
1.8708286933869707
Refer to the below article to get detailed information about the Logarithmic and Power Functions
Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions)
You all must know about Trigonometric and how it may become difficult to find the values of sine and cosine values of any angle. Math module provides built-in functions to find such values and even to change the values between degrees and radians.
sin(), cos(), and tan() functions returns the sine, cosine, and tangent of value passed as the argument. The value passed in this function should be in radians.
Example:
Python3
# Python code to demonstrate the working of# sin(), cos(), and tan() # importing "math" for mathematical operationsimport math a = math.pi/6 # returning the value of sine of pi/6print ("The value of sine of pi/6 is : ", end="")print (math.sin(a)) # returning the value of cosine of pi/6print ("The value of cosine of pi/6 is : ", end="")print (math.cos(a)) # returning the value of tangent of pi/6print ("The value of tangent of pi/6 is : ", end="")print (math.tan(a))
Output:
The value of sine of pi/6 is : 0.49999999999999994
The value of cosine of pi/6 is : 0.8660254037844387
The value of tangent of pi/6 is : 0.5773502691896257
degrees() function is used to convert argument value from radians to degrees.
radians() function is used to convert argument value from degrees to radians.
Example:
Python3
# Python code to demonstrate the working of# degrees() and radians() # importing "math" for mathematical operationsimport math a = math.pi/6b = 30 # returning the converted value from radians to degreesprint ("The converted value from radians to degrees is : ", end="")print (math.degrees(a)) # returning the converted value from degrees to radiansprint ("The converted value from degrees to radians is : ", end="")print (math.radians(b))
Output:
The converted value from radians to degrees is : 29.999999999999996
The converted value from degrees to radians is : 0.5235987755982988
Refer to the below articles to get detailed information about the trigonometric and angular functions.
Mathematical Functions in Python | Set 3 (Trigonometric and Angular Functions)
Besides all the numeric, logarithmic functions we have discussed yet, the math module provides some more useful functions that does not fall under any category discussed above but may become handy at some point while coding.
The gamma() function is used to return the gamma value of the argument.
Example:
Python3
# Python code to demonstrate# working of gamma()import math # initializing argumentgamma_var = 6 # Printing the gamma value.print ("The gamma value of the given argument is : " + str(math.gamma(gamma_var)))
Output:
The gamma value of the given argument is : 120.0
isinf() function is used to check whether the value is infinity or not.
Example:
Python3
# Python3 code to demonstrate# the working of isnan()import math # checking isnan() values# with inbuilt numbersprint (math.isinf(math.pi))print (math.isinf(math.e)) # checking for NaN valueprint (math.isinf(float('inf')))
Output:
False
False
True
isnan() function returns true if the number is βNaNβ else returns false.
Example:
Python3
# Python3 code to demonstrate# the working of isnan()import math # checking isnan() values# with inbuilt numbersprint (math.isnan(math.pi))print (math.isnan(math.e)) # checking for NaN valueprint (math.isnan(float('nan')))
Output:
False
False
True
Refer to the below article to get detailed information about the special functions.
Mathematical Functions in Python | Set 4 (Special Functions and Constants)
List of Mathematical function in Python
nikhilaggarwal3
Python math-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Aug, 2021"
},
{
"code": null,
"e": 455,
"s": 28,
"text": "Sometimes when working with some kind of financial or scientific projects it becomes necessary to implement mathematical calculations in the project. Python provides the math module to deal with such calculations. Math module provides functions to deal with both basic operations such as addition(+), subtraction(-), multiplication(*), division(/) and advance operations like trigonometric, logarithmic, exponential functions."
},
{
"code": null,
"e": 622,
"s": 455,
"text": "In this article, we learn about the math module from basics to advance using the help of a huge dataset containing functions explained with the help of good examples."
},
{
"code": null,
"e": 880,
"s": 622,
"text": "Math module provides various the value of various constants like pi, tau. Having such constants saves the time of writing the value of each constant every time we want to use it and that too with great precision. Constants provided by the math module are β "
},
{
"code": null,
"e": 895,
"s": 880,
"text": "Eulerβs Number"
},
{
"code": null,
"e": 898,
"s": 895,
"text": "Pi"
},
{
"code": null,
"e": 902,
"s": 898,
"text": "Tau"
},
{
"code": null,
"e": 911,
"s": 902,
"text": "Infinity"
},
{
"code": null,
"e": 930,
"s": 911,
"text": "Not a Number (NaN)"
},
{
"code": null,
"e": 965,
"s": 930,
"text": "Letβs see each constant in detail."
},
{
"code": null,
"e": 1028,
"s": 965,
"text": "The math.e constant returns the Eulerβs number: 2.71828182846."
},
{
"code": null,
"e": 1036,
"s": 1028,
"text": "Syntax:"
},
{
"code": null,
"e": 1043,
"s": 1036,
"text": "math.e"
},
{
"code": null,
"e": 1052,
"s": 1043,
"text": "Example:"
},
{
"code": null,
"e": 1060,
"s": 1052,
"text": "Python3"
},
{
"code": "# Import math Libraryimport math # Print the value of Euler eprint (math.e)",
"e": 1136,
"s": 1060,
"text": null
},
{
"code": null,
"e": 1144,
"s": 1136,
"text": "Output:"
},
{
"code": null,
"e": 1162,
"s": 1144,
"text": "2.718281828459045"
},
{
"code": null,
"e": 1289,
"s": 1162,
"text": "You all must be familiar with pi. The pi is depicted as either 22/7 or 3.14. math.pi provides a more precise value for the pi."
},
{
"code": null,
"e": 1297,
"s": 1289,
"text": "Syntax:"
},
{
"code": null,
"e": 1305,
"s": 1297,
"text": "math.pi"
},
{
"code": null,
"e": 1316,
"s": 1305,
"text": "Example 1:"
},
{
"code": null,
"e": 1324,
"s": 1316,
"text": "Python3"
},
{
"code": "# Import math Libraryimport math # Print the value of piprint (math.pi)",
"e": 1396,
"s": 1324,
"text": null
},
{
"code": null,
"e": 1404,
"s": 1396,
"text": "Output:"
},
{
"code": null,
"e": 1422,
"s": 1404,
"text": "3.141592653589793"
},
{
"code": null,
"e": 1468,
"s": 1422,
"text": "Example 2: Letβs find the area of the circle "
},
{
"code": null,
"e": 1476,
"s": 1468,
"text": "Python3"
},
{
"code": "# Import math Libraryimport math # radius of the circler = 4 # value of piepie = math.pi # area of the circleprint(pie * r * r)",
"e": 1604,
"s": 1476,
"text": null
},
{
"code": null,
"e": 1612,
"s": 1604,
"text": "Output:"
},
{
"code": null,
"e": 1630,
"s": 1612,
"text": "50.26548245743669"
},
{
"code": null,
"e": 1770,
"s": 1630,
"text": "Tau is defined as the ratio of the circumference to the radius of a circle. The math.tau constant returns the value tau: 6.283185307179586."
},
{
"code": null,
"e": 1778,
"s": 1770,
"text": "Syntax:"
},
{
"code": null,
"e": 1787,
"s": 1778,
"text": "math.tau"
},
{
"code": null,
"e": 1796,
"s": 1787,
"text": "Example:"
},
{
"code": null,
"e": 1804,
"s": 1796,
"text": "Python3"
},
{
"code": "# Import math Libraryimport math # Print the value of tauprint (math.tau)",
"e": 1878,
"s": 1804,
"text": null
},
{
"code": null,
"e": 1886,
"s": 1878,
"text": "Output:"
},
{
"code": null,
"e": 1904,
"s": 1886,
"text": "6.283185307179586"
},
{
"code": null,
"e": 2148,
"s": 1904,
"text": "Infinity basically means something which is never-ending or boundless from both directions i.e. negative and positive. It cannot be depicted by a number. The math.inf constant returns of positive infinity. For negative infinity, use -math.inf."
},
{
"code": null,
"e": 2156,
"s": 2148,
"text": "Syntax:"
},
{
"code": null,
"e": 2165,
"s": 2156,
"text": "math.inf"
},
{
"code": null,
"e": 2176,
"s": 2165,
"text": "Example 1:"
},
{
"code": null,
"e": 2184,
"s": 2176,
"text": "Python3"
},
{
"code": "# Import math Libraryimport math # Print the positive infinityprint (math.inf) # Print the negative infinityprint (-math.inf)",
"e": 2310,
"s": 2184,
"text": null
},
{
"code": null,
"e": 2318,
"s": 2310,
"text": "Output:"
},
{
"code": null,
"e": 2327,
"s": 2318,
"text": "inf\n-inf"
},
{
"code": null,
"e": 2409,
"s": 2327,
"text": "Example 2: Comparing the values of infinity with the maximum floating point value"
},
{
"code": null,
"e": 2417,
"s": 2409,
"text": "Python3"
},
{
"code": "# Import math Libraryimport math print (math.inf > 10e108)print (-math.inf < -10e108)",
"e": 2503,
"s": 2417,
"text": null
},
{
"code": null,
"e": 2511,
"s": 2503,
"text": "Output:"
},
{
"code": null,
"e": 2521,
"s": 2511,
"text": "True\nTrue"
},
{
"code": null,
"e": 2676,
"s": 2521,
"text": "The math.nan constant returns a floating-point nan (Not a Number) value. This value is not a legal number. The nan constant is equivalent to float(βnanβ)."
},
{
"code": null,
"e": 2685,
"s": 2676,
"text": "Example:"
},
{
"code": null,
"e": 2693,
"s": 2685,
"text": "Python3"
},
{
"code": "# Import math Libraryimport math # Print the value of nanprint (math.nan)",
"e": 2767,
"s": 2693,
"text": null
},
{
"code": null,
"e": 2775,
"s": 2767,
"text": "Output:"
},
{
"code": null,
"e": 2779,
"s": 2775,
"text": "nan"
},
{
"code": null,
"e": 2937,
"s": 2779,
"text": "In this section, we will deal with the functions that are used with number theory as well as representation theory such as finding the factorial of a number."
},
{
"code": null,
"e": 3165,
"s": 2937,
"text": "Ceil value means the smallest integral value greater than the number and the floor value means the greatest integral value smaller than the number. This can be easily calculated using the ceil() and floor() method respectively."
},
{
"code": null,
"e": 3174,
"s": 3165,
"text": "Example:"
},
{
"code": null,
"e": 3182,
"s": 3174,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# ceil() and floor() # importing \"math\" for mathematical operationsimport math a = 2.3 # returning the ceil of 2.3print (\"The ceil of 2.3 is : \", end=\"\")print (math.ceil(a)) # returning the floor of 2.3print (\"The floor of 2.3 is : \", end=\"\")print (math.floor(a))",
"e": 3489,
"s": 3182,
"text": null
},
{
"code": null,
"e": 3497,
"s": 3489,
"text": "Output:"
},
{
"code": null,
"e": 3544,
"s": 3497,
"text": "The ceil of 2.3 is : 3\nThe floor of 2.3 is : 2"
},
{
"code": null,
"e": 3700,
"s": 3544,
"text": "Using the factorial() function we can find the factorial of a number in a single line of the code. An error message is displayed if number is not integral."
},
{
"code": null,
"e": 3709,
"s": 3700,
"text": "Example:"
},
{
"code": null,
"e": 3717,
"s": 3709,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# factorial() # importing \"math\" for mathematical operationsimport math a = 5 # returning the factorial of 5print(\"The factorial of 5 is : \", end=\"\")print(math.factorial(a))",
"e": 3934,
"s": 3717,
"text": null
},
{
"code": null,
"e": 3942,
"s": 3934,
"text": "Output:"
},
{
"code": null,
"e": 3970,
"s": 3942,
"text": "The factorial of 5 is : 120"
},
{
"code": null,
"e": 4070,
"s": 3970,
"text": "gcd() function is used to find the greatest common divisor of two numbers passed as the arguments. "
},
{
"code": null,
"e": 4079,
"s": 4070,
"text": "Example:"
},
{
"code": null,
"e": 4087,
"s": 4079,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# gcd() # importing \"math\" for mathematical operationsimport math a = 15b = 5 # returning the gcd of 15 and 5print (\"The gcd of 5 and 15 is : \", end=\"\")print (math.gcd(b, a))",
"e": 4305,
"s": 4087,
"text": null
},
{
"code": null,
"e": 4313,
"s": 4305,
"text": "Output:"
},
{
"code": null,
"e": 4340,
"s": 4313,
"text": "The gcd of 5 and 15 is : 5"
},
{
"code": null,
"e": 4398,
"s": 4340,
"text": "fabs() function returns the absolute value of the number."
},
{
"code": null,
"e": 4407,
"s": 4398,
"text": "Example:"
},
{
"code": null,
"e": 4415,
"s": 4407,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# fabs() # importing \"math\" for mathematical operationsimport math a = -10 # returning the absolute value.print (\"The absolute value of -10 is : \", end=\"\")print (math.fabs(a))",
"e": 4634,
"s": 4415,
"text": null
},
{
"code": null,
"e": 4642,
"s": 4634,
"text": "Output:"
},
{
"code": null,
"e": 4678,
"s": 4642,
"text": "The absolute value of -10 is : 10.0"
},
{
"code": null,
"e": 4762,
"s": 4678,
"text": "Refer to the below article to get detailed information about the numeric functions."
},
{
"code": null,
"e": 4823,
"s": 4762,
"text": "Mathematical Functions in Python | Set 1 (Numeric Functions)"
},
{
"code": null,
"e": 4975,
"s": 4823,
"text": "Power functions can be expressed as x^n where n is the power of x whereas logarithmic functions are considered as the inverse of exponential functions."
},
{
"code": null,
"e": 5062,
"s": 4975,
"text": "exp() method is used to calculate the power of e i.e. or we can say exponential of y."
},
{
"code": null,
"e": 5071,
"s": 5062,
"text": "Example:"
},
{
"code": null,
"e": 5079,
"s": 5071,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# the working of exp()import math # initializing the valuetest_int = 4test_neg_int = -3test_float = 0.00 # checking exp() values# with different numbersprint (math.exp(test_int))print (math.exp(test_neg_int))print (math.exp(test_float))",
"e": 5345,
"s": 5079,
"text": null
},
{
"code": null,
"e": 5353,
"s": 5345,
"text": "Output:"
},
{
"code": null,
"e": 5397,
"s": 5353,
"text": "54.598150033144236\n0.049787068367863944\n1.0"
},
{
"code": null,
"e": 5510,
"s": 5397,
"text": "pow() function computes x**y. This function first converts its arguments into float and then computes the power."
},
{
"code": null,
"e": 5519,
"s": 5510,
"text": "Example:"
},
{
"code": null,
"e": 5527,
"s": 5519,
"text": "Python3"
},
{
"code": "# Python code to demonstrate pow()# version 1 print (\"The value of 3**4 is : \",end=\"\") # Returns 81print (pow(3,4))",
"e": 5643,
"s": 5527,
"text": null
},
{
"code": null,
"e": 5651,
"s": 5643,
"text": "Output:"
},
{
"code": null,
"e": 5679,
"s": 5651,
"text": "The value of 3**4 is : 81.0"
},
{
"code": null,
"e": 5814,
"s": 5679,
"text": "log() function returns the logarithmic value of a with base b. If the base is not mentioned, the computed value is of the natural log."
},
{
"code": null,
"e": 5944,
"s": 5814,
"text": "log2(a) function computes value of log a with base 2. This value is more accurate than the value of the function discussed above."
},
{
"code": null,
"e": 6076,
"s": 5944,
"text": "log10(a) function computes value of log a with base 10. This value is more accurate than the value of the function discussed above."
},
{
"code": null,
"e": 6084,
"s": 6076,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# logarithm # importing \"math\" for mathematical operationsimport math # returning the log of 2,3print (\"The value of log 2 with base 3 is : \", end=\"\")print (math.log(2,3)) # returning the log2 of 16print (\"The value of log2 of 16 is : \", end=\"\")print (math.log2(16)) # returning the log10 of 10000print (\"The value of log10 of 10000 is : \", end=\"\")print (math.log10(10000))",
"e": 6505,
"s": 6084,
"text": null
},
{
"code": null,
"e": 6513,
"s": 6505,
"text": "Output:"
},
{
"code": null,
"e": 6638,
"s": 6513,
"text": "The value of log 2 with base 3 is : 0.6309297535714574\nThe value of log2 of 16 is : 4.0\nThe value of log10 of 10000 is : 4.0"
},
{
"code": null,
"e": 6694,
"s": 6638,
"text": "sqrt() function returns the square root of the number. "
},
{
"code": null,
"e": 6703,
"s": 6694,
"text": "Example:"
},
{
"code": null,
"e": 6711,
"s": 6703,
"text": "Python3"
},
{
"code": "# Python3 program to demonstrate the# sqrt() method # import the math moduleimport math # print the square root of 0print(math.sqrt(0)) # print the square root of 4print(math.sqrt(4)) # print the square root of 3.5print(math.sqrt(3.5))",
"e": 6947,
"s": 6711,
"text": null
},
{
"code": null,
"e": 6955,
"s": 6947,
"text": "Output:"
},
{
"code": null,
"e": 6982,
"s": 6955,
"text": "0.0\n2.0\n1.8708286933869707"
},
{
"code": null,
"e": 7079,
"s": 6982,
"text": "Refer to the below article to get detailed information about the Logarithmic and Power Functions"
},
{
"code": null,
"e": 7154,
"s": 7079,
"text": "Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions)"
},
{
"code": null,
"e": 7402,
"s": 7154,
"text": "You all must know about Trigonometric and how it may become difficult to find the values of sine and cosine values of any angle. Math module provides built-in functions to find such values and even to change the values between degrees and radians."
},
{
"code": null,
"e": 7563,
"s": 7402,
"text": "sin(), cos(), and tan() functions returns the sine, cosine, and tangent of value passed as the argument. The value passed in this function should be in radians."
},
{
"code": null,
"e": 7572,
"s": 7563,
"text": "Example:"
},
{
"code": null,
"e": 7580,
"s": 7572,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# sin(), cos(), and tan() # importing \"math\" for mathematical operationsimport math a = math.pi/6 # returning the value of sine of pi/6print (\"The value of sine of pi/6 is : \", end=\"\")print (math.sin(a)) # returning the value of cosine of pi/6print (\"The value of cosine of pi/6 is : \", end=\"\")print (math.cos(a)) # returning the value of tangent of pi/6print (\"The value of tangent of pi/6 is : \", end=\"\")print (math.tan(a))",
"e": 8049,
"s": 7580,
"text": null
},
{
"code": null,
"e": 8057,
"s": 8049,
"text": "Output:"
},
{
"code": null,
"e": 8213,
"s": 8057,
"text": "The value of sine of pi/6 is : 0.49999999999999994\nThe value of cosine of pi/6 is : 0.8660254037844387\nThe value of tangent of pi/6 is : 0.5773502691896257"
},
{
"code": null,
"e": 8291,
"s": 8213,
"text": "degrees() function is used to convert argument value from radians to degrees."
},
{
"code": null,
"e": 8369,
"s": 8291,
"text": "radians() function is used to convert argument value from degrees to radians."
},
{
"code": null,
"e": 8378,
"s": 8369,
"text": "Example:"
},
{
"code": null,
"e": 8386,
"s": 8378,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# degrees() and radians() # importing \"math\" for mathematical operationsimport math a = math.pi/6b = 30 # returning the converted value from radians to degreesprint (\"The converted value from radians to degrees is : \", end=\"\")print (math.degrees(a)) # returning the converted value from degrees to radiansprint (\"The converted value from degrees to radians is : \", end=\"\")print (math.radians(b))",
"e": 8825,
"s": 8386,
"text": null
},
{
"code": null,
"e": 8833,
"s": 8825,
"text": "Output:"
},
{
"code": null,
"e": 8969,
"s": 8833,
"text": "The converted value from radians to degrees is : 29.999999999999996\nThe converted value from degrees to radians is : 0.5235987755982988"
},
{
"code": null,
"e": 9072,
"s": 8969,
"text": "Refer to the below articles to get detailed information about the trigonometric and angular functions."
},
{
"code": null,
"e": 9151,
"s": 9072,
"text": "Mathematical Functions in Python | Set 3 (Trigonometric and Angular Functions)"
},
{
"code": null,
"e": 9376,
"s": 9151,
"text": "Besides all the numeric, logarithmic functions we have discussed yet, the math module provides some more useful functions that does not fall under any category discussed above but may become handy at some point while coding."
},
{
"code": null,
"e": 9448,
"s": 9376,
"text": "The gamma() function is used to return the gamma value of the argument."
},
{
"code": null,
"e": 9457,
"s": 9448,
"text": "Example:"
},
{
"code": null,
"e": 9465,
"s": 9457,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# working of gamma()import math # initializing argumentgamma_var = 6 # Printing the gamma value.print (\"The gamma value of the given argument is : \" + str(math.gamma(gamma_var)))",
"e": 9691,
"s": 9465,
"text": null
},
{
"code": null,
"e": 9699,
"s": 9691,
"text": "Output:"
},
{
"code": null,
"e": 9748,
"s": 9699,
"text": "The gamma value of the given argument is : 120.0"
},
{
"code": null,
"e": 9820,
"s": 9748,
"text": "isinf() function is used to check whether the value is infinity or not."
},
{
"code": null,
"e": 9829,
"s": 9820,
"text": "Example:"
},
{
"code": null,
"e": 9837,
"s": 9829,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# the working of isnan()import math # checking isnan() values# with inbuilt numbersprint (math.isinf(math.pi))print (math.isinf(math.e)) # checking for NaN valueprint (math.isinf(float('inf')))",
"e": 10061,
"s": 9837,
"text": null
},
{
"code": null,
"e": 10069,
"s": 10061,
"text": "Output:"
},
{
"code": null,
"e": 10086,
"s": 10069,
"text": "False\nFalse\nTrue"
},
{
"code": null,
"e": 10159,
"s": 10086,
"text": "isnan() function returns true if the number is βNaNβ else returns false."
},
{
"code": null,
"e": 10168,
"s": 10159,
"text": "Example:"
},
{
"code": null,
"e": 10176,
"s": 10168,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# the working of isnan()import math # checking isnan() values# with inbuilt numbersprint (math.isnan(math.pi))print (math.isnan(math.e)) # checking for NaN valueprint (math.isnan(float('nan')))",
"e": 10400,
"s": 10176,
"text": null
},
{
"code": null,
"e": 10408,
"s": 10400,
"text": "Output:"
},
{
"code": null,
"e": 10425,
"s": 10408,
"text": "False\nFalse\nTrue"
},
{
"code": null,
"e": 10509,
"s": 10425,
"text": "Refer to the below article to get detailed information about the special functions."
},
{
"code": null,
"e": 10584,
"s": 10509,
"text": "Mathematical Functions in Python | Set 4 (Special Functions and Constants)"
},
{
"code": null,
"e": 10624,
"s": 10584,
"text": "List of Mathematical function in Python"
},
{
"code": null,
"e": 10640,
"s": 10624,
"text": "nikhilaggarwal3"
},
{
"code": null,
"e": 10660,
"s": 10640,
"text": "Python math-library"
},
{
"code": null,
"e": 10667,
"s": 10660,
"text": "Python"
}
] |
How to Configure the Eclipse with Apache Hadoop?
|
25 Jan, 2021
Eclipse is an IDE(Integrated Development Environment) that helps to create and build an application as per our requirement. And Hadoop is used for storing and processing big data. And if you have requirements to configure eclipse with Hadoop then you can follow this section step by step. Here, we will discuss 8 steps in which you will see the download, installation, and configuration part of an eclipse and will see how you can configure the Hadoop while installing and configuring an eclipse.
Step 1: Download and Install Eclipse IDE
It is the most popular IDE for developing java applications. It is easy to use and powerful IDE that is the reason behind the trust of many programmers. It can be downloaded from the given link below as follows.
http://www.eclipse.org/downloads/eclipse-packages
You will get a file named eclipse-committers-photon-R-linux-gtk.tar.gz.
We need to extract it using the command tar βzxvf eclipse-committers-photon-R-linux-gtk.tar.gz
Step 2: Move the eclipse folder to the home directory
In this step, you can see how to move the eclipse folder to the home directory. You can check the screenshot for your reference.
Step 3: Open Eclipse
Now, in this step, you can see the eclipse icon once you will successfully download and extract it to the required folder. And double click to open. You can see the screenshot for your reference.
Step 4: Execute Eclipse
Now choose a workspace directory and then click LAUNCH.
Step 5: Download required files
Hadoop-core-1.2.1.jar
commons-cli-1.2.jar
Step 6: Creating Java Project
Create a java project in the package explorer.
fileβ>newβ>java projectβ>finish
right clickβ>newβ>packageβ>finish
right click on packageβ>newβ>class_name
Step 7: Adding Reference libraries
Now add the following reference libraries as follows. First, we need to go to build path β>configure build path β> configure build path
Step 8: Adding .jar Files
Click on add external jars and browse to the folder where the files are downloaded and click open and select these two files i.e. hadoop-core-1.2.1.jar , commons-cli-1.2.jar.
Hadoop
MapReduce
Hadoop
How To
Hadoop
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create Table in Hive?
Apache Hive
What is Hadoop Streaming?
What is Schema On Read and Schema On Write in Hadoop?
MapReduce - Understanding With Real-Life Example
How to Install PIP on Windows ?
How to install Jupyter Notebook on Windows?
How to Install FFmpeg on Windows?
How to Find the Wi-Fi Password Using CMD in Windows?
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Jan, 2021"
},
{
"code": null,
"e": 551,
"s": 54,
"text": "Eclipse is an IDE(Integrated Development Environment) that helps to create and build an application as per our requirement. And Hadoop is used for storing and processing big data. And if you have requirements to configure eclipse with Hadoop then you can follow this section step by step. Here, we will discuss 8 steps in which you will see the download, installation, and configuration part of an eclipse and will see how you can configure the Hadoop while installing and configuring an eclipse."
},
{
"code": null,
"e": 592,
"s": 551,
"text": "Step 1: Download and Install Eclipse IDE"
},
{
"code": null,
"e": 831,
"s": 592,
"text": "It is the most popular IDE for developing java applications. It is easy to use and powerful IDE that is the reason behind the trust of many programmers. It can be downloaded from the given link below as follows. "
},
{
"code": null,
"e": 881,
"s": 831,
"text": "http://www.eclipse.org/downloads/eclipse-packages"
},
{
"code": null,
"e": 953,
"s": 881,
"text": "You will get a file named eclipse-committers-photon-R-linux-gtk.tar.gz."
},
{
"code": null,
"e": 1048,
"s": 953,
"text": "We need to extract it using the command tar βzxvf eclipse-committers-photon-R-linux-gtk.tar.gz"
},
{
"code": null,
"e": 1102,
"s": 1048,
"text": "Step 2: Move the eclipse folder to the home directory"
},
{
"code": null,
"e": 1231,
"s": 1102,
"text": "In this step, you can see how to move the eclipse folder to the home directory. You can check the screenshot for your reference."
},
{
"code": null,
"e": 1252,
"s": 1231,
"text": "Step 3: Open Eclipse"
},
{
"code": null,
"e": 1448,
"s": 1252,
"text": "Now, in this step, you can see the eclipse icon once you will successfully download and extract it to the required folder. And double click to open. You can see the screenshot for your reference."
},
{
"code": null,
"e": 1472,
"s": 1448,
"text": "Step 4: Execute Eclipse"
},
{
"code": null,
"e": 1528,
"s": 1472,
"text": "Now choose a workspace directory and then click LAUNCH."
},
{
"code": null,
"e": 1561,
"s": 1528,
"text": "Step 5: Download required files "
},
{
"code": null,
"e": 1583,
"s": 1561,
"text": "Hadoop-core-1.2.1.jar"
},
{
"code": null,
"e": 1603,
"s": 1583,
"text": "commons-cli-1.2.jar"
},
{
"code": null,
"e": 1633,
"s": 1603,
"text": "Step 6: Creating Java Project"
},
{
"code": null,
"e": 1682,
"s": 1633,
"text": "Create a java project in the package explorer. "
},
{
"code": null,
"e": 1790,
"s": 1682,
"text": "fileβ>newβ>java projectβ>finish \nright clickβ>newβ>packageβ>finish \nright click on packageβ>newβ>class_name"
},
{
"code": null,
"e": 1825,
"s": 1790,
"text": "Step 7: Adding Reference libraries"
},
{
"code": null,
"e": 1962,
"s": 1825,
"text": " Now add the following reference libraries as follows. First, we need to go to build path β>configure build path β> configure build path"
},
{
"code": null,
"e": 1988,
"s": 1962,
"text": "Step 8: Adding .jar Files"
},
{
"code": null,
"e": 2163,
"s": 1988,
"text": "Click on add external jars and browse to the folder where the files are downloaded and click open and select these two files i.e. hadoop-core-1.2.1.jar , commons-cli-1.2.jar."
},
{
"code": null,
"e": 2170,
"s": 2163,
"text": "Hadoop"
},
{
"code": null,
"e": 2180,
"s": 2170,
"text": "MapReduce"
},
{
"code": null,
"e": 2187,
"s": 2180,
"text": "Hadoop"
},
{
"code": null,
"e": 2194,
"s": 2187,
"text": "How To"
},
{
"code": null,
"e": 2201,
"s": 2194,
"text": "Hadoop"
},
{
"code": null,
"e": 2299,
"s": 2201,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2328,
"s": 2299,
"text": "How to Create Table in Hive?"
},
{
"code": null,
"e": 2340,
"s": 2328,
"text": "Apache Hive"
},
{
"code": null,
"e": 2366,
"s": 2340,
"text": "What is Hadoop Streaming?"
},
{
"code": null,
"e": 2420,
"s": 2366,
"text": "What is Schema On Read and Schema On Write in Hadoop?"
},
{
"code": null,
"e": 2469,
"s": 2420,
"text": "MapReduce - Understanding With Real-Life Example"
},
{
"code": null,
"e": 2501,
"s": 2469,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2545,
"s": 2501,
"text": "How to install Jupyter Notebook on Windows?"
},
{
"code": null,
"e": 2579,
"s": 2545,
"text": "How to Install FFmpeg on Windows?"
}
] |
How to store words in an array in C?
|
18 Oct, 2019
We all know how to store a word or String, how to store characters in an array, etc. This article will help you understand how to store words in an array in C.
To store the words, a 2-D char array is required. In this 2-D array, each row will contain a word each. Hence the rows will denote the index number of the words and the column number will denote the particular character in that word.
Direct initialization: In this method, the words are already known and the 2-D char array is created with these words directly.Syntax for Direct initialization:char array[][20] = {"Geek1", "Geek2", "Geek3", ..."};Syntax for accessing a word:Lets say we need to fetch the ith word:
array[i]
Below is the implementation of the above approach:// C program to store words in an array #include <stdio.h> int main(){ int i; // Direct initialization of 2-D char array char array[][20] = { "Geek1", "Geek2", "Geek3" }; // print the words for (i = 0; i < 3; i++) printf("%s\n", array[i]); return 0;}Output:Geek1
Geek2
Geek3
By taking input from user: In this method, the number of words and words are given by the user and we have to create and map the 2-D char array for each word.Syntax:// Declaration of 2-D char array
// where n is the number of words
char array[n][20];
// Initialization of 2-D char array
for (i = 0; i < n; i++)
scanf("%s", array[i]);
Syntax for accessing a word:Lets say we need to fetch the ith word:
array[i]
Below is the implementation of the above approach:// C program to store words in an array #include <stdio.h> int main(){ int i; // Lets say we have 3 words int n = 3; // Declaration of 2-D char array char array[n][20]; // Initialization of 2-D char array for (i = 0; i < 3; i++) scanf("%s", array[i]); // print the words for (i = 0; i < 3; i++) printf("%s\n", array[i]); return 0;}Input:Geek1
Geek2
Geek3
Output:Geek1
Geek2
Geek3
Direct initialization: In this method, the words are already known and the 2-D char array is created with these words directly.Syntax for Direct initialization:char array[][20] = {"Geek1", "Geek2", "Geek3", ..."};Syntax for accessing a word:Lets say we need to fetch the ith word:
array[i]
Below is the implementation of the above approach:// C program to store words in an array #include <stdio.h> int main(){ int i; // Direct initialization of 2-D char array char array[][20] = { "Geek1", "Geek2", "Geek3" }; // print the words for (i = 0; i < 3; i++) printf("%s\n", array[i]); return 0;}Output:Geek1
Geek2
Geek3
Syntax for Direct initialization:
char array[][20] = {"Geek1", "Geek2", "Geek3", ..."};
Syntax for accessing a word:
Lets say we need to fetch the ith word:
array[i]
Below is the implementation of the above approach:
// C program to store words in an array #include <stdio.h> int main(){ int i; // Direct initialization of 2-D char array char array[][20] = { "Geek1", "Geek2", "Geek3" }; // print the words for (i = 0; i < 3; i++) printf("%s\n", array[i]); return 0;}
Geek1
Geek2
Geek3
By taking input from user: In this method, the number of words and words are given by the user and we have to create and map the 2-D char array for each word.Syntax:// Declaration of 2-D char array
// where n is the number of words
char array[n][20];
// Initialization of 2-D char array
for (i = 0; i < n; i++)
scanf("%s", array[i]);
Syntax for accessing a word:Lets say we need to fetch the ith word:
array[i]
Below is the implementation of the above approach:// C program to store words in an array #include <stdio.h> int main(){ int i; // Lets say we have 3 words int n = 3; // Declaration of 2-D char array char array[n][20]; // Initialization of 2-D char array for (i = 0; i < 3; i++) scanf("%s", array[i]); // print the words for (i = 0; i < 3; i++) printf("%s\n", array[i]); return 0;}Input:Geek1
Geek2
Geek3
Output:Geek1
Geek2
Geek3
Syntax:
// Declaration of 2-D char array
// where n is the number of words
char array[n][20];
// Initialization of 2-D char array
for (i = 0; i < n; i++)
scanf("%s", array[i]);
Syntax for accessing a word:
Lets say we need to fetch the ith word:
array[i]
Below is the implementation of the above approach:
// C program to store words in an array #include <stdio.h> int main(){ int i; // Lets say we have 3 words int n = 3; // Declaration of 2-D char array char array[n][20]; // Initialization of 2-D char array for (i = 0; i < 3; i++) scanf("%s", array[i]); // print the words for (i = 0; i < 3; i++) printf("%s\n", array[i]); return 0;}
Geek1
Geek2
Geek3
Output:
Geek1
Geek2
Geek3
C-String
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
Difference between break and continue statement in C
Exit codes in C/C++ with Examples
C Hello World Program
Handling multiple clients on server with multithreading using Socket Programming in C/C++
C program to find the length of a string
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
C Program for Tower of Hanoi
Conditional wait and signal in multi-threading
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Oct, 2019"
},
{
"code": null,
"e": 212,
"s": 52,
"text": "We all know how to store a word or String, how to store characters in an array, etc. This article will help you understand how to store words in an array in C."
},
{
"code": null,
"e": 446,
"s": 212,
"text": "To store the words, a 2-D char array is required. In this 2-D array, each row will contain a word each. Hence the rows will denote the index number of the words and the column number will denote the particular character in that word."
},
{
"code": null,
"e": 1999,
"s": 446,
"text": "Direct initialization: In this method, the words are already known and the 2-D char array is created with these words directly.Syntax for Direct initialization:char array[][20] = {\"Geek1\", \"Geek2\", \"Geek3\", ...\"};Syntax for accessing a word:Lets say we need to fetch the ith word:\n\narray[i]\nBelow is the implementation of the above approach:// C program to store words in an array #include <stdio.h> int main(){ int i; // Direct initialization of 2-D char array char array[][20] = { \"Geek1\", \"Geek2\", \"Geek3\" }; // print the words for (i = 0; i < 3; i++) printf(\"%s\\n\", array[i]); return 0;}Output:Geek1\nGeek2\nGeek3\nBy taking input from user: In this method, the number of words and words are given by the user and we have to create and map the 2-D char array for each word.Syntax:// Declaration of 2-D char array\n// where n is the number of words\nchar array[n][20];\n\n// Initialization of 2-D char array\nfor (i = 0; i < n; i++)\n scanf(\"%s\", array[i]);\nSyntax for accessing a word:Lets say we need to fetch the ith word:\n\narray[i]\nBelow is the implementation of the above approach:// C program to store words in an array #include <stdio.h> int main(){ int i; // Lets say we have 3 words int n = 3; // Declaration of 2-D char array char array[n][20]; // Initialization of 2-D char array for (i = 0; i < 3; i++) scanf(\"%s\", array[i]); // print the words for (i = 0; i < 3; i++) printf(\"%s\\n\", array[i]); return 0;}Input:Geek1\nGeek2\nGeek3\nOutput:Geek1\nGeek2\nGeek3\n"
},
{
"code": null,
"e": 2649,
"s": 1999,
"text": "Direct initialization: In this method, the words are already known and the 2-D char array is created with these words directly.Syntax for Direct initialization:char array[][20] = {\"Geek1\", \"Geek2\", \"Geek3\", ...\"};Syntax for accessing a word:Lets say we need to fetch the ith word:\n\narray[i]\nBelow is the implementation of the above approach:// C program to store words in an array #include <stdio.h> int main(){ int i; // Direct initialization of 2-D char array char array[][20] = { \"Geek1\", \"Geek2\", \"Geek3\" }; // print the words for (i = 0; i < 3; i++) printf(\"%s\\n\", array[i]); return 0;}Output:Geek1\nGeek2\nGeek3\n"
},
{
"code": null,
"e": 2683,
"s": 2649,
"text": "Syntax for Direct initialization:"
},
{
"code": null,
"e": 2737,
"s": 2683,
"text": "char array[][20] = {\"Geek1\", \"Geek2\", \"Geek3\", ...\"};"
},
{
"code": null,
"e": 2766,
"s": 2737,
"text": "Syntax for accessing a word:"
},
{
"code": null,
"e": 2817,
"s": 2766,
"text": "Lets say we need to fetch the ith word:\n\narray[i]\n"
},
{
"code": null,
"e": 2868,
"s": 2817,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// C program to store words in an array #include <stdio.h> int main(){ int i; // Direct initialization of 2-D char array char array[][20] = { \"Geek1\", \"Geek2\", \"Geek3\" }; // print the words for (i = 0; i < 3; i++) printf(\"%s\\n\", array[i]); return 0;}",
"e": 3152,
"s": 2868,
"text": null
},
{
"code": null,
"e": 3171,
"s": 3152,
"text": "Geek1\nGeek2\nGeek3\n"
},
{
"code": null,
"e": 4075,
"s": 3171,
"text": "By taking input from user: In this method, the number of words and words are given by the user and we have to create and map the 2-D char array for each word.Syntax:// Declaration of 2-D char array\n// where n is the number of words\nchar array[n][20];\n\n// Initialization of 2-D char array\nfor (i = 0; i < n; i++)\n scanf(\"%s\", array[i]);\nSyntax for accessing a word:Lets say we need to fetch the ith word:\n\narray[i]\nBelow is the implementation of the above approach:// C program to store words in an array #include <stdio.h> int main(){ int i; // Lets say we have 3 words int n = 3; // Declaration of 2-D char array char array[n][20]; // Initialization of 2-D char array for (i = 0; i < 3; i++) scanf(\"%s\", array[i]); // print the words for (i = 0; i < 3; i++) printf(\"%s\\n\", array[i]); return 0;}Input:Geek1\nGeek2\nGeek3\nOutput:Geek1\nGeek2\nGeek3\n"
},
{
"code": null,
"e": 4083,
"s": 4075,
"text": "Syntax:"
},
{
"code": null,
"e": 4258,
"s": 4083,
"text": "// Declaration of 2-D char array\n// where n is the number of words\nchar array[n][20];\n\n// Initialization of 2-D char array\nfor (i = 0; i < n; i++)\n scanf(\"%s\", array[i]);\n"
},
{
"code": null,
"e": 4287,
"s": 4258,
"text": "Syntax for accessing a word:"
},
{
"code": null,
"e": 4338,
"s": 4287,
"text": "Lets say we need to fetch the ith word:\n\narray[i]\n"
},
{
"code": null,
"e": 4389,
"s": 4338,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// C program to store words in an array #include <stdio.h> int main(){ int i; // Lets say we have 3 words int n = 3; // Declaration of 2-D char array char array[n][20]; // Initialization of 2-D char array for (i = 0; i < 3; i++) scanf(\"%s\", array[i]); // print the words for (i = 0; i < 3; i++) printf(\"%s\\n\", array[i]); return 0;}",
"e": 4777,
"s": 4389,
"text": null
},
{
"code": null,
"e": 4796,
"s": 4777,
"text": "Geek1\nGeek2\nGeek3\n"
},
{
"code": null,
"e": 4804,
"s": 4796,
"text": "Output:"
},
{
"code": null,
"e": 4823,
"s": 4804,
"text": "Geek1\nGeek2\nGeek3\n"
},
{
"code": null,
"e": 4832,
"s": 4823,
"text": "C-String"
},
{
"code": null,
"e": 4843,
"s": 4832,
"text": "C Programs"
},
{
"code": null,
"e": 4941,
"s": 4843,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4982,
"s": 4941,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 5013,
"s": 4982,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 5066,
"s": 5013,
"text": "Difference between break and continue statement in C"
},
{
"code": null,
"e": 5100,
"s": 5066,
"text": "Exit codes in C/C++ with Examples"
},
{
"code": null,
"e": 5122,
"s": 5100,
"text": "C Hello World Program"
},
{
"code": null,
"e": 5212,
"s": 5122,
"text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++"
},
{
"code": null,
"e": 5253,
"s": 5212,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 5324,
"s": 5253,
"text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 5353,
"s": 5324,
"text": "C Program for Tower of Hanoi"
}
] |
ReactJS | State vs props
|
30 Jul, 2020
We know that in react components are the building blocks which can be reused again and again in building the UI. Before jumping into the main difference between the state and props, letβs see how a component in react is related to a normal function in javascript Example:
javascript
// simple componentclass FakeComponent extends React.component{ render(){ return <div>Hello World!</div> }}// simple javascript functionconst FakeFunction = () => console.log('Hello World!');
In the above code we declared a simple react component by extending the React.component native method and then we simply render a div which contains βHello Worldβ inside it as text. After the function we have a simple javascript function inside it which contains a simple console.log which does the same thing inside it, printing βHello World!β. So now we know that a React component works similar to a normal javascript function. Letβs take a look at state
A state is a variable which exists inside a component, that cannot be accessed and modified outside the component and can only be used inside the component. Works very similarly to a variable that is declared inside a function that cannot be accessed outside the scope of the function in normal javascript.State Can be modified using this.setState. State can be asynchronous.Whenever this.setState is used to change the state class is rerender itself.Letβs see with the help an example: Example:
javascript
// componentclass FakeComponent extends React.component{ state = { name : 'Mukul'; } render(){ return <div>Hello {this.state.name}</div> }}// simple js functionconst FakeFunction = () => { let name = 'Mukul'; console.log(`Hey ${name}`);}
In the above code we simply declare a name property inside a component and used it while rendering, similar is the case with a normal function in javascript. It should also be noted that the state is mutable in nature, and should not be accessed from child components.
We know that components in React are used again and again in the UI, but we donβt normally render the same component with the same data. Sometimes we need to change the content inside a component. Props come to play in these cases, as they are passed into the component and the user. Letβs see how they work: Example:
javascript
// componentclass FakeComponent extends React.component{ render(){ return <div>Hello {this.props.name}</div> }}// passing the props<FakeComponent name='Mukul' /><FakeComponent name='Mayank' />
A simple component and then we passes the props as attributes and then access them inside our component using this.props. So props makes components reusable by giving components the ability to receive data from the parent component in the form of props. They are immutable.
zack_aayush
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Jul, 2020"
},
{
"code": null,
"e": 328,
"s": 54,
"text": "We know that in react components are the building blocks which can be reused again and again in building the UI. Before jumping into the main difference between the state and props, letβs see how a component in react is related to a normal function in javascript Example: "
},
{
"code": null,
"e": 339,
"s": 328,
"text": "javascript"
},
{
"code": "// simple componentclass FakeComponent extends React.component{ render(){ return <div>Hello World!</div> }}// simple javascript functionconst FakeFunction = () => console.log('Hello World!');",
"e": 537,
"s": 339,
"text": null
},
{
"code": null,
"e": 997,
"s": 537,
"text": "In the above code we declared a simple react component by extending the React.component native method and then we simply render a div which contains βHello Worldβ inside it as text. After the function we have a simple javascript function inside it which contains a simple console.log which does the same thing inside it, printing βHello World!β. So now we know that a React component works similar to a normal javascript function. Letβs take a look at state "
},
{
"code": null,
"e": 1495,
"s": 997,
"text": "A state is a variable which exists inside a component, that cannot be accessed and modified outside the component and can only be used inside the component. Works very similarly to a variable that is declared inside a function that cannot be accessed outside the scope of the function in normal javascript.State Can be modified using this.setState. State can be asynchronous.Whenever this.setState is used to change the state class is rerender itself.Letβs see with the help an example: Example: "
},
{
"code": null,
"e": 1506,
"s": 1495,
"text": "javascript"
},
{
"code": "// componentclass FakeComponent extends React.component{ state = { name : 'Mukul'; } render(){ return <div>Hello {this.state.name}</div> }}// simple js functionconst FakeFunction = () => { let name = 'Mukul'; console.log(`Hey ${name}`);}",
"e": 1762,
"s": 1506,
"text": null
},
{
"code": null,
"e": 2033,
"s": 1762,
"text": "In the above code we simply declare a name property inside a component and used it while rendering, similar is the case with a normal function in javascript. It should also be noted that the state is mutable in nature, and should not be accessed from child components. "
},
{
"code": null,
"e": 2353,
"s": 2033,
"text": "We know that components in React are used again and again in the UI, but we donβt normally render the same component with the same data. Sometimes we need to change the content inside a component. Props come to play in these cases, as they are passed into the component and the user. Letβs see how they work: Example: "
},
{
"code": null,
"e": 2364,
"s": 2353,
"text": "javascript"
},
{
"code": "// componentclass FakeComponent extends React.component{ render(){ return <div>Hello {this.props.name}</div> }}// passing the props<FakeComponent name='Mukul' /><FakeComponent name='Mayank' />",
"e": 2563,
"s": 2364,
"text": null
},
{
"code": null,
"e": 2838,
"s": 2563,
"text": "A simple component and then we passes the props as attributes and then access them inside our component using this.props. So props makes components reusable by giving components the ability to receive data from the parent component in the form of props. They are immutable. "
},
{
"code": null,
"e": 2850,
"s": 2838,
"text": "zack_aayush"
},
{
"code": null,
"e": 2859,
"s": 2850,
"text": "react-js"
},
{
"code": null,
"e": 2876,
"s": 2859,
"text": "Web Technologies"
}
] |
Evaluate the Value of an Arithmetic Expression in Reverse Polish Notation in Java
|
11 Jun, 2022
Reverse Polish βNotation is postfix notation which in terms of mathematical notion signifies operators following operands. Letβs take a problem statement to implement RPN
Problem Statement: The task is to find the value of the arithmetic expression present in the array using valid operators like +, -, *, /. Each operand may be an integer or another expression.
Note:
The division between two integers should truncate toward zero.The given RPN expression is always valid. That means the expression would always evaluate to a result and there wonβt be any divide by zero operation.
The division between two integers should truncate toward zero.
The given RPN expression is always valid. That means the expression would always evaluate to a result and there wonβt be any divide by zero operation.
Layman Working of RPN as shown
Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Explanation:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
Approach:
The basic approach for the problem is using the stack.
Accessing all elements in the array, if the element is not matching with the special character (β+β, β-β,β*β, β/β) then push the element to the stack.
Then whenever the special character is found then pop the first two-element from the stack and perform the action and then push the element to stack again.
Repeat the above two process to all elements in the array
At last pop the element from the stack and print the Result
Implementation:
Python3
C++
Java
# Python 3 code to evaluate reverse polish notation """This code is contributed by Harshal Gupta""" # function to evaluate reverse polish notationdef evaluate(expression): # splitting expression at whitespaces expression = expression.split() # stack stack = [] # iterating expression for ele in expression: # ele is a number if ele not in '/*+-': stack.append(int(ele)) # ele is an operator else: # getting operands right = stack.pop() left = stack.pop() # performing operation according to operator if ele == '+': stack.append(left + right) elif ele == '-': stack.append(left - right) elif ele == '*': stack.append(left * right) elif ele == '/': stack.append(int(left / right)) # return final answer. return stack.pop() # input expressionarr = "10 6 9 3 + -11 * / * 17 + 5 +" # calling evaluate()answer = evaluate(arr)# printing final value of the expressionprint(f"Value of given expression'{arr}' = {answer}")
#include <bits/stdc++.h>using namespace std;int eval(vector<string>& A){ stack<int> st; for (int i = 0; i < A.size(); i++) { if (A[i] != "+" && A[i] != "-" && A[i] != "/" && A[i] != "*") { st.push(stoi(A[i])); continue; } else { int b = st.top(); st.pop(); int a = st.top(); st.pop(); if (A[i] == "+") st.push(a + b); else if (A[i] == "-") st.push(a - b); else if (A[i] == "*") st.push(a * b); else st.push(a / b); } } return st.top();} int main(){ vector<string> A = { "10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+" }; int res = eval(A); cout << res << endl;}
// Java Program to find the// solution of the arithmetic// using the stackimport java.io.*;import java.util.*; class solution { public int stacky(String[] tokens) { // Initialize the stack and the variable Stack<String> stack = new Stack<String>(); int x, y; String result = ""; int get = 0; String choice; int value = 0; String p = ""; // Iterating to the each character // in the array of the string for (int i = 0; i < tokens.length; i++) { // If the character is not the special character // ('+', '-' ,'*' , '/') // then push the character to the stack if (tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/") { stack.push(tokens[i]); continue; } else { // else if the character is the special // character then use the switch method to // perform the action choice = tokens[i]; } // Switch-Case switch (choice) { case "+": // Performing the "+" operation by poping // put the first two character // and then again store back to the stack x = Integer.parseInt(stack.pop()); y = Integer.parseInt(stack.pop()); value = x + y; result = p + value; stack.push(result); break; case "-": // Performing the "-" operation by poping // put the first two character // and then again store back to the stack x = Integer.parseInt(stack.pop()); y = Integer.parseInt(stack.pop()); value = y - x; result = p + value; stack.push(result); break; case "*": // Performing the "*" operation // by poping put the first two character // and then again store back to the stack x = Integer.parseInt(stack.pop()); y = Integer.parseInt(stack.pop()); value = x * y; result = p + value; stack.push(result); break; case "/": // Performing the "/" operation by poping // put the first two character // and then again store back to the stack x = Integer.parseInt(stack.pop()); y = Integer.parseInt(stack.pop()); value = y / x; result = p + value; stack.push(result); break; default: continue; } } // Method to convert the String to integer return Integer.parseInt(stack.pop()); }} class GFG { public static void main(String[] args) { // String Input String[] s = { "10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+" }; solution str = new solution(); int result = str.stacky(s); System.out.println(result); }}
Value of given expression'10 6 9 3 + -11 * / * 17 + 5 +' = 22
Time complexity: O(n)
Auxiliary Space: O(n)
akshaysingh98088
ashutoshsinghgeeksforgeeks
kushagra19991998
harshal1221325
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
List Interface in Java with Examples
Different ways of Reading a text file in Java
Constructors in Java
Strings in Java
HashMap containsKey() Method in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Jun, 2022"
},
{
"code": null,
"e": 223,
"s": 52,
"text": "Reverse Polish βNotation is postfix notation which in terms of mathematical notion signifies operators following operands. Letβs take a problem statement to implement RPN"
},
{
"code": null,
"e": 415,
"s": 223,
"text": "Problem Statement: The task is to find the value of the arithmetic expression present in the array using valid operators like +, -, *, /. Each operand may be an integer or another expression."
},
{
"code": null,
"e": 421,
"s": 415,
"text": "Note:"
},
{
"code": null,
"e": 634,
"s": 421,
"text": "The division between two integers should truncate toward zero.The given RPN expression is always valid. That means the expression would always evaluate to a result and there wonβt be any divide by zero operation."
},
{
"code": null,
"e": 697,
"s": 634,
"text": "The division between two integers should truncate toward zero."
},
{
"code": null,
"e": 848,
"s": 697,
"text": "The given RPN expression is always valid. That means the expression would always evaluate to a result and there wonβt be any divide by zero operation."
},
{
"code": null,
"e": 879,
"s": 848,
"text": "Layman Working of RPN as shown"
},
{
"code": null,
"e": 1294,
"s": 879,
"text": "Input: [\"2\", \"1\", \"+\", \"3\", \"*\"]\nOutput: 9\nExplanation: ((2 + 1) * 3) = 9\n\nInput: [\"4\", \"13\", \"5\", \"/\", \"+\"]\nOutput: 6\nExplanation: (4 + (13 / 5)) = 6\n\nInput: [\"10\", \"6\", \"9\", \"3\", \"+\", \"-11\", \"*\", \"/\", \"*\", \"17\", \"+\", \"5\", \"+\"]\nOutput: 22\nExplanation: \n ((10 * (6 / ((9 + 3) * -11))) + 17) + 5\n= ((10 * (6 / (12 * -11))) + 17) + 5\n= ((10 * (6 / -132)) + 17) + 5\n= ((10 * 0) + 17) + 5\n= (0 + 17) + 5\n= 17 + 5\n= 22"
},
{
"code": null,
"e": 1304,
"s": 1294,
"text": "Approach:"
},
{
"code": null,
"e": 1359,
"s": 1304,
"text": "The basic approach for the problem is using the stack."
},
{
"code": null,
"e": 1510,
"s": 1359,
"text": "Accessing all elements in the array, if the element is not matching with the special character (β+β, β-β,β*β, β/β) then push the element to the stack."
},
{
"code": null,
"e": 1666,
"s": 1510,
"text": "Then whenever the special character is found then pop the first two-element from the stack and perform the action and then push the element to stack again."
},
{
"code": null,
"e": 1724,
"s": 1666,
"text": "Repeat the above two process to all elements in the array"
},
{
"code": null,
"e": 1784,
"s": 1724,
"text": "At last pop the element from the stack and print the Result"
},
{
"code": null,
"e": 1800,
"s": 1784,
"text": "Implementation:"
},
{
"code": null,
"e": 1808,
"s": 1800,
"text": "Python3"
},
{
"code": null,
"e": 1812,
"s": 1808,
"text": "C++"
},
{
"code": null,
"e": 1817,
"s": 1812,
"text": "Java"
},
{
"code": "# Python 3 code to evaluate reverse polish notation \"\"\"This code is contributed by Harshal Gupta\"\"\" # function to evaluate reverse polish notationdef evaluate(expression): # splitting expression at whitespaces expression = expression.split() # stack stack = [] # iterating expression for ele in expression: # ele is a number if ele not in '/*+-': stack.append(int(ele)) # ele is an operator else: # getting operands right = stack.pop() left = stack.pop() # performing operation according to operator if ele == '+': stack.append(left + right) elif ele == '-': stack.append(left - right) elif ele == '*': stack.append(left * right) elif ele == '/': stack.append(int(left / right)) # return final answer. return stack.pop() # input expressionarr = \"10 6 9 3 + -11 * / * 17 + 5 +\" # calling evaluate()answer = evaluate(arr)# printing final value of the expressionprint(f\"Value of given expression'{arr}' = {answer}\") ",
"e": 2929,
"s": 1817,
"text": null
},
{
"code": "#include <bits/stdc++.h>using namespace std;int eval(vector<string>& A){ stack<int> st; for (int i = 0; i < A.size(); i++) { if (A[i] != \"+\" && A[i] != \"-\" && A[i] != \"/\" && A[i] != \"*\") { st.push(stoi(A[i])); continue; } else { int b = st.top(); st.pop(); int a = st.top(); st.pop(); if (A[i] == \"+\") st.push(a + b); else if (A[i] == \"-\") st.push(a - b); else if (A[i] == \"*\") st.push(a * b); else st.push(a / b); } } return st.top();} int main(){ vector<string> A = { \"10\", \"6\", \"9\", \"3\", \"+\", \"-11\", \"*\", \"/\", \"*\", \"17\", \"+\", \"5\", \"+\" }; int res = eval(A); cout << res << endl;}",
"e": 3762,
"s": 2929,
"text": null
},
{
"code": "// Java Program to find the// solution of the arithmetic// using the stackimport java.io.*;import java.util.*; class solution { public int stacky(String[] tokens) { // Initialize the stack and the variable Stack<String> stack = new Stack<String>(); int x, y; String result = \"\"; int get = 0; String choice; int value = 0; String p = \"\"; // Iterating to the each character // in the array of the string for (int i = 0; i < tokens.length; i++) { // If the character is not the special character // ('+', '-' ,'*' , '/') // then push the character to the stack if (tokens[i] != \"+\" && tokens[i] != \"-\" && tokens[i] != \"*\" && tokens[i] != \"/\") { stack.push(tokens[i]); continue; } else { // else if the character is the special // character then use the switch method to // perform the action choice = tokens[i]; } // Switch-Case switch (choice) { case \"+\": // Performing the \"+\" operation by poping // put the first two character // and then again store back to the stack x = Integer.parseInt(stack.pop()); y = Integer.parseInt(stack.pop()); value = x + y; result = p + value; stack.push(result); break; case \"-\": // Performing the \"-\" operation by poping // put the first two character // and then again store back to the stack x = Integer.parseInt(stack.pop()); y = Integer.parseInt(stack.pop()); value = y - x; result = p + value; stack.push(result); break; case \"*\": // Performing the \"*\" operation // by poping put the first two character // and then again store back to the stack x = Integer.parseInt(stack.pop()); y = Integer.parseInt(stack.pop()); value = x * y; result = p + value; stack.push(result); break; case \"/\": // Performing the \"/\" operation by poping // put the first two character // and then again store back to the stack x = Integer.parseInt(stack.pop()); y = Integer.parseInt(stack.pop()); value = y / x; result = p + value; stack.push(result); break; default: continue; } } // Method to convert the String to integer return Integer.parseInt(stack.pop()); }} class GFG { public static void main(String[] args) { // String Input String[] s = { \"10\", \"6\", \"9\", \"3\", \"+\", \"-11\", \"*\", \"/\", \"*\", \"17\", \"+\", \"5\", \"+\" }; solution str = new solution(); int result = str.stacky(s); System.out.println(result); }}",
"e": 7008,
"s": 3762,
"text": null
},
{
"code": null,
"e": 7070,
"s": 7008,
"text": "Value of given expression'10 6 9 3 + -11 * / * 17 + 5 +' = 22"
},
{
"code": null,
"e": 7092,
"s": 7070,
"text": "Time complexity: O(n)"
},
{
"code": null,
"e": 7114,
"s": 7092,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 7131,
"s": 7114,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 7158,
"s": 7131,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 7175,
"s": 7158,
"text": "kushagra19991998"
},
{
"code": null,
"e": 7190,
"s": 7175,
"text": "harshal1221325"
},
{
"code": null,
"e": 7195,
"s": 7190,
"text": "Java"
},
{
"code": null,
"e": 7209,
"s": 7195,
"text": "Java Programs"
},
{
"code": null,
"e": 7214,
"s": 7209,
"text": "Java"
},
{
"code": null,
"e": 7312,
"s": 7214,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7349,
"s": 7312,
"text": "List Interface in Java with Examples"
},
{
"code": null,
"e": 7395,
"s": 7349,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 7416,
"s": 7395,
"text": "Constructors in Java"
},
{
"code": null,
"e": 7432,
"s": 7416,
"text": "Strings in Java"
},
{
"code": null,
"e": 7469,
"s": 7432,
"text": "HashMap containsKey() Method in Java"
},
{
"code": null,
"e": 7495,
"s": 7469,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 7529,
"s": 7495,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 7576,
"s": 7529,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 7614,
"s": 7576,
"text": "Factory method design pattern in Java"
}
] |
Dart β Finding Minimum and Maximum Value in a List
|
20 Jul, 2020
In Dart we can find the minimum and maximum valued element present in the given list in seven ways:
Using for loop to find the largest and smallest element.Using sort function to find the largest and smallest element.Using forEach loop to find the largest and smallest element.Using only reduce method in dart to find the largest and smallest element.Using reduce method with dart:math library.Using fold method with dart to find the largest and smallest element.Using fold method with dart:math library.
Using for loop to find the largest and smallest element.
Using sort function to find the largest and smallest element.
Using forEach loop to find the largest and smallest element.
Using only reduce method in dart to find the largest and smallest element.
Using reduce method with dart:math library.
Using fold method with dart to find the largest and smallest element.
Using fold method with dart:math library.
It is the most basic way to find the largest and smallest element present in the list by simply going through all the elements comparing them and giving the answer.
Example:
Dart
// Main functionvoid main() { // Creating a geek list var geekList = [121, 12, 33, 14, 3]; // Declaring and assigning the // largestGeekValue and smallestGeekValue var largestGeekValue = geekList[0]; var smallestGeekValue = geekList[0]; for (var i = 0; i < geekList.length; i++) { // Checking for largest value in the list if (geekList[i] > largestGeekValue) { largestGeekValue = geekList[i]; } // Checking for smallest value in the list if (geekList[i] < smallestGeekValue) { smallestGeekValue = geekList[i]; } } // Printing the values print("Smallest value in the list : $smallestGeekValue"); print("Largest value in the list : $largestGeekValue");}
Output:
Smallest value in the list : 3
Largest value in the list : 121
Dart also provides the user to sort the list in the ascending order i.e. first one is the smallest and last one is largest.
Example:
Dart
// Main functionvoid main() { // Creating a geek list var geekList = [121, 12, 33, 14, 3]; // Sorting the list geekList.sort(); // Printing the values print("Smallest value in the list : ${geekList.first}"); print("Largest value in the list : ${geekList.last}");}
Output:
Smallest value in the list : 3
Largest value in the list : 121
Unlike for loop, one can also use forEach loop to get the elements of the list and then check for the conditions in the elements of the list.
Example:
Dart
// Main functionvoid main() { // Creating a geek list var geekList = [121, 12, 33, 14, 3]; // Declaring and assigning the // largestGeekValue and smallestGeekValue var largestGeekValue = geekList[0]; var smallestGeekValue = geekList[0]; // Using forEach loop to find // the largest and smallest // numbers in the list geekList.forEach((gfg) => { if (gfg > largestGeekValue) {largestGeekValue = gfg}, if (gfg < smallestGeekValue) {smallestGeekValue = gfg}, }); // Printing the values print("Smallest value in the list : $smallestGeekValue"); print("Largest value in the list : $largestGeekValue");}
Output:
Smallest value in the list : 3
Largest value in the list : 121
One can use Dart reduce function to reduce the list to a particular value and save it.
Example:
Dart
// Main functionvoid main() { // Creating a geek list var geekList = [121, 12, 33, 14, 3]; // Declaring and assigning the // largestGeekValue and smallestGeekValue // Finding the smallest and largest // value in the list var smallestGeekValue = geekList.reduce( (current, next) => current < next ? current : next); var largestGeekValue = geekList.reduce( (current, next) => current > next ? current : next); // Printing the values print("Smallest value in the list : $smallestGeekValue"); print("Largest value in the list : $largestGeekValue");}
Output:
Smallest value in the list : 3
Largest value in the list : 121
The above code can be minimized by importing the math libraries.
Example:
Dart
import "dart:math"; // Main functionvoid main() { // Creating a geek list var geekList = [121, 12, 33, 14, 3]; // Declaring and assigning the // largestGeekValue and smallestGeekValue // Finding the smallest and largest value in the list var smallestGeekValue = geekList.reduce(min); var largestGeekValue = geekList.reduce(max); // Printing the values print("Smallest value in the list : $smallestGeekValue"); print("Largest value in the list : $largestGeekValue");}
Output:
Smallest value in the list : 3
Largest value in the list : 121
Apart from reducing dart also has fold method which is quite similar to reduce apart from the fact that it starts with an initial value and then changes it during the process.
Example:
Dart
// Main functionvoid main() { // Creating a geek list var geekList = [121, 12, 33, 14, 3]; // Declaring and assigning the // largestGeekValue and smallestGeekValue // Finding the smallest and // largest value in the list var smallestGeekValue = geekList.fold(geekList[0], (previous, current) => previous < current ? previous : current); var largestGeekValue = geekList.fold(geekList[0], (previous, current) => previous > current ? previous : current); // Printing the values print("Smallest value in the list : $smallestGeekValue"); print("Largest value in the list : $largestGeekValue");}
Output:
Smallest value in the list : 3
Largest value in the list : 121
The above code can be minimized importing the math libraries.
Example:
Dart
import "dart:math"; // Main functionvoid main() { // Creating a geek list var geekList = [121, 12, 33, 14, 3]; // Declaring and assigning // the largestGeekValue and smallestGeekValue // Finding the smallest and // largest value in the list var smallestGeekValue = geekList.fold(geekList[0],min); var largestGeekValue = geekList.fold(geekList[0],max); // Printing the values print("Smallest value in the list : $smallestGeekValue"); print("Largest value in the list : $largestGeekValue");}
Output:
Smallest value in the list : 3
Largest value in the list : 121
Dart-List
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
ListView Class in Flutter
Flutter - Row and Column Widgets
Dart Tutorial
Flutter - Stack Widget
Flutter - Search Bar
Container class in Flutter
Operators in Dart
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Jul, 2020"
},
{
"code": null,
"e": 128,
"s": 28,
"text": "In Dart we can find the minimum and maximum valued element present in the given list in seven ways:"
},
{
"code": null,
"e": 533,
"s": 128,
"text": "Using for loop to find the largest and smallest element.Using sort function to find the largest and smallest element.Using forEach loop to find the largest and smallest element.Using only reduce method in dart to find the largest and smallest element.Using reduce method with dart:math library.Using fold method with dart to find the largest and smallest element.Using fold method with dart:math library."
},
{
"code": null,
"e": 590,
"s": 533,
"text": "Using for loop to find the largest and smallest element."
},
{
"code": null,
"e": 652,
"s": 590,
"text": "Using sort function to find the largest and smallest element."
},
{
"code": null,
"e": 713,
"s": 652,
"text": "Using forEach loop to find the largest and smallest element."
},
{
"code": null,
"e": 788,
"s": 713,
"text": "Using only reduce method in dart to find the largest and smallest element."
},
{
"code": null,
"e": 832,
"s": 788,
"text": "Using reduce method with dart:math library."
},
{
"code": null,
"e": 902,
"s": 832,
"text": "Using fold method with dart to find the largest and smallest element."
},
{
"code": null,
"e": 944,
"s": 902,
"text": "Using fold method with dart:math library."
},
{
"code": null,
"e": 1109,
"s": 944,
"text": "It is the most basic way to find the largest and smallest element present in the list by simply going through all the elements comparing them and giving the answer."
},
{
"code": null,
"e": 1118,
"s": 1109,
"text": "Example:"
},
{
"code": null,
"e": 1123,
"s": 1118,
"text": "Dart"
},
{
"code": "// Main functionvoid main() { // Creating a geek list var geekList = [121, 12, 33, 14, 3]; // Declaring and assigning the // largestGeekValue and smallestGeekValue var largestGeekValue = geekList[0]; var smallestGeekValue = geekList[0]; for (var i = 0; i < geekList.length; i++) { // Checking for largest value in the list if (geekList[i] > largestGeekValue) { largestGeekValue = geekList[i]; } // Checking for smallest value in the list if (geekList[i] < smallestGeekValue) { smallestGeekValue = geekList[i]; } } // Printing the values print(\"Smallest value in the list : $smallestGeekValue\"); print(\"Largest value in the list : $largestGeekValue\");}",
"e": 1838,
"s": 1123,
"text": null
},
{
"code": null,
"e": 1848,
"s": 1840,
"text": "Output:"
},
{
"code": null,
"e": 1912,
"s": 1848,
"text": "Smallest value in the list : 3\nLargest value in the list : 121\n"
},
{
"code": null,
"e": 2036,
"s": 1912,
"text": "Dart also provides the user to sort the list in the ascending order i.e. first one is the smallest and last one is largest."
},
{
"code": null,
"e": 2045,
"s": 2036,
"text": "Example:"
},
{
"code": null,
"e": 2050,
"s": 2045,
"text": "Dart"
},
{
"code": "// Main functionvoid main() { // Creating a geek list var geekList = [121, 12, 33, 14, 3]; // Sorting the list geekList.sort(); // Printing the values print(\"Smallest value in the list : ${geekList.first}\"); print(\"Largest value in the list : ${geekList.last}\");}",
"e": 2327,
"s": 2050,
"text": null
},
{
"code": null,
"e": 2337,
"s": 2329,
"text": "Output:"
},
{
"code": null,
"e": 2401,
"s": 2337,
"text": "Smallest value in the list : 3\nLargest value in the list : 121\n"
},
{
"code": null,
"e": 2543,
"s": 2401,
"text": "Unlike for loop, one can also use forEach loop to get the elements of the list and then check for the conditions in the elements of the list."
},
{
"code": null,
"e": 2552,
"s": 2543,
"text": "Example:"
},
{
"code": null,
"e": 2557,
"s": 2552,
"text": "Dart"
},
{
"code": "// Main functionvoid main() { // Creating a geek list var geekList = [121, 12, 33, 14, 3]; // Declaring and assigning the // largestGeekValue and smallestGeekValue var largestGeekValue = geekList[0]; var smallestGeekValue = geekList[0]; // Using forEach loop to find // the largest and smallest // numbers in the list geekList.forEach((gfg) => { if (gfg > largestGeekValue) {largestGeekValue = gfg}, if (gfg < smallestGeekValue) {smallestGeekValue = gfg}, }); // Printing the values print(\"Smallest value in the list : $smallestGeekValue\"); print(\"Largest value in the list : $largestGeekValue\");}",
"e": 3201,
"s": 2557,
"text": null
},
{
"code": null,
"e": 3211,
"s": 3203,
"text": "Output:"
},
{
"code": null,
"e": 3274,
"s": 3211,
"text": "Smallest value in the list : 3\nLargest value in the list : 121"
},
{
"code": null,
"e": 3361,
"s": 3274,
"text": "One can use Dart reduce function to reduce the list to a particular value and save it."
},
{
"code": null,
"e": 3370,
"s": 3361,
"text": "Example:"
},
{
"code": null,
"e": 3375,
"s": 3370,
"text": "Dart"
},
{
"code": "// Main functionvoid main() { // Creating a geek list var geekList = [121, 12, 33, 14, 3]; // Declaring and assigning the // largestGeekValue and smallestGeekValue // Finding the smallest and largest // value in the list var smallestGeekValue = geekList.reduce( (current, next) => current < next ? current : next); var largestGeekValue = geekList.reduce( (current, next) => current > next ? current : next); // Printing the values print(\"Smallest value in the list : $smallestGeekValue\"); print(\"Largest value in the list : $largestGeekValue\");}",
"e": 3945,
"s": 3375,
"text": null
},
{
"code": null,
"e": 3955,
"s": 3947,
"text": "Output:"
},
{
"code": null,
"e": 4019,
"s": 3955,
"text": "Smallest value in the list : 3\nLargest value in the list : 121\n"
},
{
"code": null,
"e": 4084,
"s": 4019,
"text": "The above code can be minimized by importing the math libraries."
},
{
"code": null,
"e": 4093,
"s": 4084,
"text": "Example:"
},
{
"code": null,
"e": 4098,
"s": 4093,
"text": "Dart"
},
{
"code": "import \"dart:math\"; // Main functionvoid main() { // Creating a geek list var geekList = [121, 12, 33, 14, 3]; // Declaring and assigning the // largestGeekValue and smallestGeekValue // Finding the smallest and largest value in the list var smallestGeekValue = geekList.reduce(min); var largestGeekValue = geekList.reduce(max); // Printing the values print(\"Smallest value in the list : $smallestGeekValue\"); print(\"Largest value in the list : $largestGeekValue\");}",
"e": 4583,
"s": 4098,
"text": null
},
{
"code": null,
"e": 4593,
"s": 4585,
"text": "Output:"
},
{
"code": null,
"e": 4657,
"s": 4593,
"text": "Smallest value in the list : 3\nLargest value in the list : 121\n"
},
{
"code": null,
"e": 4833,
"s": 4657,
"text": "Apart from reducing dart also has fold method which is quite similar to reduce apart from the fact that it starts with an initial value and then changes it during the process."
},
{
"code": null,
"e": 4842,
"s": 4833,
"text": "Example:"
},
{
"code": null,
"e": 4847,
"s": 4842,
"text": "Dart"
},
{
"code": "// Main functionvoid main() { // Creating a geek list var geekList = [121, 12, 33, 14, 3]; // Declaring and assigning the // largestGeekValue and smallestGeekValue // Finding the smallest and // largest value in the list var smallestGeekValue = geekList.fold(geekList[0], (previous, current) => previous < current ? previous : current); var largestGeekValue = geekList.fold(geekList[0], (previous, current) => previous > current ? previous : current); // Printing the values print(\"Smallest value in the list : $smallestGeekValue\"); print(\"Largest value in the list : $largestGeekValue\");}",
"e": 5460,
"s": 4847,
"text": null
},
{
"code": null,
"e": 5470,
"s": 5462,
"text": "Output:"
},
{
"code": null,
"e": 5534,
"s": 5470,
"text": "Smallest value in the list : 3\nLargest value in the list : 121\n"
},
{
"code": null,
"e": 5596,
"s": 5534,
"text": "The above code can be minimized importing the math libraries."
},
{
"code": null,
"e": 5605,
"s": 5596,
"text": "Example:"
},
{
"code": null,
"e": 5610,
"s": 5605,
"text": "Dart"
},
{
"code": "import \"dart:math\"; // Main functionvoid main() { // Creating a geek list var geekList = [121, 12, 33, 14, 3]; // Declaring and assigning // the largestGeekValue and smallestGeekValue // Finding the smallest and // largest value in the list var smallestGeekValue = geekList.fold(geekList[0],min); var largestGeekValue = geekList.fold(geekList[0],max); // Printing the values print(\"Smallest value in the list : $smallestGeekValue\"); print(\"Largest value in the list : $largestGeekValue\");}",
"e": 6118,
"s": 5610,
"text": null
},
{
"code": null,
"e": 6128,
"s": 6120,
"text": "Output:"
},
{
"code": null,
"e": 6192,
"s": 6128,
"text": "Smallest value in the list : 3\nLargest value in the list : 121\n"
},
{
"code": null,
"e": 6202,
"s": 6192,
"text": "Dart-List"
},
{
"code": null,
"e": 6207,
"s": 6202,
"text": "Dart"
},
{
"code": null,
"e": 6305,
"s": 6207,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6337,
"s": 6305,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 6376,
"s": 6337,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 6402,
"s": 6376,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 6428,
"s": 6402,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 6461,
"s": 6428,
"text": "Flutter - Row and Column Widgets"
},
{
"code": null,
"e": 6475,
"s": 6461,
"text": "Dart Tutorial"
},
{
"code": null,
"e": 6498,
"s": 6475,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 6519,
"s": 6498,
"text": "Flutter - Search Bar"
},
{
"code": null,
"e": 6546,
"s": 6519,
"text": "Container class in Flutter"
}
] |
How ReactJS ES6 syntax is different compared to ES5 ?
|
11 May, 2022
In this article, we will learn whatβs the exact difference between ES6 and ES5 syntaxes in ReactJs. Both ES6 and ES5 are Javascript scripting languages in the development industry. ECMA Script or ES is a trademarked scripting language made by ECMA International. The European Computer Manufacture Association or ECMA is used for client-side scripting for the worldwide web. ES5 was released in 2009 and ES6 in 2015. ES5 was good but lengthy. The new ES6 is a major update and enhancement on ES5 in terms of code optimization and readability, in other words, ES-6 syntax helps an individual the long, tedious code bit shorter and easy to understand and grasp easily.
ES5:
The full form of ES5 is ECMA Script 5 and was developed in 2009.
Datatypes allowed here are number, string, null, Boolean, undefined, and Symbol.
ES5 uses the require module to import any member module in our script file.
Syntax:
var React = require('react'); // ES5
In ES5 we can only use var to define a variable in the global scope.
Es5 export any component as a module using the module.exports keyword.
Syntax:
module.exports = Component; // ES5
ES5 uses the function keyword along with the return keyword to define a function.
Syntax:
// ES5
var sum = function(x, y) {
return x + y;
};
ES5 uses the createReactClass() or React.createClass() API to create a react component class and defines a react component state using getInitialState() method.
Object manipulation is slow for processing.
ES5 lacks new features for its performance so it is comparatively low which makes it less readable (with time).
ES5 has huge community support since it has been used for long.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Example 1: Using Reactβs ES5 syntax
Inside the index.js file
Javascript
var React = require("react"); // ES5var ReactDOM = require("react-dom"); // ES5var createReactClass = require("create-react-class"); // ES5 // ES5 Syntaxvar CountComp = createReactClass({ getInitialState: function () { return { counter: 0, }; }, Increase: function () { this.setState({ counter: this.state.counter + 1, }); }, Decrease: function () { this.setState({ counter: this.state.counter - 1, }); }, render: function () { return ( <div> <button onClick={this.Increase}> Count increase </button> <h1> {this.state.counter} </h1> <button onClick={this.Decrease}> Count decrease </button> </div> ); },}); // ES5 Syntaxvar Component = createReactClass({ render: function () { return ( <div> <CountComp /> </div> ); },}); ReactDOM.render(<Component />, document.getElementById("root"));
Output:
ES6:
The full form of ES6 is ECMA Script 6 and was published in 2015.
Datatypes allowed here are number, string, null, Boolean, undefined, and Symbol.
ES6 uses the import module to import any member module in our script file.
Syntax:
import React from 'react'; // ES6
In ES6 we can also use let and const to define a variable locally.
Es5 export any component as module using the export default keyword.
Syntax:
export default Component; // ES6
In ES6 we donβt need to use a function keyword to define a function. The use of the Arrow function in ES6 makes it more compact. These are a function which is described by the β=>β syntax.
Syntax:
var sum = (x,y)=>{ return x+y };// ES6
ES6 uses the ES6 class which extends React.Component and defines a react component state using this.state in the constructor().
Object manipulation is fast because of object destructing. This process strengthens the binding pattern by allowing its pattern matching.
ES6 provides high performance due to advanced features added to it and code optimization.
ES6 has less community support than ES5 as it is a recent update on ES5 and not all browser supports it.
Example 2: Using Reactβs ES6 syntax
Inside the index.js file
Javascript
import React from "react"; // ES6import ReactDOM from "react-dom"; // ES6 let CountComp = (Compprop) => class extends React.Component { constructor(props) { super(props); this.state = { counter: 0, }; this.Increase = this.Increase.bind(this); this.Decrease = this.Decrease.bind(this); } // ES6 Syntax // ES6 Syntax Increase() { this.setState({ counter: this.state.counter + 1, }); } Decrease() { this.setState({ counter: this.state.counter - 1, }); } render() { return ( <div> <Compprop {...this.state} increase={this.Increase} decrease={this.Decrease} /> </div> ); } }; // ES6 Syntaxconst Button = (props) => { return ( <div> <button onClick={props.increase}> Count increase </button> <h1> {props.counter} </h1> <button onClick={props.decrease}> Count decrease </button> </div> );}; // ES6 Syntaxlet CompClick = CountComp(Button); const Component = () => { return ( <div> <CompClick /> </div> );}; ReactDOM.render(<Component />, document.getElementById("root"));
Output:
Difference between ES5 and ES6:
amansingla
ES6
JavaScript-Questions
Picked
React-Questions
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 720,
"s": 54,
"text": "In this article, we will learn whatβs the exact difference between ES6 and ES5 syntaxes in ReactJs. Both ES6 and ES5 are Javascript scripting languages in the development industry. ECMA Script or ES is a trademarked scripting language made by ECMA International. The European Computer Manufacture Association or ECMA is used for client-side scripting for the worldwide web. ES5 was released in 2009 and ES6 in 2015. ES5 was good but lengthy. The new ES6 is a major update and enhancement on ES5 in terms of code optimization and readability, in other words, ES-6 syntax helps an individual the long, tedious code bit shorter and easy to understand and grasp easily."
},
{
"code": null,
"e": 725,
"s": 720,
"text": "ES5:"
},
{
"code": null,
"e": 790,
"s": 725,
"text": "The full form of ES5 is ECMA Script 5 and was developed in 2009."
},
{
"code": null,
"e": 871,
"s": 790,
"text": "Datatypes allowed here are number, string, null, Boolean, undefined, and Symbol."
},
{
"code": null,
"e": 947,
"s": 871,
"text": "ES5 uses the require module to import any member module in our script file."
},
{
"code": null,
"e": 955,
"s": 947,
"text": "Syntax:"
},
{
"code": null,
"e": 992,
"s": 955,
"text": "var React = require('react'); // ES5"
},
{
"code": null,
"e": 1061,
"s": 992,
"text": "In ES5 we can only use var to define a variable in the global scope."
},
{
"code": null,
"e": 1132,
"s": 1061,
"text": "Es5 export any component as a module using the module.exports keyword."
},
{
"code": null,
"e": 1140,
"s": 1132,
"text": "Syntax:"
},
{
"code": null,
"e": 1176,
"s": 1140,
"text": " module.exports = Component; // ES5"
},
{
"code": null,
"e": 1258,
"s": 1176,
"text": "ES5 uses the function keyword along with the return keyword to define a function."
},
{
"code": null,
"e": 1266,
"s": 1258,
"text": "Syntax:"
},
{
"code": null,
"e": 1321,
"s": 1266,
"text": "// ES5\nvar sum = function(x, y) {\n return x + y;\n};"
},
{
"code": null,
"e": 1482,
"s": 1321,
"text": "ES5 uses the createReactClass() or React.createClass() API to create a react component class and defines a react component state using getInitialState() method."
},
{
"code": null,
"e": 1526,
"s": 1482,
"text": "Object manipulation is slow for processing."
},
{
"code": null,
"e": 1638,
"s": 1526,
"text": "ES5 lacks new features for its performance so it is comparatively low which makes it less readable (with time)."
},
{
"code": null,
"e": 1702,
"s": 1638,
"text": "ES5 has huge community support since it has been used for long."
},
{
"code": null,
"e": 1752,
"s": 1702,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 1816,
"s": 1752,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 1848,
"s": 1816,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 1948,
"s": 1848,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 1962,
"s": 1948,
"text": "cd foldername"
},
{
"code": null,
"e": 2014,
"s": 1962,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 2144,
"s": 2014,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 2180,
"s": 2144,
"text": "Example 1: Using Reactβs ES5 syntax"
},
{
"code": null,
"e": 2205,
"s": 2180,
"text": "Inside the index.js file"
},
{
"code": null,
"e": 2216,
"s": 2205,
"text": "Javascript"
},
{
"code": "var React = require(\"react\"); // ES5var ReactDOM = require(\"react-dom\"); // ES5var createReactClass = require(\"create-react-class\"); // ES5 // ES5 Syntaxvar CountComp = createReactClass({ getInitialState: function () { return { counter: 0, }; }, Increase: function () { this.setState({ counter: this.state.counter + 1, }); }, Decrease: function () { this.setState({ counter: this.state.counter - 1, }); }, render: function () { return ( <div> <button onClick={this.Increase}> Count increase </button> <h1> {this.state.counter} </h1> <button onClick={this.Decrease}> Count decrease </button> </div> ); },}); // ES5 Syntaxvar Component = createReactClass({ render: function () { return ( <div> <CountComp /> </div> ); },}); ReactDOM.render(<Component />, document.getElementById(\"root\"));",
"e": 3141,
"s": 2216,
"text": null
},
{
"code": null,
"e": 3149,
"s": 3141,
"text": "Output:"
},
{
"code": null,
"e": 3154,
"s": 3149,
"text": "ES6:"
},
{
"code": null,
"e": 3219,
"s": 3154,
"text": "The full form of ES6 is ECMA Script 6 and was published in 2015."
},
{
"code": null,
"e": 3300,
"s": 3219,
"text": "Datatypes allowed here are number, string, null, Boolean, undefined, and Symbol."
},
{
"code": null,
"e": 3375,
"s": 3300,
"text": "ES6 uses the import module to import any member module in our script file."
},
{
"code": null,
"e": 3383,
"s": 3375,
"text": "Syntax:"
},
{
"code": null,
"e": 3417,
"s": 3383,
"text": "import React from 'react'; // ES6"
},
{
"code": null,
"e": 3484,
"s": 3417,
"text": "In ES6 we can also use let and const to define a variable locally."
},
{
"code": null,
"e": 3553,
"s": 3484,
"text": "Es5 export any component as module using the export default keyword."
},
{
"code": null,
"e": 3561,
"s": 3553,
"text": "Syntax:"
},
{
"code": null,
"e": 3594,
"s": 3561,
"text": "export default Component; // ES6"
},
{
"code": null,
"e": 3783,
"s": 3594,
"text": "In ES6 we donβt need to use a function keyword to define a function. The use of the Arrow function in ES6 makes it more compact. These are a function which is described by the β=>β syntax."
},
{
"code": null,
"e": 3791,
"s": 3783,
"text": "Syntax:"
},
{
"code": null,
"e": 3830,
"s": 3791,
"text": "var sum = (x,y)=>{ return x+y };// ES6"
},
{
"code": null,
"e": 3958,
"s": 3830,
"text": "ES6 uses the ES6 class which extends React.Component and defines a react component state using this.state in the constructor()."
},
{
"code": null,
"e": 4096,
"s": 3958,
"text": "Object manipulation is fast because of object destructing. This process strengthens the binding pattern by allowing its pattern matching."
},
{
"code": null,
"e": 4186,
"s": 4096,
"text": "ES6 provides high performance due to advanced features added to it and code optimization."
},
{
"code": null,
"e": 4291,
"s": 4186,
"text": "ES6 has less community support than ES5 as it is a recent update on ES5 and not all browser supports it."
},
{
"code": null,
"e": 4327,
"s": 4291,
"text": "Example 2: Using Reactβs ES6 syntax"
},
{
"code": null,
"e": 4352,
"s": 4327,
"text": "Inside the index.js file"
},
{
"code": null,
"e": 4363,
"s": 4352,
"text": "Javascript"
},
{
"code": "import React from \"react\"; // ES6import ReactDOM from \"react-dom\"; // ES6 let CountComp = (Compprop) => class extends React.Component { constructor(props) { super(props); this.state = { counter: 0, }; this.Increase = this.Increase.bind(this); this.Decrease = this.Decrease.bind(this); } // ES6 Syntax // ES6 Syntax Increase() { this.setState({ counter: this.state.counter + 1, }); } Decrease() { this.setState({ counter: this.state.counter - 1, }); } render() { return ( <div> <Compprop {...this.state} increase={this.Increase} decrease={this.Decrease} /> </div> ); } }; // ES6 Syntaxconst Button = (props) => { return ( <div> <button onClick={props.increase}> Count increase </button> <h1> {props.counter} </h1> <button onClick={props.decrease}> Count decrease </button> </div> );}; // ES6 Syntaxlet CompClick = CountComp(Button); const Component = () => { return ( <div> <CompClick /> </div> );}; ReactDOM.render(<Component />, document.getElementById(\"root\"));",
"e": 5559,
"s": 4363,
"text": null
},
{
"code": null,
"e": 5567,
"s": 5559,
"text": "Output:"
},
{
"code": null,
"e": 5599,
"s": 5567,
"text": "Difference between ES5 and ES6:"
},
{
"code": null,
"e": 5610,
"s": 5599,
"text": "amansingla"
},
{
"code": null,
"e": 5614,
"s": 5610,
"text": "ES6"
},
{
"code": null,
"e": 5635,
"s": 5614,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 5642,
"s": 5635,
"text": "Picked"
},
{
"code": null,
"e": 5658,
"s": 5642,
"text": "React-Questions"
},
{
"code": null,
"e": 5669,
"s": 5658,
"text": "JavaScript"
},
{
"code": null,
"e": 5677,
"s": 5669,
"text": "ReactJS"
},
{
"code": null,
"e": 5694,
"s": 5677,
"text": "Web Technologies"
}
] |
Python | Convert numeric words to numbers
|
22 Apr, 2020
Sometimes, while working with python Strings, we can have a problem in which we need to convert the strings that are in form of named numbers to actual numbers. This has application in Mathematical domains and Data Science domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop + join() + split()One of the ways to solve this problem is to use a map, where one can map the numeric with words and then split the strings and rejoin using mapping to numbers.
# Python3 code to demonstrate working of # Convert numeric words to numbers# Using join() + split() help_dict = { 'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9', 'zero' : '0'} # initializing stringtest_str = "zero four zero one" # printing original stringprint("The original string is : " + test_str) # Convert numeric words to numbers# Using join() + split()res = ''.join(help_dict[ele] for ele in test_str.split()) # printing result print("The string after performing replace : " + res)
The original string is : zero four zero one
The string after performing replace : 0401
Method #2 : Using word2number libraryThis problem can also be solved using PyPI library word2number. It has inbuilt functions that converts words to numbers.
# Python3 code to demonstrate working of # Convert numeric words to numbers# Using word2numberfrom word2number import w2n # initializing stringtest_str = "zero four zero one" # printing original stringprint("The original string is : " + test_str) # Convert numeric words to numbers# Using word2numberres = w2n.word_to_num(test_str) # printing result print("The string after performing replace : " + str(res))
The original string is : zero four zero one
The string after performing replace : 0401
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
Rotate axis tick labels in Seaborn and Matplotlib
Enumerate() in Python
Deque in Python
Stack in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Iterate over characters of a string in Python
Python | Convert set into a list
Python program to convert a list to string
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 347,
"s": 52,
"text": "Sometimes, while working with python Strings, we can have a problem in which we need to convert the strings that are in form of named numbers to actual numbers. This has application in Mathematical domains and Data Science domains. Lets discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 548,
"s": 347,
"text": "Method #1 : Using loop + join() + split()One of the ways to solve this problem is to use a map, where one can map the numeric with words and then split the strings and rejoin using mapping to numbers."
},
{
"code": "# Python3 code to demonstrate working of # Convert numeric words to numbers# Using join() + split() help_dict = { 'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9', 'zero' : '0'} # initializing stringtest_str = \"zero four zero one\" # printing original stringprint(\"The original string is : \" + test_str) # Convert numeric words to numbers# Using join() + split()res = ''.join(help_dict[ele] for ele in test_str.split()) # printing result print(\"The string after performing replace : \" + res) ",
"e": 1142,
"s": 548,
"text": null
},
{
"code": null,
"e": 1230,
"s": 1142,
"text": "The original string is : zero four zero one\nThe string after performing replace : 0401\n"
},
{
"code": null,
"e": 1390,
"s": 1232,
"text": "Method #2 : Using word2number libraryThis problem can also be solved using PyPI library word2number. It has inbuilt functions that converts words to numbers."
},
{
"code": "# Python3 code to demonstrate working of # Convert numeric words to numbers# Using word2numberfrom word2number import w2n # initializing stringtest_str = \"zero four zero one\" # printing original stringprint(\"The original string is : \" + test_str) # Convert numeric words to numbers# Using word2numberres = w2n.word_to_num(test_str) # printing result print(\"The string after performing replace : \" + str(res)) ",
"e": 1804,
"s": 1390,
"text": null
},
{
"code": null,
"e": 1892,
"s": 1804,
"text": "The original string is : zero four zero one\nThe string after performing replace : 0401\n"
},
{
"code": null,
"e": 1915,
"s": 1892,
"text": "Python string-programs"
},
{
"code": null,
"e": 1922,
"s": 1915,
"text": "Python"
},
{
"code": null,
"e": 1938,
"s": 1922,
"text": "Python Programs"
},
{
"code": null,
"e": 2036,
"s": 1938,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2066,
"s": 2036,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2116,
"s": 2066,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 2138,
"s": 2116,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2154,
"s": 2138,
"text": "Deque in Python"
},
{
"code": null,
"e": 2170,
"s": 2154,
"text": "Stack in Python"
},
{
"code": null,
"e": 2192,
"s": 2170,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2231,
"s": 2192,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2277,
"s": 2231,
"text": "Iterate over characters of a string in Python"
},
{
"code": null,
"e": 2310,
"s": 2277,
"text": "Python | Convert set into a list"
}
] |
Scala | Functions Call-by-Name
|
08 Apr, 2019
In Scala when arguments pass through call-by-value function it compute the passed-in expressionβs or arguments value once before calling the function . But a call-by-Name function in Scala calls the expression and recompute the passed-in expressionβs value every time it get accessed inside the function. Here example are shown with difference and syntax.
This method uses in-mode semantics. Changes made to formal parameter do not get transmitted back to the caller. Any modifications to the formal parameter variable inside the called function or method affect only the separate storage location and will not be reflected in the actual parameter in the calling environment. This method is also called as call by value.
Syntax :
def callByValue(x: Int)
// Scala program of function call-by-value // Creating objectobject GFG { // Main method def main(args: Array[String]) { // Defined function def ArticleCounts(i: Int) { println("Tanya did article " + "on day one is 1 - Total = " + i) println("Tanya did article " + "on day two is 1 - Total = " + i) println("Tanya did article "+ "on day three is 1 - Total = " + i) println("Tanya did article " + "on day four is 1 - Total = " + i) } var Total = 0; // function call ArticleCounts { Total += 1 ; Total } }}
Tanya did article on day one is 1 - Total = 1
Tanya did article on day two is 1 - Total = 1
Tanya did article on day three is 1 - Total = 1
Tanya did article on day four is 1 - Total = 1
Here, by using function call-by-value mechanism in above program total count of article not increased.
A call-by-name mechanism passes a code block to the function call and the code block is complied, executed and calculated the value. message will be printed first than returns the value.Syntax :
def callByName(x: => Int)
Example :
// Scala program of function call-by-name // Creating objectobject main { // Main method def main(args: Array[String]) { // Defined function call-by-name def ArticleCounts(i: => Int) { println("Tanya did articles " + " on day one is 1 - Total = " + i) println("Tanya did articles "+ "on day two is 1 - Total = " + i) println("Tanya did articles " + "on day three is 1 - Total = " + i) println("Tanya did articles " + "on day four is 1 - Total = " + i) } var Total = 0; // calling function ArticleCounts { Total += 1 ; Total }}}
Tanya did articles on day one is 1 - Total = 1
Tanya did articles on day two is 1 - Total = 2
Tanya did articles on day three is 1 - Total = 3
Tanya did articles on day four is 1 - Total = 4
Here, by using function call-by-name mechanism in above program total count of article will increased.Another program of function call-by-name.
Example :
// Scala program of function call-by-name // Creating objectobject GFG{ // Main method def main(args: Array[String]) { def something() = { println("calling something") 1 // return value } // Defined function def callByName(x: => Int) = { println("x1=" + x) println("x2=" + x) } // Calling function callByName(something) }}
calling something
x1=1
calling something
x2=1
Picked
Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Type Casting in Scala
Scala List filter() method with example
Scala Map
Scala Tutorial β Learn Scala with Step By Step Guide
Scala Lists
Operators in Scala
Scala | Arrays
Scala Constructors
Inheritance in Scala
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Apr, 2019"
},
{
"code": null,
"e": 384,
"s": 28,
"text": "In Scala when arguments pass through call-by-value function it compute the passed-in expressionβs or arguments value once before calling the function . But a call-by-Name function in Scala calls the expression and recompute the passed-in expressionβs value every time it get accessed inside the function. Here example are shown with difference and syntax."
},
{
"code": null,
"e": 749,
"s": 384,
"text": "This method uses in-mode semantics. Changes made to formal parameter do not get transmitted back to the caller. Any modifications to the formal parameter variable inside the called function or method affect only the separate storage location and will not be reflected in the actual parameter in the calling environment. This method is also called as call by value."
},
{
"code": null,
"e": 758,
"s": 749,
"text": "Syntax :"
},
{
"code": null,
"e": 782,
"s": 758,
"text": "def callByValue(x: Int)"
},
{
"code": "// Scala program of function call-by-value // Creating objectobject GFG { // Main method def main(args: Array[String]) { // Defined function def ArticleCounts(i: Int) { println(\"Tanya did article \" + \"on day one is 1 - Total = \" + i) println(\"Tanya did article \" + \"on day two is 1 - Total = \" + i) println(\"Tanya did article \"+ \"on day three is 1 - Total = \" + i) println(\"Tanya did article \" + \"on day four is 1 - Total = \" + i) } var Total = 0; // function call ArticleCounts { Total += 1 ; Total } }}",
"e": 1524,
"s": 782,
"text": null
},
{
"code": null,
"e": 1712,
"s": 1524,
"text": "Tanya did article on day one is 1 - Total = 1\nTanya did article on day two is 1 - Total = 1\nTanya did article on day three is 1 - Total = 1\nTanya did article on day four is 1 - Total = 1\n"
},
{
"code": null,
"e": 1815,
"s": 1712,
"text": "Here, by using function call-by-value mechanism in above program total count of article not increased."
},
{
"code": null,
"e": 2010,
"s": 1815,
"text": "A call-by-name mechanism passes a code block to the function call and the code block is complied, executed and calculated the value. message will be printed first than returns the value.Syntax :"
},
{
"code": null,
"e": 2036,
"s": 2010,
"text": "def callByName(x: => Int)"
},
{
"code": null,
"e": 2046,
"s": 2036,
"text": "Example :"
},
{
"code": "// Scala program of function call-by-name // Creating objectobject main { // Main method def main(args: Array[String]) { // Defined function call-by-name def ArticleCounts(i: => Int) { println(\"Tanya did articles \" + \" on day one is 1 - Total = \" + i) println(\"Tanya did articles \"+ \"on day two is 1 - Total = \" + i) println(\"Tanya did articles \" + \"on day three is 1 - Total = \" + i) println(\"Tanya did articles \" + \"on day four is 1 - Total = \" + i) } var Total = 0; // calling function ArticleCounts { Total += 1 ; Total }}}",
"e": 2796,
"s": 2046,
"text": null
},
{
"code": null,
"e": 2989,
"s": 2796,
"text": "Tanya did articles on day one is 1 - Total = 1\nTanya did articles on day two is 1 - Total = 2\nTanya did articles on day three is 1 - Total = 3\nTanya did articles on day four is 1 - Total = 4\n"
},
{
"code": null,
"e": 3133,
"s": 2989,
"text": "Here, by using function call-by-name mechanism in above program total count of article will increased.Another program of function call-by-name."
},
{
"code": null,
"e": 3143,
"s": 3133,
"text": "Example :"
},
{
"code": "// Scala program of function call-by-name // Creating objectobject GFG{ // Main method def main(args: Array[String]) { def something() = { println(\"calling something\") 1 // return value } // Defined function def callByName(x: => Int) = { println(\"x1=\" + x) println(\"x2=\" + x) } // Calling function callByName(something) }}",
"e": 3609,
"s": 3143,
"text": null
},
{
"code": null,
"e": 3656,
"s": 3609,
"text": "calling something\nx1=1\ncalling something\nx2=1\n"
},
{
"code": null,
"e": 3663,
"s": 3656,
"text": "Picked"
},
{
"code": null,
"e": 3669,
"s": 3663,
"text": "Scala"
},
{
"code": null,
"e": 3682,
"s": 3669,
"text": "Scala-Method"
},
{
"code": null,
"e": 3688,
"s": 3682,
"text": "Scala"
},
{
"code": null,
"e": 3786,
"s": 3688,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3812,
"s": 3786,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 3834,
"s": 3812,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 3874,
"s": 3834,
"text": "Scala List filter() method with example"
},
{
"code": null,
"e": 3884,
"s": 3874,
"text": "Scala Map"
},
{
"code": null,
"e": 3937,
"s": 3884,
"text": "Scala Tutorial β Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 3949,
"s": 3937,
"text": "Scala Lists"
},
{
"code": null,
"e": 3968,
"s": 3949,
"text": "Operators in Scala"
},
{
"code": null,
"e": 3983,
"s": 3968,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 4002,
"s": 3983,
"text": "Scala Constructors"
}
] |
How to display an error for invalid input with php/html ?
|
31 Dec, 2020
PHP can be easily embedded in HTML files and HTML codes can also be written in a PHP file. The thing that differentiates PHP from a client-side language like HTML is, PHP codes are executed on the server whereas HTML codes are directly rendered on the browser. To display error for invalid input with HTML and PHP.
Approach:
Display error on invalid error when
input textbox is left empty.
input is wrong.
PHP code: The following is the code for βform.phpβ which is used in the HTML code in the later part.
To show invalid input in PHP, set the name of the input textbox which is in HTML. All the fields are first checked for empty fields and then it is validated for correctness. If all fields are correct then it shows the success message. If the input given by the user is wrong then it will show a message for β Invalid input!!β.
PHP
<?php$nameError = "";$emailError = "";$passwordError = "";$mobileError = "";$success = ""; function validate_input($input) { $input = trim($input); $input = stripslashes($input); $input = htmlspecialchars($input); return $input;} if(isset($_POST['form_submit'])) { $name = $_POST['name']; $password = $_POST['password']; $email = $_POST['user_email']; $mobile = $_POST['mobile']; if (empty($_POST["name"])) { $nameError = "Name is required"; } else { $name = validate_input($_POST["name"]); if($name == 'chetan') { $success= "Thank you ". $name.", "; echo $success; } } if (empty($_POST["email"])) { $emailError = "Email is required"; } else { $email = validate_input($_POST["email"]); if($email == '[email protected]') { $success= $email." is correct"; echo $success; } } if (empty($_POST["password"])) { $passwordError = "Password is required"; } else { $password = validate_input($_POST["password"]); if($password == 'test@123') { $success= $password." is correct"; echo $success; } } if (empty($_POST["mobile"])) { $mobileError = "Mobile is required"; } else { $mobile = validate_input($_POST["mobile"]); if($mobile == '123456789') { $success= $mobile." is correct"; echo $success; } } if(empty($success)) echo "Invalid input!!!";}?>
HTML code: The following code uses the above PHP βform.phpβ code.
HTML
<!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Form</title></head> <body> <form action="form.php" method="POST"> <input type="text" name="name" placeholder="Enter name"> <input type="password" name="password" placeholder="Password"> <input type="email" name="user_email" placeholder="[email protected]"> <input type="tel" name="mobile" placeholder="Mobile no"> <button type="submit" name="form_submit"> Submit </button> </form></body> </html>
Output:
Incorrect input by userInvalid input!!!
Invalid input!!!
Correct input by user Thank you chetan, 123456789 is correct
Thank you chetan, 123456789 is correct
HTML-Misc
PHP-Misc
Picked
Technical Scripter 2020
HTML
PHP
Technical Scripter
Web Technologies
HTML
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
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 convert array to string in PHP ?
How to pop an alert message box using PHP ?
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n31 Dec, 2020"
},
{
"code": null,
"e": 370,
"s": 53,
"text": " PHP can be easily embedded in HTML files and HTML codes can also be written in a PHP file. The thing that differentiates PHP from a client-side language like HTML is, PHP codes are executed on the server whereas HTML codes are directly rendered on the browser. To display error for invalid input with HTML and PHP. "
},
{
"code": null,
"e": 380,
"s": 370,
"text": "Approach:"
},
{
"code": null,
"e": 416,
"s": 380,
"text": "Display error on invalid error when"
},
{
"code": null,
"e": 445,
"s": 416,
"text": "input textbox is left empty."
},
{
"code": null,
"e": 461,
"s": 445,
"text": "input is wrong."
},
{
"code": null,
"e": 562,
"s": 461,
"text": "PHP code: The following is the code for βform.phpβ which is used in the HTML code in the later part."
},
{
"code": null,
"e": 889,
"s": 562,
"text": "To show invalid input in PHP, set the name of the input textbox which is in HTML. All the fields are first checked for empty fields and then it is validated for correctness. If all fields are correct then it shows the success message. If the input given by the user is wrong then it will show a message for β Invalid input!!β."
},
{
"code": null,
"e": 893,
"s": 889,
"text": "PHP"
},
{
"code": "<?php$nameError = \"\";$emailError = \"\";$passwordError = \"\";$mobileError = \"\";$success = \"\"; function validate_input($input) { $input = trim($input); $input = stripslashes($input); $input = htmlspecialchars($input); return $input;} if(isset($_POST['form_submit'])) { $name = $_POST['name']; $password = $_POST['password']; $email = $_POST['user_email']; $mobile = $_POST['mobile']; if (empty($_POST[\"name\"])) { $nameError = \"Name is required\"; } else { $name = validate_input($_POST[\"name\"]); if($name == 'chetan') { $success= \"Thank you \". $name.\", \"; echo $success; } } if (empty($_POST[\"email\"])) { $emailError = \"Email is required\"; } else { $email = validate_input($_POST[\"email\"]); if($email == '[email protected]') { $success= $email.\" is correct\"; echo $success; } } if (empty($_POST[\"password\"])) { $passwordError = \"Password is required\"; } else { $password = validate_input($_POST[\"password\"]); if($password == 'test@123') { $success= $password.\" is correct\"; echo $success; } } if (empty($_POST[\"mobile\"])) { $mobileError = \"Mobile is required\"; } else { $mobile = validate_input($_POST[\"mobile\"]); if($mobile == '123456789') { $success= $mobile.\" is correct\"; echo $success; } } if(empty($success)) echo \"Invalid input!!!\";}?>",
"e": 2458,
"s": 893,
"text": null
},
{
"code": null,
"e": 2524,
"s": 2458,
"text": "HTML code: The following code uses the above PHP βform.phpβ code."
},
{
"code": null,
"e": 2529,
"s": 2524,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <meta charset=\"utf-8\"> <title>Form</title></head> <body> <form action=\"form.php\" method=\"POST\"> <input type=\"text\" name=\"name\" placeholder=\"Enter name\"> <input type=\"password\" name=\"password\" placeholder=\"Password\"> <input type=\"email\" name=\"user_email\" placeholder=\"[email protected]\"> <input type=\"tel\" name=\"mobile\" placeholder=\"Mobile no\"> <button type=\"submit\" name=\"form_submit\"> Submit </button> </form></body> </html>",
"e": 3128,
"s": 2529,
"text": null
},
{
"code": null,
"e": 3136,
"s": 3128,
"text": "Output:"
},
{
"code": null,
"e": 3176,
"s": 3136,
"text": "Incorrect input by userInvalid input!!!"
},
{
"code": null,
"e": 3193,
"s": 3176,
"text": "Invalid input!!!"
},
{
"code": null,
"e": 3254,
"s": 3193,
"text": "Correct input by user Thank you chetan, 123456789 is correct"
},
{
"code": null,
"e": 3293,
"s": 3254,
"text": "Thank you chetan, 123456789 is correct"
},
{
"code": null,
"e": 3303,
"s": 3293,
"text": "HTML-Misc"
},
{
"code": null,
"e": 3312,
"s": 3303,
"text": "PHP-Misc"
},
{
"code": null,
"e": 3319,
"s": 3312,
"text": "Picked"
},
{
"code": null,
"e": 3343,
"s": 3319,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3348,
"s": 3343,
"text": "HTML"
},
{
"code": null,
"e": 3352,
"s": 3348,
"text": "PHP"
},
{
"code": null,
"e": 3371,
"s": 3352,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3388,
"s": 3371,
"text": "Web Technologies"
},
{
"code": null,
"e": 3393,
"s": 3388,
"text": "HTML"
},
{
"code": null,
"e": 3397,
"s": 3393,
"text": "PHP"
},
{
"code": null,
"e": 3495,
"s": 3397,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3519,
"s": 3495,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3558,
"s": 3519,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 3597,
"s": 3558,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 3617,
"s": 3597,
"text": "Angular File Upload"
},
{
"code": null,
"e": 3646,
"s": 3617,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 3691,
"s": 3646,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 3715,
"s": 3691,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 3767,
"s": 3715,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 3807,
"s": 3767,
"text": "How to convert array to string in PHP ?"
}
] |
How to check if value exists with MySQL SELECT 1?
|
Use SELECT 1 for this as in the below syntax β
select 1 from yourTableName where yourColumnName=yourValue;
If the above returns 1, that means value exists in the MySQL database. Let us first see an example and create a table β
mysql> create table DemoTable
(
StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
StudentName varchar(40),
StudentAge int
);
Query OK, 0 rows affected (0.46 sec)
Insert some records in the table using insert command β
mysql> insert into DemoTable(StudentName,StudentAge) values('Chris',21);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(StudentName,StudentAge) values('David',20);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(StudentName,StudentAge) values('Bob',22);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(StudentName,StudentAge) values('Tom',19);
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement β
mysql> select *from DemoTable;
This will produce the following output β
+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
| 1 | Chris | 21 |
| 2 | David | 20 |
| 3 | Bob | 22 |
| 4 | Tom | 19 |
+-----------+-------------+------------+
4 rows in set (0.00 sec)
Let us now check if value exists in MySQL database β
mysql> select 1 from DemoTable where StudentName='Bob';
This will produce the following output β
+---+
| 1 |
+---+
| 1 |
+---+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1109,
"s": 1062,
"text": "Use SELECT 1 for this as in the below syntax β"
},
{
"code": null,
"e": 1169,
"s": 1109,
"text": "select 1 from yourTableName where yourColumnName=yourValue;"
},
{
"code": null,
"e": 1289,
"s": 1169,
"text": "If the above returns 1, that means value exists in the MySQL database. Let us first see an example and create a table β"
},
{
"code": null,
"e": 1461,
"s": 1289,
"text": "mysql> create table DemoTable\n(\n StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n StudentName varchar(40),\n StudentAge int\n);\nQuery OK, 0 rows affected (0.46 sec)"
},
{
"code": null,
"e": 1517,
"s": 1461,
"text": "Insert some records in the table using insert command β"
},
{
"code": null,
"e": 1949,
"s": 1517,
"text": "mysql> insert into DemoTable(StudentName,StudentAge) values('Chris',21);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable(StudentName,StudentAge) values('David',20);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable(StudentName,StudentAge) values('Bob',22);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable(StudentName,StudentAge) values('Tom',19);\nQuery OK, 1 row affected (0.15 sec)"
},
{
"code": null,
"e": 2009,
"s": 1949,
"text": "Display all records from the table using select statement β"
},
{
"code": null,
"e": 2040,
"s": 2009,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2081,
"s": 2040,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2434,
"s": 2081,
"text": "+-----------+-------------+------------+\n| StudentId | StudentName | StudentAge |\n+-----------+-------------+------------+\n| 1 | Chris | 21 |\n| 2 | David | 20 |\n| 3 | Bob | 22 |\n| 4 | Tom | 19 |\n+-----------+-------------+------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2487,
"s": 2434,
"text": "Let us now check if value exists in MySQL database β"
},
{
"code": null,
"e": 2543,
"s": 2487,
"text": "mysql> select 1 from DemoTable where StudentName='Bob';"
},
{
"code": null,
"e": 2584,
"s": 2543,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2638,
"s": 2584,
"text": "+---+\n| 1 |\n+---+\n| 1 |\n+---+\n1 row in set (0.00 sec)"
}
] |
How to Crop Image from Camera and Gallery in Android? - GeeksforGeeks
|
19 Feb, 2021
In the previous article, we have discussed how to select an Image from Gallery in Android, but in this project, there is no crop functionality. Sometimes we take pictures on our phone and want to update them as our profile picture. But we need to need to remove the background. So in that case we can use the crop image feature to remove that background and then we can upload that image. A sample video 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.
Media error: Format(s) not supported or source(s) not found
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: Add dependency to the build.gradle(Module:app) file
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.
// This library is used for crop image feature
api βcom.theartofdev.edmodo:android-image-cropper:2.8.+β
// This library is used for loading the
// cropped image into ImageView.
implementation βcom.squareup.picasso:picasso:2.5.2β
Step 3: Working with the AndroidManifest.xml file
Add below permission to the AndroidManifest.xml file.
<uses-permission android:name=βandroid.permission.READ_EXTERNAL_STORAGEβ />
<uses-permission android:name=βandroid.permission.WRITE_EXTERNAL_STORAGEβ />
<uses-permission android:name=βandroid.permission.CAMERAβ/>
Add below lines inside the <application> tag.
<activity
android:name=βcom.theartofdev.edmodo.cropper.CropImageActivityβ
android:theme=β@style/Base.Theme.AppCompatβ />
Below is the code for the complete AndroidManifest.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.anni.cropimage"> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.CAMERA" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.theartofdev.edmodo.cropper.CropImageActivity" android:theme="@style/Base.Theme.AppCompat" /> </application> </manifest>
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginBottom="100dp" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <!--Here the selected cropped image will be shown--> <ImageView android:id="@+id/set_profile_image" android:layout_width="300dp" android:layout_height="300dp" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="40dp" android:src="@drawable/ic_image_black_24dp" /> <!--Here we are clicking on this text to select an image from camera or gallery--> <TextView android:id="@+id/click" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click Here to select an Image" android:textSize="22sp" android:textStyle="bold" /> </LinearLayout>
Step 4: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.Manifest;import android.app.AlertDialog;import android.content.DialogInterface;import android.content.Intent;import android.content.pm.PackageManager;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.core.content.ContextCompat; import com.squareup.picasso.Picasso;import com.theartofdev.edmodo.cropper.CropImage; public class MainActivity extends AppCompatActivity { ImageView userpic; private static final int GalleryPick = 1; private static final int CAMERA_REQUEST = 100; private static final int STORAGE_REQUEST = 200; private static final int IMAGEPICK_GALLERY_REQUEST = 300; private static final int IMAGE_PICKCAMERA_REQUEST = 400; String cameraPermission[]; String storagePermission[]; Uri imageuri; TextView click; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Here we are initialising // the text and image View click = findViewById(R.id.click); userpic = findViewById(R.id.set_profile_image); // allowing permissions of gallery and camera cameraPermission = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; storagePermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}; // After clicking on text we will have // to choose whether to // select image from camera and gallery click.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showImagePicDialog(); } }); } private void showImagePicDialog() { String options[] = {"Camera", "Gallery"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Pick Image From"); builder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == 0) { if (!checkCameraPermission()) { requestCameraPermission(); } else { pickFromGallery(); } } else if (which == 1) { if (!checkStoragePermission()) { requestStoragePermission(); } else { pickFromGallery(); } } } }); builder.create().show(); } // checking storage permissions private Boolean checkStoragePermission() { boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED); return result; } // Requesting gallery permission private void requestStoragePermission() { requestPermissions(storagePermission, STORAGE_REQUEST); } // checking camera permissions private Boolean checkCameraPermission() { boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED); boolean result1 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED); return result && result1; } // Requesting camera permission private void requestCameraPermission() { requestPermissions(cameraPermission, CAMERA_REQUEST); } // Requesting camera and gallery // permission if not given @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case CAMERA_REQUEST: { if (grantResults.length > 0) { boolean camera_accepted = grantResults[0] == PackageManager.PERMISSION_GRANTED; boolean writeStorageaccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED; if (camera_accepted && writeStorageaccepted) { pickFromGallery(); } else { Toast.makeText(this, "Please Enable Camera and Storage Permissions", Toast.LENGTH_LONG).show(); } } } break; case STORAGE_REQUEST: { if (grantResults.length > 0) { boolean writeStorageaccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED; if (writeStorageaccepted) { pickFromGallery(); } else { Toast.makeText(this, "Please Enable Storage Permissions", Toast.LENGTH_LONG).show(); } } } break; } } // Here we will pick image from gallery or camera private void pickFromGallery() { CropImage.activity().start(MainActivity.this); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { CropImage.ActivityResult result = CropImage.getActivityResult(data); if (resultCode == RESULT_OK) { Uri resultUri = result.getUri(); Picasso.with(this).load(resultUri).into(userpic); } } }}
Media error: Format(s) not supported or source(s) not found
Github Link: https://github.com/Anni1123/CropImage
android
Picked
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Flexbox-Layout in Android
How to Post Data to API using Retrofit in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Stream In Java
Object Oriented Programming (OOPs) Concept in Java
|
[
{
"code": null,
"e": 26515,
"s": 26487,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 27071,
"s": 26515,
"text": "In the previous article, we have discussed how to select an Image from Gallery in Android, but in this project, there is no crop functionality. Sometimes we take pictures on our phone and want to update them as our profile picture. But we need to need to remove the background. So in that case we can use the crop image feature to remove that background and then we can upload that image. A sample video 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": 27131,
"s": 27071,
"text": "Media error: Format(s) not supported or source(s) not found"
},
{
"code": null,
"e": 27160,
"s": 27131,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 27322,
"s": 27160,
"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": 27382,
"s": 27322,
"text": "Step 2: Add dependency to the build.gradle(Module:app) file"
},
{
"code": null,
"e": 27501,
"s": 27382,
"text": "Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. "
},
{
"code": null,
"e": 27548,
"s": 27501,
"text": "// This library is used for crop image feature"
},
{
"code": null,
"e": 27605,
"s": 27548,
"text": "api βcom.theartofdev.edmodo:android-image-cropper:2.8.+β"
},
{
"code": null,
"e": 27647,
"s": 27605,
"text": "// This library is used for loading the "
},
{
"code": null,
"e": 27680,
"s": 27647,
"text": "// cropped image into ImageView."
},
{
"code": null,
"e": 27732,
"s": 27680,
"text": "implementation βcom.squareup.picasso:picasso:2.5.2β"
},
{
"code": null,
"e": 27782,
"s": 27732,
"text": "Step 3: Working with the AndroidManifest.xml file"
},
{
"code": null,
"e": 27836,
"s": 27782,
"text": "Add below permission to the AndroidManifest.xml file."
},
{
"code": null,
"e": 27912,
"s": 27836,
"text": "<uses-permission android:name=βandroid.permission.READ_EXTERNAL_STORAGEβ />"
},
{
"code": null,
"e": 27989,
"s": 27912,
"text": "<uses-permission android:name=βandroid.permission.WRITE_EXTERNAL_STORAGEβ />"
},
{
"code": null,
"e": 28049,
"s": 27989,
"text": "<uses-permission android:name=βandroid.permission.CAMERAβ/>"
},
{
"code": null,
"e": 28095,
"s": 28049,
"text": "Add below lines inside the <application> tag."
},
{
"code": null,
"e": 28105,
"s": 28095,
"text": "<activity"
},
{
"code": null,
"e": 28170,
"s": 28105,
"text": " android:name=βcom.theartofdev.edmodo.cropper.CropImageActivityβ"
},
{
"code": null,
"e": 28218,
"s": 28170,
"text": " android:theme=β@style/Base.Theme.AppCompatβ />"
},
{
"code": null,
"e": 28279,
"s": 28218,
"text": "Below is the code for the complete AndroidManifest.xml file."
},
{
"code": null,
"e": 28283,
"s": 28279,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.anni.cropimage\"> <uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\" /> <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" /> <uses-permission android:name=\"android.permission.CAMERA\" /> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> <activity android:name=\"com.theartofdev.edmodo.cropper.CropImageActivity\" android:theme=\"@style/Base.Theme.AppCompat\" /> </application> </manifest>",
"e": 29361,
"s": 28283,
"text": null
},
{
"code": null,
"e": 29409,
"s": 29361,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 29552,
"s": 29409,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 29556,
"s": 29552,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_marginBottom=\"100dp\" android:gravity=\"center\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--Here the selected cropped image will be shown--> <ImageView android:id=\"@+id/set_profile_image\" android:layout_width=\"300dp\" android:layout_height=\"300dp\" android:layout_alignParentTop=\"true\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"40dp\" android:src=\"@drawable/ic_image_black_24dp\" /> <!--Here we are clicking on this text to select an image from camera or gallery--> <TextView android:id=\"@+id/click\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Click Here to select an Image\" android:textSize=\"22sp\" android:textStyle=\"bold\" /> </LinearLayout>",
"e": 30671,
"s": 29556,
"text": null
},
{
"code": null,
"e": 30719,
"s": 30671,
"text": "Step 4: Working with the MainActivity.java file"
},
{
"code": null,
"e": 30909,
"s": 30719,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 30914,
"s": 30909,
"text": "Java"
},
{
"code": "import android.Manifest;import android.app.AlertDialog;import android.content.DialogInterface;import android.content.Intent;import android.content.pm.PackageManager;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.core.content.ContextCompat; import com.squareup.picasso.Picasso;import com.theartofdev.edmodo.cropper.CropImage; public class MainActivity extends AppCompatActivity { ImageView userpic; private static final int GalleryPick = 1; private static final int CAMERA_REQUEST = 100; private static final int STORAGE_REQUEST = 200; private static final int IMAGEPICK_GALLERY_REQUEST = 300; private static final int IMAGE_PICKCAMERA_REQUEST = 400; String cameraPermission[]; String storagePermission[]; Uri imageuri; TextView click; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Here we are initialising // the text and image View click = findViewById(R.id.click); userpic = findViewById(R.id.set_profile_image); // allowing permissions of gallery and camera cameraPermission = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; storagePermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}; // After clicking on text we will have // to choose whether to // select image from camera and gallery click.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showImagePicDialog(); } }); } private void showImagePicDialog() { String options[] = {\"Camera\", \"Gallery\"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(\"Pick Image From\"); builder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == 0) { if (!checkCameraPermission()) { requestCameraPermission(); } else { pickFromGallery(); } } else if (which == 1) { if (!checkStoragePermission()) { requestStoragePermission(); } else { pickFromGallery(); } } } }); builder.create().show(); } // checking storage permissions private Boolean checkStoragePermission() { boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED); return result; } // Requesting gallery permission private void requestStoragePermission() { requestPermissions(storagePermission, STORAGE_REQUEST); } // checking camera permissions private Boolean checkCameraPermission() { boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED); boolean result1 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED); return result && result1; } // Requesting camera permission private void requestCameraPermission() { requestPermissions(cameraPermission, CAMERA_REQUEST); } // Requesting camera and gallery // permission if not given @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case CAMERA_REQUEST: { if (grantResults.length > 0) { boolean camera_accepted = grantResults[0] == PackageManager.PERMISSION_GRANTED; boolean writeStorageaccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED; if (camera_accepted && writeStorageaccepted) { pickFromGallery(); } else { Toast.makeText(this, \"Please Enable Camera and Storage Permissions\", Toast.LENGTH_LONG).show(); } } } break; case STORAGE_REQUEST: { if (grantResults.length > 0) { boolean writeStorageaccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED; if (writeStorageaccepted) { pickFromGallery(); } else { Toast.makeText(this, \"Please Enable Storage Permissions\", Toast.LENGTH_LONG).show(); } } } break; } } // Here we will pick image from gallery or camera private void pickFromGallery() { CropImage.activity().start(MainActivity.this); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { CropImage.ActivityResult result = CropImage.getActivityResult(data); if (resultCode == RESULT_OK) { Uri resultUri = result.getUri(); Picasso.with(this).load(resultUri).into(userpic); } } }}",
"e": 36684,
"s": 30914,
"text": null
},
{
"code": null,
"e": 36744,
"s": 36684,
"text": "Media error: Format(s) not supported or source(s) not found"
},
{
"code": null,
"e": 36795,
"s": 36744,
"text": "Github Link: https://github.com/Anni1123/CropImage"
},
{
"code": null,
"e": 36803,
"s": 36795,
"text": "android"
},
{
"code": null,
"e": 36810,
"s": 36803,
"text": "Picked"
},
{
"code": null,
"e": 36834,
"s": 36810,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 36842,
"s": 36834,
"text": "Android"
},
{
"code": null,
"e": 36847,
"s": 36842,
"text": "Java"
},
{
"code": null,
"e": 36866,
"s": 36847,
"text": "Technical Scripter"
},
{
"code": null,
"e": 36871,
"s": 36866,
"text": "Java"
},
{
"code": null,
"e": 36879,
"s": 36871,
"text": "Android"
},
{
"code": null,
"e": 36977,
"s": 36879,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37015,
"s": 36977,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 37054,
"s": 37015,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 37104,
"s": 37054,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 37130,
"s": 37104,
"text": "Flexbox-Layout in Android"
},
{
"code": null,
"e": 37181,
"s": 37130,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 37196,
"s": 37181,
"text": "Arrays in Java"
},
{
"code": null,
"e": 37240,
"s": 37196,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 37262,
"s": 37240,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 37277,
"s": 37262,
"text": "Stream In Java"
}
] |
What is the difference between a string and a byte string in Python?
|
A string is a sequence of characters; these are an abstract concept, and can't be directly stored on disk. A byte string is a sequence of bytes - things that can be stored on disk. The mapping between them is an encoding - there are quite a lot of these (and infinitely many are possible) - and you need to know which applies in the particular case in order to do the conversion, since a different encoding may map the same bytes to a different string. For example, the same byte string can represent 2 different strings in 2 different encodings.
>>> b'\xcf\x84o\xcf\x81\xce\xbdo\xcf\x82'.decode('utf-16')
'θαα
©ααα
‘α΄ζΎ½θ'
>>> b'\xcf\x84o\xcf\x81\xce\xbdo\xcf\x82'.decode('utf-8')
'ΟoΟΞ½oΟ'
Once you know which encoding to use, you can use the .decode() method of the byte string to get the right character string from it. The .encode() method of a character string goes the opposite way and encodes the character string as a byte string.
|
[
{
"code": null,
"e": 1609,
"s": 1062,
"text": "A string is a sequence of characters; these are an abstract concept, and can't be directly stored on disk. A byte string is a sequence of bytes - things that can be stored on disk. The mapping between them is an encoding - there are quite a lot of these (and infinitely many are possible) - and you need to know which applies in the particular case in order to do the conversion, since a different encoding may map the same bytes to a different string. For example, the same byte string can represent 2 different strings in 2 different encodings."
},
{
"code": null,
"e": 1747,
"s": 1609,
"text": ">>> b'\\xcf\\x84o\\xcf\\x81\\xce\\xbdo\\xcf\\x82'.decode('utf-16')\n'θαα
©ααα
‘α΄ζΎ½θ'\n>>> b'\\xcf\\x84o\\xcf\\x81\\xce\\xbdo\\xcf\\x82'.decode('utf-8')\n'ΟoΟΞ½oΟ'"
},
{
"code": null,
"e": 1995,
"s": 1747,
"text": "Once you know which encoding to use, you can use the .decode() method of the byte string to get the right character string from it. The .encode() method of a character string goes the opposite way and encodes the character string as a byte string."
}
] |
Change the position and the appearance of a graph legend in R - GeeksforGeeks
|
10 Jun, 2021
Legends are useful to add more information to the plots and enhance the user readability. It involves the creation of titles, indexes, placement of plot boxes in order to create a better understanding of the graphs plotted. The in-built R function legend() can be used to add a legend to the plot. Scatter, line and block plots are available for easy visualization of data in R. In this article, change the position and the appearance of a graph legend in R
Syntax: legend(x, y, legend)
Arguments :
x and y : the x and y co-ordinates to be used to position the legend. It can also take string as an argument, like topright, bottomleft and so on..
legend : vector giving info about each class plotted in the graph
Example 1: Changing the Position of the legend
Integer values can be assigned to both x and y coordinates and the legend box is aligned directly with these coordinates. It is necessary to provide both the coordinates in this case.
Code:
R
# declaring the data to plot# x coordinate is a vector of# integers from 1 to 10x <- 1 : 10y = x^1/2z = x^2 # plotting x and y coordinate lineplot(x, y, col = "blue") # adding another line on# the coordinates involving y and zlines(z, y ,col = "red") # Adding a legend to the graph#defining the lineslegend(2, 4, legend=c("Equation 1", "Equation 2"), fill = c("blue","red"))
Output:
Example 2: Placement of legend with alignment justified.
The x coordinate may even contain a string with the position justified. The string is a combination of keywords, the plausible values of which are defined as bottomright, bottom, bottomleft, left, topleft, top, topright, right, center. This scenario eliminates the need of defining the value for y co-ordinate.
Code:
R
# declaring the data to plot# x coordinate is a vector of# integers from 1 to 10 x <- 1 : 10y = x^1/2z = x^2 # plotting x and y coordinate# lineplot(x, y, col = "blue") # adding another line on the# coordinates involving y and zlines(z, y , col = "red") # Adding a legend to the graph# defining the lineslegend(x = "topleft", legend=c( "Equation 1", "Equation 2"), fill = c("blue","red"))
Output
Example 3: Leaving margin along with alignment justification
In case, we specify the position argument in the form of keywords, the legend box appears connected to the corresponding axes. To resolve this, the inset argument can be defined within this method. This argument specifies the distance from the margin as a fraction of the plot region.
Code:
R
# declaring the data to plot# x coordinate is a vector of# integers from 1 to 10x <- 1:10y = x^1/2z = x^2 # plotting x and y coordinate lineplot(x, y, col = "blue") # adding another line on the# coordinates involving y and zlines(z, y ,col = "red") # Adding a legend to the graph# defining the lineslegend(x="topleft", legend=c( "Equation 1", "Equation 2"), fill = c("blue","red"), inset = 0.05)
Output:
Example 4: Color appearance of the legend
The legend box in the graph can be customized to suit the requirements in order to convey more information and offer better visually. The following arguments can be used to customize the arguments.
title: The title of the legend box that can be declared to understand what the index of the indicates
bty (Default : o) : The type of box to enclose the legend . Different types of letters can be used, where the box shape is equivalent to the letter shape. For instance, βnβ can be used for no box.
bg: A background colour can be assigned to the legend box
box.lwd : Indicator of the line width of the legend box
box.lty : Indicator of the line type of the legend box
box.col : Indicator of the line color of the legend box
Code:
R
# declaring the data to plot# x coordinate is a vector of# integers from 1 to 10x <- 1:10y = x^1/2z = x^2 # plotting x and y coordinate lineplot(x, y, col = "blue") # adding another line on the# coordinates involving y and zlines(z, y , col = "red") # Adding a legend to the graph# defining the lineslegend(x = "topleft", box.col = "brown", bg ="yellow", box.lwd = 2 , title="EQUATIONS", legend=c("Equation 1", "Equation 2"), fill = c("blue","red"))
Output:
sumitgumber28
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
R - if statement
How to filter R dataframe by multiple conditions?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
|
[
{
"code": null,
"e": 26597,
"s": 26569,
"text": "\n10 Jun, 2021"
},
{
"code": null,
"e": 27055,
"s": 26597,
"text": "Legends are useful to add more information to the plots and enhance the user readability. It involves the creation of titles, indexes, placement of plot boxes in order to create a better understanding of the graphs plotted. The in-built R function legend() can be used to add a legend to the plot. Scatter, line and block plots are available for easy visualization of data in R. In this article, change the position and the appearance of a graph legend in R"
},
{
"code": null,
"e": 27084,
"s": 27055,
"text": "Syntax: legend(x, y, legend)"
},
{
"code": null,
"e": 27096,
"s": 27084,
"text": "Arguments :"
},
{
"code": null,
"e": 27244,
"s": 27096,
"text": "x and y : the x and y co-ordinates to be used to position the legend. It can also take string as an argument, like topright, bottomleft and so on.."
},
{
"code": null,
"e": 27310,
"s": 27244,
"text": "legend : vector giving info about each class plotted in the graph"
},
{
"code": null,
"e": 27358,
"s": 27310,
"text": "Example 1: Changing the Position of the legend "
},
{
"code": null,
"e": 27543,
"s": 27358,
"text": "Integer values can be assigned to both x and y coordinates and the legend box is aligned directly with these coordinates. It is necessary to provide both the coordinates in this case. "
},
{
"code": null,
"e": 27549,
"s": 27543,
"text": "Code:"
},
{
"code": null,
"e": 27551,
"s": 27549,
"text": "R"
},
{
"code": "# declaring the data to plot# x coordinate is a vector of# integers from 1 to 10x <- 1 : 10y = x^1/2z = x^2 # plotting x and y coordinate lineplot(x, y, col = \"blue\") # adding another line on# the coordinates involving y and zlines(z, y ,col = \"red\") # Adding a legend to the graph#defining the lineslegend(2, 4, legend=c(\"Equation 1\", \"Equation 2\"), fill = c(\"blue\",\"red\"))",
"e": 27933,
"s": 27551,
"text": null
},
{
"code": null,
"e": 27941,
"s": 27933,
"text": "Output:"
},
{
"code": null,
"e": 27998,
"s": 27941,
"text": "Example 2: Placement of legend with alignment justified."
},
{
"code": null,
"e": 28310,
"s": 27998,
"text": "The x coordinate may even contain a string with the position justified. The string is a combination of keywords, the plausible values of which are defined as bottomright, bottom, bottomleft, left, topleft, top, topright, right, center. This scenario eliminates the need of defining the value for y co-ordinate. "
},
{
"code": null,
"e": 28316,
"s": 28310,
"text": "Code:"
},
{
"code": null,
"e": 28318,
"s": 28316,
"text": "R"
},
{
"code": "# declaring the data to plot# x coordinate is a vector of# integers from 1 to 10 x <- 1 : 10y = x^1/2z = x^2 # plotting x and y coordinate# lineplot(x, y, col = \"blue\") # adding another line on the# coordinates involving y and zlines(z, y , col = \"red\") # Adding a legend to the graph# defining the lineslegend(x = \"topleft\", legend=c( \"Equation 1\", \"Equation 2\"), fill = c(\"blue\",\"red\"))",
"e": 28715,
"s": 28318,
"text": null
},
{
"code": null,
"e": 28722,
"s": 28715,
"text": "Output"
},
{
"code": null,
"e": 28783,
"s": 28722,
"text": "Example 3: Leaving margin along with alignment justification"
},
{
"code": null,
"e": 29068,
"s": 28783,
"text": "In case, we specify the position argument in the form of keywords, the legend box appears connected to the corresponding axes. To resolve this, the inset argument can be defined within this method. This argument specifies the distance from the margin as a fraction of the plot region."
},
{
"code": null,
"e": 29074,
"s": 29068,
"text": "Code:"
},
{
"code": null,
"e": 29076,
"s": 29074,
"text": "R"
},
{
"code": "# declaring the data to plot# x coordinate is a vector of# integers from 1 to 10x <- 1:10y = x^1/2z = x^2 # plotting x and y coordinate lineplot(x, y, col = \"blue\") # adding another line on the# coordinates involving y and zlines(z, y ,col = \"red\") # Adding a legend to the graph# defining the lineslegend(x=\"topleft\", legend=c( \"Equation 1\", \"Equation 2\"), fill = c(\"blue\",\"red\"), inset = 0.05)",
"e": 29480,
"s": 29076,
"text": null
},
{
"code": null,
"e": 29488,
"s": 29480,
"text": "Output:"
},
{
"code": null,
"e": 29531,
"s": 29488,
"text": "Example 4: Color appearance of the legend "
},
{
"code": null,
"e": 29729,
"s": 29531,
"text": "The legend box in the graph can be customized to suit the requirements in order to convey more information and offer better visually. The following arguments can be used to customize the arguments."
},
{
"code": null,
"e": 29831,
"s": 29729,
"text": "title: The title of the legend box that can be declared to understand what the index of the indicates"
},
{
"code": null,
"e": 30028,
"s": 29831,
"text": "bty (Default : o) : The type of box to enclose the legend . Different types of letters can be used, where the box shape is equivalent to the letter shape. For instance, βnβ can be used for no box."
},
{
"code": null,
"e": 30086,
"s": 30028,
"text": "bg: A background colour can be assigned to the legend box"
},
{
"code": null,
"e": 30142,
"s": 30086,
"text": "box.lwd : Indicator of the line width of the legend box"
},
{
"code": null,
"e": 30197,
"s": 30142,
"text": "box.lty : Indicator of the line type of the legend box"
},
{
"code": null,
"e": 30253,
"s": 30197,
"text": "box.col : Indicator of the line color of the legend box"
},
{
"code": null,
"e": 30259,
"s": 30253,
"text": "Code:"
},
{
"code": null,
"e": 30261,
"s": 30259,
"text": "R"
},
{
"code": "# declaring the data to plot# x coordinate is a vector of# integers from 1 to 10x <- 1:10y = x^1/2z = x^2 # plotting x and y coordinate lineplot(x, y, col = \"blue\") # adding another line on the# coordinates involving y and zlines(z, y , col = \"red\") # Adding a legend to the graph# defining the lineslegend(x = \"topleft\", box.col = \"brown\", bg =\"yellow\", box.lwd = 2 , title=\"EQUATIONS\", legend=c(\"Equation 1\", \"Equation 2\"), fill = c(\"blue\",\"red\"))",
"e": 30729,
"s": 30261,
"text": null
},
{
"code": null,
"e": 30737,
"s": 30729,
"text": "Output:"
},
{
"code": null,
"e": 30751,
"s": 30737,
"text": "sumitgumber28"
},
{
"code": null,
"e": 30758,
"s": 30751,
"text": "Picked"
},
{
"code": null,
"e": 30767,
"s": 30758,
"text": "R-Charts"
},
{
"code": null,
"e": 30776,
"s": 30767,
"text": "R-Graphs"
},
{
"code": null,
"e": 30784,
"s": 30776,
"text": "R-plots"
},
{
"code": null,
"e": 30795,
"s": 30784,
"text": "R Language"
},
{
"code": null,
"e": 30893,
"s": 30795,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30945,
"s": 30893,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 30980,
"s": 30945,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 31038,
"s": 30980,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 31076,
"s": 31038,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 31119,
"s": 31076,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 31136,
"s": 31119,
"text": "R - if statement"
},
{
"code": null,
"e": 31186,
"s": 31136,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 31235,
"s": 31186,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 31272,
"s": 31235,
"text": "How to import an Excel File into R ?"
}
] |
PostgreSQL - SUM Function
|
PostgreSQL SUM function is used to find out the sum of a field in various records.
To understand the SUM function consider the table COMPANY having records as follows β
testdb# select * from COMPANY;
id | name | age | address | salary
----+-------+-----+-----------+--------
1 | Paul | 32 | California| 20000
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
6 | Kim | 22 | South-Hall| 45000
7 | James | 24 | Houston | 10000
(7 rows)
Now, based on the above table, suppose you want to calculate the total of all the salary, then you can do so by using the following command β
testdb# SELECT SUM(salary) FROM company;
The above given PostgreSQL statement will produce the following result β
sum
--------
260000
(1 row)
You can take the sum of various records set using the GROUP BY clause. The following example will sum up all the records related to a single person and you will have salary for each person.
testdb# SELECT name, SUM(salary) FROM company GROUP BY name;
The above given PostgreSQL statement will produce the following result β
name | sum
-------+-------
Teddy | 20000
Paul | 20000
Mark | 65000
David | 85000
Allen | 15000
Kim | 45000
James | 10000
(7 rows)
23 Lectures
1.5 hours
John Elder
49 Lectures
3.5 hours
Niyazi Erdogan
126 Lectures
10.5 hours
Abhishek And Pukhraj
35 Lectures
5 hours
Karthikeya T
5 Lectures
51 mins
Vinay Kumar
5 Lectures
52 mins
Vinay Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2908,
"s": 2825,
"text": "PostgreSQL SUM function is used to find out the sum of a field in various records."
},
{
"code": null,
"e": 2994,
"s": 2908,
"text": "To understand the SUM function consider the table COMPANY having records as follows β"
},
{
"code": null,
"e": 3386,
"s": 2994,
"text": "testdb# select * from COMPANY;\n id | name | age | address | salary\n----+-------+-----+-----------+--------\n 1 | Paul | 32 | California| 20000\n 2 | Allen | 25 | Texas | 15000\n 3 | Teddy | 23 | Norway | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n 5 | David | 27 | Texas | 85000\n 6 | Kim | 22 | South-Hall| 45000\n 7 | James | 24 | Houston | 10000\n(7 rows)"
},
{
"code": null,
"e": 3528,
"s": 3386,
"text": "Now, based on the above table, suppose you want to calculate the total of all the salary, then you can do so by using the following command β"
},
{
"code": null,
"e": 3569,
"s": 3528,
"text": "testdb# SELECT SUM(salary) FROM company;"
},
{
"code": null,
"e": 3642,
"s": 3569,
"text": "The above given PostgreSQL statement will produce the following result β"
},
{
"code": null,
"e": 3674,
"s": 3642,
"text": " sum\n--------\n 260000\n(1 row)\n"
},
{
"code": null,
"e": 3864,
"s": 3674,
"text": "You can take the sum of various records set using the GROUP BY clause. The following example will sum up all the records related to a single person and you will have salary for each person."
},
{
"code": null,
"e": 3925,
"s": 3864,
"text": "testdb# SELECT name, SUM(salary) FROM company GROUP BY name;"
},
{
"code": null,
"e": 3998,
"s": 3925,
"text": "The above given PostgreSQL statement will produce the following result β"
},
{
"code": null,
"e": 4143,
"s": 3998,
"text": " name | sum\n-------+-------\n Teddy | 20000\n Paul | 20000\n Mark | 65000\n David | 85000\n Allen | 15000\n Kim | 45000\n James | 10000\n(7 rows)\n"
},
{
"code": null,
"e": 4178,
"s": 4143,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4190,
"s": 4178,
"text": " John Elder"
},
{
"code": null,
"e": 4225,
"s": 4190,
"text": "\n 49 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4241,
"s": 4225,
"text": " Niyazi Erdogan"
},
{
"code": null,
"e": 4278,
"s": 4241,
"text": "\n 126 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 4300,
"s": 4278,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 4333,
"s": 4300,
"text": "\n 35 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4347,
"s": 4333,
"text": " Karthikeya T"
},
{
"code": null,
"e": 4378,
"s": 4347,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 4391,
"s": 4378,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 4422,
"s": 4391,
"text": "\n 5 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 4435,
"s": 4422,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 4442,
"s": 4435,
"text": " Print"
},
{
"code": null,
"e": 4453,
"s": 4442,
"text": " Add Notes"
}
] |
Introduction To Grammar in Theory of Computation - GeeksforGeeks
|
18 Oct, 2021
Prerequisite β Theory of Computation
Grammar :It is a finite set of formal rules for generating syntactically correct sentences or meaningful correct sentences.
Constitute Of Grammar :Grammar is basically composed of two basic elements β
Terminal Symbols βTerminal symbols are those which are the components of the sentences generated using a grammar and are represented using small case letter like a, b, c etc.Non-Terminal Symbols βNon-Terminal Symbols are those symbols which take part in the generation of the sentence but are not the component of the sentence. Non-Terminal Symbols are also called Auxiliary Symbols and Variables. These symbols are represented using a capital letter like A, B, C, etc.
Terminal Symbols βTerminal symbols are those which are the components of the sentences generated using a grammar and are represented using small case letter like a, b, c etc.
Non-Terminal Symbols βNon-Terminal Symbols are those symbols which take part in the generation of the sentence but are not the component of the sentence. Non-Terminal Symbols are also called Auxiliary Symbols and Variables. These symbols are represented using a capital letter like A, B, C, etc.
Formal Definition of Grammar :Any Grammar can be represented by 4 tuples β <N, T, P, S>
N β Finite Non-Empty Set of Non-Terminal Symbols.
T β Finite Set of Terminal Symbols.
P β Finite Non-Empty Set of Production Rules.
S β Start Symbol (Symbol from where we start producing our sentences or strings).
Production Rules :A production or production rule in computer science is a rewrite rule specifying a symbol substitution that can be recursively performed to generate new symbol sequences. It is of the form Ξ±-> Ξ² where Ξ± is a Non-Terminal Symbol which can be replaced by Ξ² which is a string of Terminal Symbols or Non-Terminal Symbols.
Example-1 :Consider Grammar G1 = <N, T, P, S>
T = {a,b} #Set of terminal symbols
P = {A->Aa,A->Ab,A->a,A->b,A-> } #Set of all production rules
S = {A} #Start Symbol
As the start symbol is S then we can produce Aa, Ab, a,b,which can further produce strings where A can be replaced by the Strings mentioned in the production rules and hence this grammar can be used to produce strings of the form (a+b)*.
Derivation Of Strings :
A->a #using production rule 3
OR
A->Aa #using production rule 1
Aa->ba #using production rule 4
OR
A->Aa #using production rule 1
Aa->AAa #using production rule 1
AAa->bAa #using production rule 4
bAa->ba #using production rule 5
Example-2 :Consider Grammar G2 = <N, T, P, S>
N = {A} #Set of non-terminals Symbols
T = {a} #Set of terminal symbols
P = {A->Aa, A->AAa, A->a, A->} #Set of all production rules
S = {A} #Start Symbol
As the start symbol is S then we can produce Aa, AAa, a,which can further produce strings where A can be replaced by the Strings mentioned in the production rules and hence this grammar can be used to produce strings of form (a)*.
Derivation Of Strings :
A->a #using production rule 3
OR
A->Aa #using production rule 1
Aa->aa #using production rule 3
OR
A->Aa #using production rule 1
Aa->AAa #using production rule 1
AAa->Aa #using production rule 4
Aa->aa #using production rule 3
Equivalent Grammars :Grammars are said to be equivalent id they produce the same language.
Different Types Of Grammars :Grammar can be divided on basis of β
Type of Production Rules
Number of Derivation Trees
Number of Strings
sahilrawat680
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Clustered and Non-clustered index
Phases of a Compiler
Preemptive and Non-Preemptive Scheduling
Differences between IPv4 and IPv6
Introduction of Process Synchronization
Difference between DFA and NFA
Introduction of Finite Automata
Regular Expressions, Regular Grammar and Regular Languages
Conversion from NFA to DFA
Pumping Lemma in Theory of Computation
|
[
{
"code": null,
"e": 23987,
"s": 23959,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 24024,
"s": 23987,
"text": "Prerequisite β Theory of Computation"
},
{
"code": null,
"e": 24148,
"s": 24024,
"text": "Grammar :It is a finite set of formal rules for generating syntactically correct sentences or meaningful correct sentences."
},
{
"code": null,
"e": 24225,
"s": 24148,
"text": "Constitute Of Grammar :Grammar is basically composed of two basic elements β"
},
{
"code": null,
"e": 24695,
"s": 24225,
"text": "Terminal Symbols βTerminal symbols are those which are the components of the sentences generated using a grammar and are represented using small case letter like a, b, c etc.Non-Terminal Symbols βNon-Terminal Symbols are those symbols which take part in the generation of the sentence but are not the component of the sentence. Non-Terminal Symbols are also called Auxiliary Symbols and Variables. These symbols are represented using a capital letter like A, B, C, etc."
},
{
"code": null,
"e": 24870,
"s": 24695,
"text": "Terminal Symbols βTerminal symbols are those which are the components of the sentences generated using a grammar and are represented using small case letter like a, b, c etc."
},
{
"code": null,
"e": 25166,
"s": 24870,
"text": "Non-Terminal Symbols βNon-Terminal Symbols are those symbols which take part in the generation of the sentence but are not the component of the sentence. Non-Terminal Symbols are also called Auxiliary Symbols and Variables. These symbols are represented using a capital letter like A, B, C, etc."
},
{
"code": null,
"e": 25254,
"s": 25166,
"text": "Formal Definition of Grammar :Any Grammar can be represented by 4 tuples β <N, T, P, S>"
},
{
"code": null,
"e": 25304,
"s": 25254,
"text": "N β Finite Non-Empty Set of Non-Terminal Symbols."
},
{
"code": null,
"e": 25340,
"s": 25304,
"text": "T β Finite Set of Terminal Symbols."
},
{
"code": null,
"e": 25386,
"s": 25340,
"text": "P β Finite Non-Empty Set of Production Rules."
},
{
"code": null,
"e": 25468,
"s": 25386,
"text": "S β Start Symbol (Symbol from where we start producing our sentences or strings)."
},
{
"code": null,
"e": 25806,
"s": 25468,
"text": "Production Rules :A production or production rule in computer science is a rewrite rule specifying a symbol substitution that can be recursively performed to generate new symbol sequences. It is of the form Ξ±-> Ξ² where Ξ± is a Non-Terminal Symbol which can be replaced by Ξ² which is a string of Terminal Symbols or Non-Terminal Symbols."
},
{
"code": null,
"e": 25852,
"s": 25806,
"text": "Example-1 :Consider Grammar G1 = <N, T, P, S>"
},
{
"code": null,
"e": 25981,
"s": 25852,
"text": "T = {a,b} #Set of terminal symbols\nP = {A->Aa,A->Ab,A->a,A->b,A-> } #Set of all production rules\n\nS = {A} #Start Symbol"
},
{
"code": null,
"e": 26219,
"s": 25981,
"text": "As the start symbol is S then we can produce Aa, Ab, a,b,which can further produce strings where A can be replaced by the Strings mentioned in the production rules and hence this grammar can be used to produce strings of the form (a+b)*."
},
{
"code": null,
"e": 26243,
"s": 26219,
"text": "Derivation Of Strings :"
},
{
"code": null,
"e": 26494,
"s": 26243,
"text": "A->a #using production rule 3\nOR\nA->Aa #using production rule 1\nAa->ba #using production rule 4\nOR\nA->Aa #using production rule 1\nAa->AAa #using production rule 1\nAAa->bAa #using production rule 4\nbAa->ba #using production rule 5"
},
{
"code": null,
"e": 26540,
"s": 26494,
"text": "Example-2 :Consider Grammar G2 = <N, T, P, S>"
},
{
"code": null,
"e": 26704,
"s": 26540,
"text": "N = {A} #Set of non-terminals Symbols\nT = {a} #Set of terminal symbols\nP = {A->Aa, A->AAa, A->a, A->} #Set of all production rules\n\nS = {A} #Start Symbol"
},
{
"code": null,
"e": 26935,
"s": 26704,
"text": "As the start symbol is S then we can produce Aa, AAa, a,which can further produce strings where A can be replaced by the Strings mentioned in the production rules and hence this grammar can be used to produce strings of form (a)*."
},
{
"code": null,
"e": 26959,
"s": 26935,
"text": "Derivation Of Strings :"
},
{
"code": null,
"e": 27208,
"s": 26959,
"text": "A->a #using production rule 3\nOR\nA->Aa #using production rule 1\nAa->aa #using production rule 3\nOR\nA->Aa #using production rule 1\nAa->AAa #using production rule 1\nAAa->Aa #using production rule 4\nAa->aa #using production rule 3"
},
{
"code": null,
"e": 27299,
"s": 27208,
"text": "Equivalent Grammars :Grammars are said to be equivalent id they produce the same language."
},
{
"code": null,
"e": 27365,
"s": 27299,
"text": "Different Types Of Grammars :Grammar can be divided on basis of β"
},
{
"code": null,
"e": 27390,
"s": 27365,
"text": "Type of Production Rules"
},
{
"code": null,
"e": 27417,
"s": 27390,
"text": "Number of Derivation Trees"
},
{
"code": null,
"e": 27435,
"s": 27417,
"text": "Number of Strings"
},
{
"code": null,
"e": 27449,
"s": 27435,
"text": "sahilrawat680"
},
{
"code": null,
"e": 27457,
"s": 27449,
"text": "GATE CS"
},
{
"code": null,
"e": 27490,
"s": 27457,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 27588,
"s": 27490,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27597,
"s": 27588,
"text": "Comments"
},
{
"code": null,
"e": 27610,
"s": 27597,
"text": "Old Comments"
},
{
"code": null,
"e": 27663,
"s": 27610,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 27684,
"s": 27663,
"text": "Phases of a Compiler"
},
{
"code": null,
"e": 27725,
"s": 27684,
"text": "Preemptive and Non-Preemptive Scheduling"
},
{
"code": null,
"e": 27759,
"s": 27725,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 27799,
"s": 27759,
"text": "Introduction of Process Synchronization"
},
{
"code": null,
"e": 27830,
"s": 27799,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 27862,
"s": 27830,
"text": "Introduction of Finite Automata"
},
{
"code": null,
"e": 27921,
"s": 27862,
"text": "Regular Expressions, Regular Grammar and Regular Languages"
},
{
"code": null,
"e": 27948,
"s": 27921,
"text": "Conversion from NFA to DFA"
}
] |
Python program to find all duplicate characters in a string
|
In this tutorial, we are going to learn how to find all duplicate values in a string. We can do it in different ways in Python. Let's explore them one by one.
The aim of the program we are going to write is to find the duplicate characters present in a string. For example, we have a string tutorialspoint the program will give us t o i as output. In simple words, we have to find characters whose count is greater than one in the string. Let's see.
Writing programs without using any modules. We can use different methods of Python to achieve our goal. First, we will find the duplicate characters of a string using the count method. Let's see the procedure first.
Initialize a string.
Initialize an empty list
Loop over the string.Check whether the char frequency is greater than one or not using the count method.
Check whether the char frequency is greater than one or not using the count method.
If greater than one check whether it's present in the list or not.
If not present append to the list
Print the characters
## initializing string
string = "tutorialspoint"
## initializing a list to append all the duplicate characters
duplicates = []
for char in string:
## checking whether the character have a duplicate or not
## str.count(char) returns the frequency of a char in the str
if string.count(char) > 1:
## appending to the list if it's already not present
if char not in duplicates:
duplicates.append(char)
print(*duplicates)
If you run the above program, you will get the following results.
t o i
Now we will find the duplicate characters of string without any methods. We are going to use the dictionary data structure to get the desired output. Let's see the procedure first.
Initialize a string.
Initialize an empty dictionary
Loop over the string.Check whether the char is already present in the dictionary or notInitialize the count of the char to 1
Check whether the char is already present in the dictionary or not
Initialize the count of the char to 1
Increase the count
## initializing string
string = "tutorialspoint"
## initializing a dictionary
duplicates = {}
for char in string:
## checking whether the char is already present in dictionary or not
if char in duplicates:
## increasing count if present
duplicates[char] += 1
else:
## initializing count to 1 if not present
duplicates[char] = 1
for key, value in duplicates.items():
if value > 1:
print(key, end = " ")
print()
If you run the above program,
t o i
|
[
{
"code": null,
"e": 1221,
"s": 1062,
"text": "In this tutorial, we are going to learn how to find all duplicate values in a string. We can do it in different ways in Python. Let's explore them one by one."
},
{
"code": null,
"e": 1512,
"s": 1221,
"text": "The aim of the program we are going to write is to find the duplicate characters present in a string. For example, we have a string tutorialspoint the program will give us t o i as output. In simple words, we have to find characters whose count is greater than one in the string. Let's see."
},
{
"code": null,
"e": 1728,
"s": 1512,
"text": "Writing programs without using any modules. We can use different methods of Python to achieve our goal. First, we will find the duplicate characters of a string using the count method. Let's see the procedure first."
},
{
"code": null,
"e": 1749,
"s": 1728,
"text": "Initialize a string."
},
{
"code": null,
"e": 1774,
"s": 1749,
"text": "Initialize an empty list"
},
{
"code": null,
"e": 1879,
"s": 1774,
"text": "Loop over the string.Check whether the char frequency is greater than one or not using the count method."
},
{
"code": null,
"e": 1963,
"s": 1879,
"text": "Check whether the char frequency is greater than one or not using the count method."
},
{
"code": null,
"e": 2064,
"s": 1963,
"text": "If greater than one check whether it's present in the list or not.\nIf not present append to the list"
},
{
"code": null,
"e": 2085,
"s": 2064,
"text": "Print the characters"
},
{
"code": null,
"e": 2520,
"s": 2085,
"text": "## initializing string\nstring = \"tutorialspoint\"\n## initializing a list to append all the duplicate characters\nduplicates = []\nfor char in string:\n ## checking whether the character have a duplicate or not\n ## str.count(char) returns the frequency of a char in the str\n if string.count(char) > 1:\n ## appending to the list if it's already not present\n if char not in duplicates:\n duplicates.append(char)\nprint(*duplicates)"
},
{
"code": null,
"e": 2586,
"s": 2520,
"text": "If you run the above program, you will get the following results."
},
{
"code": null,
"e": 2592,
"s": 2586,
"text": "t o i"
},
{
"code": null,
"e": 2773,
"s": 2592,
"text": "Now we will find the duplicate characters of string without any methods. We are going to use the dictionary data structure to get the desired output. Let's see the procedure first."
},
{
"code": null,
"e": 2794,
"s": 2773,
"text": "Initialize a string."
},
{
"code": null,
"e": 2825,
"s": 2794,
"text": "Initialize an empty dictionary"
},
{
"code": null,
"e": 2950,
"s": 2825,
"text": "Loop over the string.Check whether the char is already present in the dictionary or notInitialize the count of the char to 1"
},
{
"code": null,
"e": 3017,
"s": 2950,
"text": "Check whether the char is already present in the dictionary or not"
},
{
"code": null,
"e": 3055,
"s": 3017,
"text": "Initialize the count of the char to 1"
},
{
"code": null,
"e": 3074,
"s": 3055,
"text": "Increase the count"
},
{
"code": null,
"e": 3526,
"s": 3074,
"text": "## initializing string\nstring = \"tutorialspoint\"\n## initializing a dictionary\nduplicates = {}\nfor char in string:\n ## checking whether the char is already present in dictionary or not\n if char in duplicates:\n ## increasing count if present\n duplicates[char] += 1\n else:\n ## initializing count to 1 if not present\n duplicates[char] = 1\nfor key, value in duplicates.items():\n if value > 1:\n print(key, end = \" \")\nprint()"
},
{
"code": null,
"e": 3556,
"s": 3526,
"text": "If you run the above program,"
},
{
"code": null,
"e": 3562,
"s": 3556,
"text": "t o i"
}
] |
Java Concurrency - AtomicBoolean Class
|
A java.util.concurrent.atomic.AtomicBoolean class provides operations on underlying boolean value that can be read and written atomically, and also contains advanced atomic operations. AtomicBoolean supports atomic operations on underlying boolean variable. It have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features.
Following is the list of important methods available in the AtomicBoolean class.
public boolean compareAndSet(boolean expect, boolean update)
Atomically sets the value to the given updated value if the current value == the expected value.
public boolean get()
Returns the current value.
public boolean getAndSet(boolean newValue)
Atomically sets to the given value and returns the previous value.
public void lazySet(boolean newValue)
Eventually sets to the given value.
public void set(boolean newValue)
Unconditionally sets to the given value.
public String toString()
Returns the String representation of the current value.
public boolean weakCompareAndSet(boolean expect, boolean update)
Atomically sets the value to the given updated value if the current value == the expected value.
The following TestThread program shows usage of AtomicBoolean variable in thread based environment.
import java.util.concurrent.atomic.AtomicBoolean;
public class TestThread {
public static void main(final String[] arguments) throws InterruptedException {
final AtomicBoolean atomicBoolean = new AtomicBoolean(false);
new Thread("Thread 1") {
public void run() {
while(true) {
System.out.println(Thread.currentThread().getName()
+" Waiting for Thread 2 to set Atomic variable to true. Current value is "
+ atomicBoolean.get());
if(atomicBoolean.compareAndSet(true, false)) {
System.out.println("Done!");
break;
}
}
};
}.start();
new Thread("Thread 2") {
public void run() {
System.out.println(Thread.currentThread().getName() +
", Atomic Variable: " +atomicBoolean.get());
System.out.println(Thread.currentThread().getName() +
" is setting the variable to true ");
atomicBoolean.set(true);
System.out.println(Thread.currentThread().getName() +
", Atomic Variable: " +atomicBoolean.get());
};
}.start();
}
}
This will produce the following result.
Thread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false
Thread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false
Thread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false
Thread 2, Atomic Variable: false
Thread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false
Thread 2 is setting the variable to true
Thread 2, Atomic Variable: true
Thread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false
Done!
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3169,
"s": 2657,
"text": "A java.util.concurrent.atomic.AtomicBoolean class provides operations on underlying boolean value that can be read and written atomically, and also contains advanced atomic operations. AtomicBoolean supports atomic operations on underlying boolean variable. It have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features."
},
{
"code": null,
"e": 3250,
"s": 3169,
"text": "Following is the list of important methods available in the AtomicBoolean class."
},
{
"code": null,
"e": 3311,
"s": 3250,
"text": "public boolean compareAndSet(boolean expect, boolean update)"
},
{
"code": null,
"e": 3408,
"s": 3311,
"text": "Atomically sets the value to the given updated value if the current value == the expected value."
},
{
"code": null,
"e": 3429,
"s": 3408,
"text": "public boolean get()"
},
{
"code": null,
"e": 3456,
"s": 3429,
"text": "Returns the current value."
},
{
"code": null,
"e": 3499,
"s": 3456,
"text": "public boolean getAndSet(boolean newValue)"
},
{
"code": null,
"e": 3566,
"s": 3499,
"text": "Atomically sets to the given value and returns the previous value."
},
{
"code": null,
"e": 3604,
"s": 3566,
"text": "public void lazySet(boolean newValue)"
},
{
"code": null,
"e": 3640,
"s": 3604,
"text": "Eventually sets to the given value."
},
{
"code": null,
"e": 3674,
"s": 3640,
"text": "public void set(boolean newValue)"
},
{
"code": null,
"e": 3715,
"s": 3674,
"text": "Unconditionally sets to the given value."
},
{
"code": null,
"e": 3740,
"s": 3715,
"text": "public String\ttoString()"
},
{
"code": null,
"e": 3796,
"s": 3740,
"text": "Returns the String representation of the current value."
},
{
"code": null,
"e": 3861,
"s": 3796,
"text": "public boolean weakCompareAndSet(boolean expect, boolean update)"
},
{
"code": null,
"e": 3958,
"s": 3861,
"text": "Atomically sets the value to the given updated value if the current value == the expected value."
},
{
"code": null,
"e": 4058,
"s": 3958,
"text": "The following TestThread program shows usage of AtomicBoolean variable in thread based environment."
},
{
"code": null,
"e": 5282,
"s": 4058,
"text": "import java.util.concurrent.atomic.AtomicBoolean;\n\npublic class TestThread {\n\n public static void main(final String[] arguments) throws InterruptedException {\n final AtomicBoolean atomicBoolean = new AtomicBoolean(false);\n\n new Thread(\"Thread 1\") {\n\n public void run() {\n\n while(true) {\n System.out.println(Thread.currentThread().getName() \n +\" Waiting for Thread 2 to set Atomic variable to true. Current value is \"\n + atomicBoolean.get());\n\n if(atomicBoolean.compareAndSet(true, false)) {\n System.out.println(\"Done!\");\n break;\n }\n }\n };\n }.start();\n\n new Thread(\"Thread 2\") {\n\n public void run() {\n System.out.println(Thread.currentThread().getName() +\n \", Atomic Variable: \" +atomicBoolean.get()); \n System.out.println(Thread.currentThread().getName() +\n \" is setting the variable to true \");\n atomicBoolean.set(true);\n System.out.println(Thread.currentThread().getName() +\n \", Atomic Variable: \" +atomicBoolean.get()); \n };\n }.start();\n }\n}"
},
{
"code": null,
"e": 5322,
"s": 5282,
"text": "This will produce the following result."
},
{
"code": null,
"e": 5860,
"s": 5322,
"text": "Thread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false\nThread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false\nThread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false\nThread 2, Atomic Variable: false\nThread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false\nThread 2 is setting the variable to true\nThread 2, Atomic Variable: true\nThread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false\nDone!\n"
},
{
"code": null,
"e": 5893,
"s": 5860,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5909,
"s": 5893,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5942,
"s": 5909,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5958,
"s": 5942,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5993,
"s": 5958,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6007,
"s": 5993,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6041,
"s": 6007,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6055,
"s": 6041,
"text": " Tushar Kale"
},
{
"code": null,
"e": 6092,
"s": 6055,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6107,
"s": 6092,
"text": " Monica Mittal"
},
{
"code": null,
"e": 6140,
"s": 6107,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6159,
"s": 6140,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6166,
"s": 6159,
"text": " Print"
},
{
"code": null,
"e": 6177,
"s": 6166,
"text": " Add Notes"
}
] |
VBA - Constants
|
Constant is a named memory location used to hold a value that CANNOT be changed during the script execution. If a user tries to change a Constant value, the script execution ends up with an error. Constants are declared the same way the variables are declared.
Following are the rules for naming a constant.
You must use a letter as the first character.
You must use a letter as the first character.
You can't use a space, period (.), exclamation mark (!), or the characters @, &, $, # in the name.
You can't use a space, period (.), exclamation mark (!), or the characters @, &, $, # in the name.
Name can't exceed 255 characters in length.
Name can't exceed 255 characters in length.
You cannot use Visual Basic reserved keywords as variable name.
You cannot use Visual Basic reserved keywords as variable name.
In VBA, we need to assign a value to the declared Constants. An error is thrown, if we try to change the value of the constant.
Const <<constant_name>> As <<constant_type>> = <<constant_value>>
Let us create a button "Constant_demo" to demonstrate how to work with constants.
Private Sub Constant_demo_Click()
Const MyInteger As Integer = 42
Const myDate As Date = #2/2/2020#
Const myDay As String = "Sunday"
MsgBox "Integer is " & MyInteger & Chr(10) & "myDate is "
& myDate & Chr(10) & "myDay is " & myDay
End Sub
Upon executing the script, the output will be displayed as shown in the following screenshot.
101 Lectures
6 hours
Pavan Lalwani
41 Lectures
3 hours
Arnold Higuit
80 Lectures
5.5 hours
Prashant Panchal
25 Lectures
2 hours
Prashant Panchal
26 Lectures
2 hours
Arnold Higuit
92 Lectures
10.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2196,
"s": 1935,
"text": "Constant is a named memory location used to hold a value that CANNOT be changed during the script execution. If a user tries to change a Constant value, the script execution ends up with an error. Constants are declared the same way the variables are declared."
},
{
"code": null,
"e": 2243,
"s": 2196,
"text": "Following are the rules for naming a constant."
},
{
"code": null,
"e": 2289,
"s": 2243,
"text": "You must use a letter as the first character."
},
{
"code": null,
"e": 2335,
"s": 2289,
"text": "You must use a letter as the first character."
},
{
"code": null,
"e": 2434,
"s": 2335,
"text": "You can't use a space, period (.), exclamation mark (!), or the characters @, &, $, # in the name."
},
{
"code": null,
"e": 2533,
"s": 2434,
"text": "You can't use a space, period (.), exclamation mark (!), or the characters @, &, $, # in the name."
},
{
"code": null,
"e": 2577,
"s": 2533,
"text": "Name can't exceed 255 characters in length."
},
{
"code": null,
"e": 2621,
"s": 2577,
"text": "Name can't exceed 255 characters in length."
},
{
"code": null,
"e": 2685,
"s": 2621,
"text": "You cannot use Visual Basic reserved keywords as variable name."
},
{
"code": null,
"e": 2749,
"s": 2685,
"text": "You cannot use Visual Basic reserved keywords as variable name."
},
{
"code": null,
"e": 2877,
"s": 2749,
"text": "In VBA, we need to assign a value to the declared Constants. An error is thrown, if we try to change the value of the constant."
},
{
"code": null,
"e": 2944,
"s": 2877,
"text": "Const <<constant_name>> As <<constant_type>> = <<constant_value>>\n"
},
{
"code": null,
"e": 3026,
"s": 2944,
"text": "Let us create a button \"Constant_demo\" to demonstrate how to work with constants."
},
{
"code": null,
"e": 3295,
"s": 3026,
"text": "Private Sub Constant_demo_Click() \n Const MyInteger As Integer = 42 \n Const myDate As Date = #2/2/2020# \n Const myDay As String = \"Sunday\" \n \n MsgBox \"Integer is \" & MyInteger & Chr(10) & \"myDate is \" \n & myDate & Chr(10) & \"myDay is \" & myDay \nEnd Sub"
},
{
"code": null,
"e": 3389,
"s": 3295,
"text": "Upon executing the script, the output will be displayed as shown in the following screenshot."
},
{
"code": null,
"e": 3423,
"s": 3389,
"text": "\n 101 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3438,
"s": 3423,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 3471,
"s": 3438,
"text": "\n 41 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3486,
"s": 3471,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3521,
"s": 3486,
"text": "\n 80 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3539,
"s": 3521,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 3572,
"s": 3539,
"text": "\n 25 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3590,
"s": 3572,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 3623,
"s": 3590,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3638,
"s": 3623,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3674,
"s": 3638,
"text": "\n 92 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 3702,
"s": 3674,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 3709,
"s": 3702,
"text": " Print"
},
{
"code": null,
"e": 3720,
"s": 3709,
"text": " Add Notes"
}
] |
Text Processing in Python. Text processing example with NLTK and... | by KahEm Chu | Towards Data Science
|
The Internet has connected the world, while Social Media like Facebook, Twitter and Reddit provided the platform for people to express their opinions and feelings toward a topic. Then, the proliferation of smartphones increased the usage of these platforms directly. For instance, there are 96% or 2,240 million Facebook active users who used Facebook by smartphones and tablets [1].
The increment in the usage of Social Media has grown the size of text data, and boost the studies or researches in Natural Language Processing (NLP), for example, Information Retrieval and Sentiment Analysis. Most of the time, the documents or the text files to be analyzed are gigantic and contains a lot of noise, directly used raw texts for analysis is inapplicable. Hence, text processing is essential to provide clean input for modelling and analysis.
Text processing contains two main phases, which are tokenization and normalization [2]. Tokenization is the process of splitting a longer string of text into smaller pieces, or tokens [3]. Normalization referring to convert number to their word equivalent, remove punctuation, convert all text to the same case, remove stopwords, remove noise, lemmatizing and stemming.
Stemming β removing affixes (suffixed, prefixes, infixes, circumfixes), For example, running to run
Lemmatization β capture canonical form based on a wordβs lemma. For example, better to good [4]
In this article, I am going to demonstrate text processing in Python.
The following is a paragraph extracted from the book βSpeech and Language Processingβ by Daniel Jurafsky and James H. Martin [6].
βThe idea of giving computers the ability to process human language is as old as the idea of computers themselves. This book is about the implementation and implications of that exciting idea. We introduce a vibrant interdisciplinary field with many names corresponding to its many facets, names like speech and language processing, human language technology, natural language processing, computational linguistics, and speech recognition and synthesis. The goal of this new field is to get computers to perform useful tasks involving human language, tasks like enabling human-machine communication, improving human-human communication, or simply doing useful processing of text or speech.β
This paragraph will be used in the examples of text processing below.
For text processing in Python, two Natural Language Processing (NLP) libraries, namely NLTK (Natural Language Toolkit) and spaCy will be used in the demonstration. The rationale behind selecting these two libraries instead of other text processing libraries like Gensim and Transformer is because NLTK and spaCy are the most popular library for everyone and friendly for the beginner in Natural Language Processing (NLP).
For both NLTK and spaCy, the text will need to be saved as a variable in the first place.
text = """The idea of giving computers the ability to process human language is as old as the idea of computers themselves. This book is about the implementation and implications of that exciting idea. We introduce a vibrant interdisciplinary field with many names corresponding to its many facets, names like speech and language processing, human language technology, natural language processing, computational linguistics, and speech recognition and synthesis. The goal of this new field is to get computers to perform useful tasks involving human language, tasks like enabling human-machine communication, improving human-human communication, or simply doing useful processing of text or speech."""
Import all needed libraries
Import all needed libraries
import reimport pandas as pdimport nltkfrom nltk.tokenize import WordPunctTokenizernltk.download(βstopwordsβ)from nltk.corpus import stopwords# needed for nltk.pos_tag function nltk.download(βaveraged_perceptron_taggerβ)nltk.download(βwordnetβ)from nltk.stem import WordNetLemmatizer
Tokenization
Tokenization
Using tokenizer to separate the sentences into a list of single words (tokens).
word_punct_token = WordPunctTokenizer().tokenize(text)
There are several tokenizer modules in NLTK libraries other than WordPunctTokenizer used above. For example, word_tokenizeand RegexpTokenizer. RegexpTokenizer able to separate the currency like $9.99 as a single token by setting RegexpTokenizer(β\w+|\$[\d\.]+|\S+β). All the tokenizers mentioned will be return the tokens in the list form. NLTK also have a module name sent_tokenize which able to separate paragraphs into the list of sentences.
2. Normalization
The script below removed the tokens which are not a word, for example, the symbols and numbers, also tokens that only contain less than two letters or contain only consonants. This script might not be useful in this example, but itβs pretty useful when you are dealing with a large set of text data, it helps to clean up much noise. I always like to include it whenever I was processing text data.
clean_token=[]for token in word_punct_token: token = token.lower() # remove any value that are not alphabetical new_token = re.sub(r'[^a-zA-Z]+', '', token) # remove empty value and single character value if new_token != "" and len(new_token) >= 2: vowels=len([v for v in new_token if v in "aeiou"]) if vowels != 0: # remove line that only contains consonants clean_token.append(new_token)
2a. Removing Stopwords
Stopwords referring to the word which does not carry much insight, such as preposition. NLTK and spaCy have a different amount of stopwords in the library, but both NLTK and spaCy allowed us to add in any word we feel necessary. For example, when we dealing with email, we may add in gmail, com, outlook as stopwords.
# Get the list of stop wordsstop_words = stopwords.words('english')# add new stopwords to the liststop_words.extend(["could","though","would","also","many",'much'])print(stop_words)# Remove the stopwords from the list of tokenstokens = [x for x in clean_token if x not in stop_words]
2b. Part-of-Speech Tagging (POS Tag)
This process referring to tag the word with their part-of-speech position, for example, verbs, adjectives and nouns. nltk.pos_tag module return results as tuples, to ease the task afterwards, normally I will transform them into a DataFrame. In [6], the POS Tag is the task perform straight after tokenization, which is a smart move when you know you only need a particular part of speech like adjectives and nouns.
data_tagset = nltk.pos_tag(tokens)df_tagset = pd.DataFrame(data_tagset, columns=['Word', 'Tag'])
2c. Lemmatization
Lemmatizing and stemming both help to reduce the dimension of the vocabulary by return the words to their root form (lemmatizing) or remove all the suffix, affix, prefix and so on (stemming). Stemming is nice for reducing the dimension of vocabulary, but most of the time the word become meaningless as stemming only chopped off the suffix but not returning the words to their base form. For example, houses will become hous after stemming, which completely lose its meaning. Hence, lemmatizing is more preferable for text analytics.
The following script is used to obtain the root form for the nouns, adjectives and verbs.
# Create lemmatizer object lemmatizer = WordNetLemmatizer()# Lemmatize each word and display the outputlemmatize_text = []for word in tokens: output = [word, lemmatizer.lemmatize(word, pos='n'), lemmatizer.lemmatize(word, pos='a'),lemmatizer.lemmatize(word, pos='v')] lemmatize_text.append(output)# create DataFrame using original words and their lemma wordsdf = pd.DataFrame(lemmatize_text, columns =['Word', 'Lemmatized Noun', 'Lemmatized Adjective', 'Lemmatized Verb']) df['Tag'] = df_tagset['Tag']
The reason for lemmatizing the adjectives, nouns and verbs separately is to improve the accuracy of the lemmatizer.
# replace with single character for simplifyingdf = df.replace(['NN','NNS','NNP','NNPS'],'n')df = df.replace(['JJ','JJR','JJS'],'a')df = df.replace(['VBG','VBP','VB','VBD','VBN','VBZ'],'v')'''define a function where take the lemmatized word when tagset is noun, and take lemmatized adjectives when tagset is adjective'''df_lemmatized = df.copy()df_lemmatized['Tempt Lemmatized Word']=df_lemmatized['Lemmatized Noun'] + ' | ' + df_lemmatized['Lemmatized Adjective']+ ' | ' + df_lemmatized['Lemmatized Verb']df_lemmatized.head(5)lemma_word = df_lemmatized['Tempt Lemmatized Word']tag = df_lemmatized['Tag']i = 0new_word = []while i<len(tag): words = lemma_word[i].split('|') if tag[i] == 'n': word = words[0] elif tag[i] == 'a': word = words[1] elif tag[i] == 'v': word = words[2] new_word.append(word) i += 1df_lemmatized['Lemmatized Word']=new_word
The script above is to assign the correct lemmatized word to the original word according to their POS Tag.
3. Obtain the Cleaned Tokens
# calculate frequency distribution of the tokenslemma_word = [str(x) for x in df_lemmatized['Lemmatized Word']]
After tokenized and normalized the text, now we obtained a list of clean tokens, which ready to be plug-in into WordCloud or other text analytics models.
Tokenization + Lemmatization
Tokenization + Lemmatization
SpaCy advantage compared to NLTK is it simplified the text processes.
# Import spaCy and load the language libraryimport spacy#you will need this line below to download the package!python -m spacy download en_core_web_smnlp = spacy.load('en_core_web_sm')# Create a Doc objectdoc = nlp(text)token_list = []# collect each token separately with their POS Tag, dependencies and lemmafor token in doc: output = [token.text, token.pos_, token.dep_,token.lemma_] token_list.append(output)# create DataFrame using data df = pd.DataFrame(token_list, columns =['Word', 'POS Tag', 'Dependencies', 'Lemmatized Word'])
In spaCy, you may obtain the POS Tag and the lemma (root form of the word) when you performing tokenization, which saves you some effort.
2. Normalization
As the lemmatizing is performed at the very beginning, the normalization steps leave only removing noise and stopwords.
2a. Removing Noise
df_nopunct = df[df['POS Tag']!='PUNCT']df_nopunct
The spaCy POS Tag contained a punctuation tag which showed as PUNCT, hence we can remove all the punctuation by removing the tokens with PUNCT tag.
2b. Removing Stopwords
import numpy as nplemma_word = df_nopunct['Lemmatized Word'].values.tolist()stopword = nlp.Defaults.stop_words# Add the word to the set of stop words. Use lowercase!nlp.Defaults.stop_words.add('btw')is_stopword_list = []for word in lemma_word: is_stopword = nlp.vocab[word].is_stop is_stopword_list.append(is_stopword)df_nopunct["is_stopword"] = is_stopword_listdf_nopunctclean_df = df_nopunct[df_nopunct["is_stopword"]==False]
SpaCy have a class .is_stop which can be used to detect whether a token is a stopword, we can use it to remove the stopwords as shown in the script above.
3. Obtain the Cleaned Tokens
clean_list = clean_df["Lemmatized Word"].values.tolist()
Now we obtained the list of cleaned tokens!
spaCy is faster and more advance than NLTK, but NLTK is better for beginners to understand every process in text processing as it occurs longer and does have a lot of documentation and explanation. You may find the comparison of spaCy and NLTK for other features like GPU support, efficiency, performance, state of the art, word vectors and flexibility here.
Thank you for reading until here! Hope the demonstration above does help you to understand text processing in Python.
For text processing, understanding the data structure is as important as Regular Expression (RegEx). For example, the return of the class or module might be in the form of tuples and lists, to manipulate the return output, we first have to understand them. The below is some of the scripts I used frequently to change the data structure of the variables for different purposes.
From DataFrame (Multiple Columns) to Nested List, From Nested List to List
From DataFrame (Multiple Columns) to Nested List, From Nested List to List
When we are creating Topic Modelling or Sentiment Analysis models, normally we kept the tokens separately according to sentences or paragraphs, for example, reviews and tweets are kept separately to obtain the accurate sentiment or topic for each review or tweet. Hence, if we have 10 reviews, there will be 10 lists of tokens, saving them together in a single variable create a nested list. Another example is, a DataFrame with few columns holding text data, which could be essay questions for survey or maybe reviews for a product. We might want to change these columns into lists directly, but changing few columns of data into a list created a nested list also.
# df_essays is a dataframe with few columns of text dataessay_list = df_essays.values.tolist() # this create a nested list# this create a flat listflatEssayList = [item for elem in essay_list for item in elem if str(item) != 'nan']
2. From DataFrame (Single Columns) or List to Text
One of the popular application in Text Analytics is WordCloud, which mainly used to analyze the most frequent discussion in the text. This module only takes text as input, so in this scenario, we will need to change the list or DataFrame.Column to text.
# dataframe.column to texttext = β β.join(str(x) for x in df[βreviewβ])# list to texttext = β β.join(str(x) for x in any_list)
3. From DataFrame (Single Column) to List
reviews_list = df["reviews"].values.tolist()
4. From Text to List
This is simple and handy.
token_list = text.split()
5. From Tuples to DataFrame
I mentioned this above, repeat it here for better reference.
The nltk.pos_tagmodule returns the tag set as tuples in form of (word, pos tag) .
data_tagset = nltk.pos_tag(tokens)df_tagset = pd.DataFrame(data_tagset, columns=['Word', 'Tag'])
If you are interested in extracting the sentences that contain the keywords from a keyword list: Text Extraction using Regular Expression (Python).
If you are interested in explore the gigantic text with Word Cloud: Text Exploration with Word Cloud.
Subscribe on YouTube
[1] M. Iqbal, βFacebook Revenue and Usage Statistics (2020),β 8 March 2021. [Online]. Available: https://www.businessofapps.com/data/facebook-statistics/.
[2] M. Mayo, βA General Approach to Preprocessing Text Data,β 2017. [Online]. Available: https://www.kdnuggets.com/2017/12/general-approach-preprocessing-text-data.html. [Accessed 12 June 2020].
[3] D. Subramanian, βText Mining in Python: Steps and Examples,β 22 August 2019. [Online]. Available: https://medium.com/towards-artificial-intelligence/text-mining-in-python-steps-and-examples-78b3f8fd913b. [Accessed 12 June 2020].
[4] M. Mayo, βNatural Language Processing Key Terms, Explained,β 2017. [Online]. Available: https://www.kdnuggets.com/2017/02/natural-language-processing-key-terms-explained.html.
[5] βNatural Language Processing In Julia (Text Analysis),β JCharisTech, 1 May 2018. [Online]. Available: https://jcharistech.wordpress.com/2018/05/01/natural-language-processing-in-julia-text-analysis/.
[6] D. Jurafsky and J. H. Martin, βSpeech and Language Processing,β 3 December 2020. [Online]. Available: https://web.stanford.edu/~jurafsky/slp3/.
[7] M.F. Goh, βText Normalization with spaCy and NLTK,β 29 November 2020. [Online]. Available: https://towardsdatascience.com/text-normalization-with-spacy-and-nltk-1302ff430119.
Congrats and thanks for reading to the end. Hope you enjoy this article. βΊοΈ
|
[
{
"code": null,
"e": 555,
"s": 171,
"text": "The Internet has connected the world, while Social Media like Facebook, Twitter and Reddit provided the platform for people to express their opinions and feelings toward a topic. Then, the proliferation of smartphones increased the usage of these platforms directly. For instance, there are 96% or 2,240 million Facebook active users who used Facebook by smartphones and tablets [1]."
},
{
"code": null,
"e": 1012,
"s": 555,
"text": "The increment in the usage of Social Media has grown the size of text data, and boost the studies or researches in Natural Language Processing (NLP), for example, Information Retrieval and Sentiment Analysis. Most of the time, the documents or the text files to be analyzed are gigantic and contains a lot of noise, directly used raw texts for analysis is inapplicable. Hence, text processing is essential to provide clean input for modelling and analysis."
},
{
"code": null,
"e": 1382,
"s": 1012,
"text": "Text processing contains two main phases, which are tokenization and normalization [2]. Tokenization is the process of splitting a longer string of text into smaller pieces, or tokens [3]. Normalization referring to convert number to their word equivalent, remove punctuation, convert all text to the same case, remove stopwords, remove noise, lemmatizing and stemming."
},
{
"code": null,
"e": 1482,
"s": 1382,
"text": "Stemming β removing affixes (suffixed, prefixes, infixes, circumfixes), For example, running to run"
},
{
"code": null,
"e": 1578,
"s": 1482,
"text": "Lemmatization β capture canonical form based on a wordβs lemma. For example, better to good [4]"
},
{
"code": null,
"e": 1648,
"s": 1578,
"text": "In this article, I am going to demonstrate text processing in Python."
},
{
"code": null,
"e": 1778,
"s": 1648,
"text": "The following is a paragraph extracted from the book βSpeech and Language Processingβ by Daniel Jurafsky and James H. Martin [6]."
},
{
"code": null,
"e": 2469,
"s": 1778,
"text": "βThe idea of giving computers the ability to process human language is as old as the idea of computers themselves. This book is about the implementation and implications of that exciting idea. We introduce a vibrant interdisciplinary field with many names corresponding to its many facets, names like speech and language processing, human language technology, natural language processing, computational linguistics, and speech recognition and synthesis. The goal of this new field is to get computers to perform useful tasks involving human language, tasks like enabling human-machine communication, improving human-human communication, or simply doing useful processing of text or speech.β"
},
{
"code": null,
"e": 2539,
"s": 2469,
"text": "This paragraph will be used in the examples of text processing below."
},
{
"code": null,
"e": 2961,
"s": 2539,
"text": "For text processing in Python, two Natural Language Processing (NLP) libraries, namely NLTK (Natural Language Toolkit) and spaCy will be used in the demonstration. The rationale behind selecting these two libraries instead of other text processing libraries like Gensim and Transformer is because NLTK and spaCy are the most popular library for everyone and friendly for the beginner in Natural Language Processing (NLP)."
},
{
"code": null,
"e": 3051,
"s": 2961,
"text": "For both NLTK and spaCy, the text will need to be saved as a variable in the first place."
},
{
"code": null,
"e": 3753,
"s": 3051,
"text": "text = \"\"\"The idea of giving computers the ability to process human language is as old as the idea of computers themselves. This book is about the implementation and implications of that exciting idea. We introduce a vibrant interdisciplinary field with many names corresponding to its many facets, names like speech and language processing, human language technology, natural language processing, computational linguistics, and speech recognition and synthesis. The goal of this new field is to get computers to perform useful tasks involving human language, tasks like enabling human-machine communication, improving human-human communication, or simply doing useful processing of text or speech.\"\"\""
},
{
"code": null,
"e": 3781,
"s": 3753,
"text": "Import all needed libraries"
},
{
"code": null,
"e": 3809,
"s": 3781,
"text": "Import all needed libraries"
},
{
"code": null,
"e": 4093,
"s": 3809,
"text": "import reimport pandas as pdimport nltkfrom nltk.tokenize import WordPunctTokenizernltk.download(βstopwordsβ)from nltk.corpus import stopwords# needed for nltk.pos_tag function nltk.download(βaveraged_perceptron_taggerβ)nltk.download(βwordnetβ)from nltk.stem import WordNetLemmatizer"
},
{
"code": null,
"e": 4106,
"s": 4093,
"text": "Tokenization"
},
{
"code": null,
"e": 4119,
"s": 4106,
"text": "Tokenization"
},
{
"code": null,
"e": 4199,
"s": 4119,
"text": "Using tokenizer to separate the sentences into a list of single words (tokens)."
},
{
"code": null,
"e": 4254,
"s": 4199,
"text": "word_punct_token = WordPunctTokenizer().tokenize(text)"
},
{
"code": null,
"e": 4699,
"s": 4254,
"text": "There are several tokenizer modules in NLTK libraries other than WordPunctTokenizer used above. For example, word_tokenizeand RegexpTokenizer. RegexpTokenizer able to separate the currency like $9.99 as a single token by setting RegexpTokenizer(β\\w+|\\$[\\d\\.]+|\\S+β). All the tokenizers mentioned will be return the tokens in the list form. NLTK also have a module name sent_tokenize which able to separate paragraphs into the list of sentences."
},
{
"code": null,
"e": 4716,
"s": 4699,
"text": "2. Normalization"
},
{
"code": null,
"e": 5114,
"s": 4716,
"text": "The script below removed the tokens which are not a word, for example, the symbols and numbers, also tokens that only contain less than two letters or contain only consonants. This script might not be useful in this example, but itβs pretty useful when you are dealing with a large set of text data, it helps to clean up much noise. I always like to include it whenever I was processing text data."
},
{
"code": null,
"e": 5546,
"s": 5114,
"text": "clean_token=[]for token in word_punct_token: token = token.lower() # remove any value that are not alphabetical new_token = re.sub(r'[^a-zA-Z]+', '', token) # remove empty value and single character value if new_token != \"\" and len(new_token) >= 2: vowels=len([v for v in new_token if v in \"aeiou\"]) if vowels != 0: # remove line that only contains consonants clean_token.append(new_token)"
},
{
"code": null,
"e": 5569,
"s": 5546,
"text": "2a. Removing Stopwords"
},
{
"code": null,
"e": 5887,
"s": 5569,
"text": "Stopwords referring to the word which does not carry much insight, such as preposition. NLTK and spaCy have a different amount of stopwords in the library, but both NLTK and spaCy allowed us to add in any word we feel necessary. For example, when we dealing with email, we may add in gmail, com, outlook as stopwords."
},
{
"code": null,
"e": 6171,
"s": 5887,
"text": "# Get the list of stop wordsstop_words = stopwords.words('english')# add new stopwords to the liststop_words.extend([\"could\",\"though\",\"would\",\"also\",\"many\",'much'])print(stop_words)# Remove the stopwords from the list of tokenstokens = [x for x in clean_token if x not in stop_words]"
},
{
"code": null,
"e": 6208,
"s": 6171,
"text": "2b. Part-of-Speech Tagging (POS Tag)"
},
{
"code": null,
"e": 6623,
"s": 6208,
"text": "This process referring to tag the word with their part-of-speech position, for example, verbs, adjectives and nouns. nltk.pos_tag module return results as tuples, to ease the task afterwards, normally I will transform them into a DataFrame. In [6], the POS Tag is the task perform straight after tokenization, which is a smart move when you know you only need a particular part of speech like adjectives and nouns."
},
{
"code": null,
"e": 6720,
"s": 6623,
"text": "data_tagset = nltk.pos_tag(tokens)df_tagset = pd.DataFrame(data_tagset, columns=['Word', 'Tag'])"
},
{
"code": null,
"e": 6738,
"s": 6720,
"text": "2c. Lemmatization"
},
{
"code": null,
"e": 7272,
"s": 6738,
"text": "Lemmatizing and stemming both help to reduce the dimension of the vocabulary by return the words to their root form (lemmatizing) or remove all the suffix, affix, prefix and so on (stemming). Stemming is nice for reducing the dimension of vocabulary, but most of the time the word become meaningless as stemming only chopped off the suffix but not returning the words to their base form. For example, houses will become hous after stemming, which completely lose its meaning. Hence, lemmatizing is more preferable for text analytics."
},
{
"code": null,
"e": 7362,
"s": 7272,
"text": "The following script is used to obtain the root form for the nouns, adjectives and verbs."
},
{
"code": null,
"e": 7876,
"s": 7362,
"text": "# Create lemmatizer object lemmatizer = WordNetLemmatizer()# Lemmatize each word and display the outputlemmatize_text = []for word in tokens: output = [word, lemmatizer.lemmatize(word, pos='n'), lemmatizer.lemmatize(word, pos='a'),lemmatizer.lemmatize(word, pos='v')] lemmatize_text.append(output)# create DataFrame using original words and their lemma wordsdf = pd.DataFrame(lemmatize_text, columns =['Word', 'Lemmatized Noun', 'Lemmatized Adjective', 'Lemmatized Verb']) df['Tag'] = df_tagset['Tag']"
},
{
"code": null,
"e": 7992,
"s": 7876,
"text": "The reason for lemmatizing the adjectives, nouns and verbs separately is to improve the accuracy of the lemmatizer."
},
{
"code": null,
"e": 8888,
"s": 7992,
"text": "# replace with single character for simplifyingdf = df.replace(['NN','NNS','NNP','NNPS'],'n')df = df.replace(['JJ','JJR','JJS'],'a')df = df.replace(['VBG','VBP','VB','VBD','VBN','VBZ'],'v')'''define a function where take the lemmatized word when tagset is noun, and take lemmatized adjectives when tagset is adjective'''df_lemmatized = df.copy()df_lemmatized['Tempt Lemmatized Word']=df_lemmatized['Lemmatized Noun'] + ' | ' + df_lemmatized['Lemmatized Adjective']+ ' | ' + df_lemmatized['Lemmatized Verb']df_lemmatized.head(5)lemma_word = df_lemmatized['Tempt Lemmatized Word']tag = df_lemmatized['Tag']i = 0new_word = []while i<len(tag): words = lemma_word[i].split('|') if tag[i] == 'n': word = words[0] elif tag[i] == 'a': word = words[1] elif tag[i] == 'v': word = words[2] new_word.append(word) i += 1df_lemmatized['Lemmatized Word']=new_word"
},
{
"code": null,
"e": 8995,
"s": 8888,
"text": "The script above is to assign the correct lemmatized word to the original word according to their POS Tag."
},
{
"code": null,
"e": 9024,
"s": 8995,
"text": "3. Obtain the Cleaned Tokens"
},
{
"code": null,
"e": 9136,
"s": 9024,
"text": "# calculate frequency distribution of the tokenslemma_word = [str(x) for x in df_lemmatized['Lemmatized Word']]"
},
{
"code": null,
"e": 9290,
"s": 9136,
"text": "After tokenized and normalized the text, now we obtained a list of clean tokens, which ready to be plug-in into WordCloud or other text analytics models."
},
{
"code": null,
"e": 9319,
"s": 9290,
"text": "Tokenization + Lemmatization"
},
{
"code": null,
"e": 9348,
"s": 9319,
"text": "Tokenization + Lemmatization"
},
{
"code": null,
"e": 9418,
"s": 9348,
"text": "SpaCy advantage compared to NLTK is it simplified the text processes."
},
{
"code": null,
"e": 9961,
"s": 9418,
"text": "# Import spaCy and load the language libraryimport spacy#you will need this line below to download the package!python -m spacy download en_core_web_smnlp = spacy.load('en_core_web_sm')# Create a Doc objectdoc = nlp(text)token_list = []# collect each token separately with their POS Tag, dependencies and lemmafor token in doc: output = [token.text, token.pos_, token.dep_,token.lemma_] token_list.append(output)# create DataFrame using data df = pd.DataFrame(token_list, columns =['Word', 'POS Tag', 'Dependencies', 'Lemmatized Word']) "
},
{
"code": null,
"e": 10099,
"s": 9961,
"text": "In spaCy, you may obtain the POS Tag and the lemma (root form of the word) when you performing tokenization, which saves you some effort."
},
{
"code": null,
"e": 10116,
"s": 10099,
"text": "2. Normalization"
},
{
"code": null,
"e": 10236,
"s": 10116,
"text": "As the lemmatizing is performed at the very beginning, the normalization steps leave only removing noise and stopwords."
},
{
"code": null,
"e": 10255,
"s": 10236,
"text": "2a. Removing Noise"
},
{
"code": null,
"e": 10305,
"s": 10255,
"text": "df_nopunct = df[df['POS Tag']!='PUNCT']df_nopunct"
},
{
"code": null,
"e": 10453,
"s": 10305,
"text": "The spaCy POS Tag contained a punctuation tag which showed as PUNCT, hence we can remove all the punctuation by removing the tokens with PUNCT tag."
},
{
"code": null,
"e": 10476,
"s": 10453,
"text": "2b. Removing Stopwords"
},
{
"code": null,
"e": 10910,
"s": 10476,
"text": "import numpy as nplemma_word = df_nopunct['Lemmatized Word'].values.tolist()stopword = nlp.Defaults.stop_words# Add the word to the set of stop words. Use lowercase!nlp.Defaults.stop_words.add('btw')is_stopword_list = []for word in lemma_word: is_stopword = nlp.vocab[word].is_stop is_stopword_list.append(is_stopword)df_nopunct[\"is_stopword\"] = is_stopword_listdf_nopunctclean_df = df_nopunct[df_nopunct[\"is_stopword\"]==False]"
},
{
"code": null,
"e": 11065,
"s": 10910,
"text": "SpaCy have a class .is_stop which can be used to detect whether a token is a stopword, we can use it to remove the stopwords as shown in the script above."
},
{
"code": null,
"e": 11094,
"s": 11065,
"text": "3. Obtain the Cleaned Tokens"
},
{
"code": null,
"e": 11151,
"s": 11094,
"text": "clean_list = clean_df[\"Lemmatized Word\"].values.tolist()"
},
{
"code": null,
"e": 11195,
"s": 11151,
"text": "Now we obtained the list of cleaned tokens!"
},
{
"code": null,
"e": 11554,
"s": 11195,
"text": "spaCy is faster and more advance than NLTK, but NLTK is better for beginners to understand every process in text processing as it occurs longer and does have a lot of documentation and explanation. You may find the comparison of spaCy and NLTK for other features like GPU support, efficiency, performance, state of the art, word vectors and flexibility here."
},
{
"code": null,
"e": 11672,
"s": 11554,
"text": "Thank you for reading until here! Hope the demonstration above does help you to understand text processing in Python."
},
{
"code": null,
"e": 12050,
"s": 11672,
"text": "For text processing, understanding the data structure is as important as Regular Expression (RegEx). For example, the return of the class or module might be in the form of tuples and lists, to manipulate the return output, we first have to understand them. The below is some of the scripts I used frequently to change the data structure of the variables for different purposes."
},
{
"code": null,
"e": 12125,
"s": 12050,
"text": "From DataFrame (Multiple Columns) to Nested List, From Nested List to List"
},
{
"code": null,
"e": 12200,
"s": 12125,
"text": "From DataFrame (Multiple Columns) to Nested List, From Nested List to List"
},
{
"code": null,
"e": 12866,
"s": 12200,
"text": "When we are creating Topic Modelling or Sentiment Analysis models, normally we kept the tokens separately according to sentences or paragraphs, for example, reviews and tweets are kept separately to obtain the accurate sentiment or topic for each review or tweet. Hence, if we have 10 reviews, there will be 10 lists of tokens, saving them together in a single variable create a nested list. Another example is, a DataFrame with few columns holding text data, which could be essay questions for survey or maybe reviews for a product. We might want to change these columns into lists directly, but changing few columns of data into a list created a nested list also."
},
{
"code": null,
"e": 13098,
"s": 12866,
"text": "# df_essays is a dataframe with few columns of text dataessay_list = df_essays.values.tolist() # this create a nested list# this create a flat listflatEssayList = [item for elem in essay_list for item in elem if str(item) != 'nan']"
},
{
"code": null,
"e": 13149,
"s": 13098,
"text": "2. From DataFrame (Single Columns) or List to Text"
},
{
"code": null,
"e": 13403,
"s": 13149,
"text": "One of the popular application in Text Analytics is WordCloud, which mainly used to analyze the most frequent discussion in the text. This module only takes text as input, so in this scenario, we will need to change the list or DataFrame.Column to text."
},
{
"code": null,
"e": 13530,
"s": 13403,
"text": "# dataframe.column to texttext = β β.join(str(x) for x in df[βreviewβ])# list to texttext = β β.join(str(x) for x in any_list)"
},
{
"code": null,
"e": 13572,
"s": 13530,
"text": "3. From DataFrame (Single Column) to List"
},
{
"code": null,
"e": 13617,
"s": 13572,
"text": "reviews_list = df[\"reviews\"].values.tolist()"
},
{
"code": null,
"e": 13638,
"s": 13617,
"text": "4. From Text to List"
},
{
"code": null,
"e": 13664,
"s": 13638,
"text": "This is simple and handy."
},
{
"code": null,
"e": 13690,
"s": 13664,
"text": "token_list = text.split()"
},
{
"code": null,
"e": 13718,
"s": 13690,
"text": "5. From Tuples to DataFrame"
},
{
"code": null,
"e": 13779,
"s": 13718,
"text": "I mentioned this above, repeat it here for better reference."
},
{
"code": null,
"e": 13861,
"s": 13779,
"text": "The nltk.pos_tagmodule returns the tag set as tuples in form of (word, pos tag) ."
},
{
"code": null,
"e": 13958,
"s": 13861,
"text": "data_tagset = nltk.pos_tag(tokens)df_tagset = pd.DataFrame(data_tagset, columns=['Word', 'Tag'])"
},
{
"code": null,
"e": 14106,
"s": 13958,
"text": "If you are interested in extracting the sentences that contain the keywords from a keyword list: Text Extraction using Regular Expression (Python)."
},
{
"code": null,
"e": 14208,
"s": 14106,
"text": "If you are interested in explore the gigantic text with Word Cloud: Text Exploration with Word Cloud."
},
{
"code": null,
"e": 14229,
"s": 14208,
"text": "Subscribe on YouTube"
},
{
"code": null,
"e": 14384,
"s": 14229,
"text": "[1] M. Iqbal, βFacebook Revenue and Usage Statistics (2020),β 8 March 2021. [Online]. Available: https://www.businessofapps.com/data/facebook-statistics/."
},
{
"code": null,
"e": 14579,
"s": 14384,
"text": "[2] M. Mayo, βA General Approach to Preprocessing Text Data,β 2017. [Online]. Available: https://www.kdnuggets.com/2017/12/general-approach-preprocessing-text-data.html. [Accessed 12 June 2020]."
},
{
"code": null,
"e": 14812,
"s": 14579,
"text": "[3] D. Subramanian, βText Mining in Python: Steps and Examples,β 22 August 2019. [Online]. Available: https://medium.com/towards-artificial-intelligence/text-mining-in-python-steps-and-examples-78b3f8fd913b. [Accessed 12 June 2020]."
},
{
"code": null,
"e": 14992,
"s": 14812,
"text": "[4] M. Mayo, βNatural Language Processing Key Terms, Explained,β 2017. [Online]. Available: https://www.kdnuggets.com/2017/02/natural-language-processing-key-terms-explained.html."
},
{
"code": null,
"e": 15196,
"s": 14992,
"text": "[5] βNatural Language Processing In Julia (Text Analysis),β JCharisTech, 1 May 2018. [Online]. Available: https://jcharistech.wordpress.com/2018/05/01/natural-language-processing-in-julia-text-analysis/."
},
{
"code": null,
"e": 15344,
"s": 15196,
"text": "[6] D. Jurafsky and J. H. Martin, βSpeech and Language Processing,β 3 December 2020. [Online]. Available: https://web.stanford.edu/~jurafsky/slp3/."
},
{
"code": null,
"e": 15523,
"s": 15344,
"text": "[7] M.F. Goh, βText Normalization with spaCy and NLTK,β 29 November 2020. [Online]. Available: https://towardsdatascience.com/text-normalization-with-spacy-and-nltk-1302ff430119."
}
] |
MessageFormat format() method in Java with Example : Set - 1 - GeeksforGeeks
|
04 Feb, 2022
The format() method of java.text.MessageFormat class is used to get the formatted array of object appended into the string buffer object. formatted array will contain all forms of element lies in the pattern of MessageFormat object.Syntax:
public final StringBuffer format(Object[] arguments,
StringBuffer result,
FieldPosition pos)
Parameter:
argument :β This method takes array object as a parameter for which formatting is going to take place.
result :- string buffer will be use for appending the formatted array.
pos :- field position will be going to use for alignment purpose.
Return Value: This method returns string buffer which will have the appended result of formatted array.Exception: This method throws NullPointerException if the result is null.Below are the examples to illustrate the format() method:Example 1:
Java
// Java program to demonstrate// format() method import java.text.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { try { // creating and initializing new MessageFormat Object MessageFormat mf = new MessageFormat("{0, number, #}, {0, number, #.##}, {0, number}"); // Creating and initializing new FieldPosition Object FieldPosition fp = new FieldPosition(MessageFormat.Field.ARGUMENT); // Creating and initializing an array of type Double // to be formatted Object[] objs = { new Double(9.5678) }; // Creating and initializing StringBuffer for // appending the result StringBuffer stb = new StringBuffer(10); // Formatting an array of object // using format() method stb = mf.format(objs, stb, fp); // display the result System.out.println("formatted array : " + stb.toString()); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } }}
Example 2:
Java
// Java program to demonstrate// format() method import java.text.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { try { // creating and initializing new MessageFormat Object MessageFormat mf = new MessageFormat("{0, number, #}, {0, number, #.##}, {0, number}"); // Creating and initializing new FieldPosition Object FieldPosition fp = new FieldPosition(MessageFormat.Field.ARGUMENT); // Creating and initializing an array of type Double // to be formatted Object[] objs = { new Double(9.5678) }; // Creating and initializing StringBuffer for // appending the result StringBuffer stb = new StringBuffer(10); // Formatting an array of object // using format() method stb = mf.format(objs, null, fp); // display the result System.out.println("formatted array : " + stb.toString()); } catch (NullPointerException e) { System.out.println("StringBuffer is null " + e); System.out.println("Exception thrown : " + e); } }}
old pattern : {0, date, #}, {1, date, #}, {0, number}
String is Null
StringBuffer is null java.lang.NullPointerException
Exception thrown : java.lang.NullPointerException
Reference: https://docs.oracle.com/javase/9/docs/api/java/text/MessageFormat.html#format-java.lang.Object:A-java.lang.StringBuffer-java.text.FieldPosition-
sumitgumber28
adnanirshad158
sweetyty
saurabh1990aror
Java-Functions
Java-MessageFormat
Java-text package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
Overriding in Java
Multidimensional Arrays in Java
LinkedList in Java
How to iterate any Map in Java
PriorityQueue in Java
ArrayList in Java
Stack Class in Java
Queue Interface In Java
Object Oriented Programming (OOPs) Concept in Java
|
[
{
"code": null,
"e": 24601,
"s": 24573,
"text": "\n04 Feb, 2022"
},
{
"code": null,
"e": 24842,
"s": 24601,
"text": "The format() method of java.text.MessageFormat class is used to get the formatted array of object appended into the string buffer object. formatted array will contain all forms of element lies in the pattern of MessageFormat object.Syntax: "
},
{
"code": null,
"e": 25001,
"s": 24842,
"text": "public final StringBuffer format(Object[] arguments,\n StringBuffer result,\n FieldPosition pos)"
},
{
"code": null,
"e": 25014,
"s": 25001,
"text": "Parameter: "
},
{
"code": null,
"e": 25117,
"s": 25014,
"text": "argument :β This method takes array object as a parameter for which formatting is going to take place."
},
{
"code": null,
"e": 25188,
"s": 25117,
"text": "result :- string buffer will be use for appending the formatted array."
},
{
"code": null,
"e": 25254,
"s": 25188,
"text": "pos :- field position will be going to use for alignment purpose."
},
{
"code": null,
"e": 25500,
"s": 25254,
"text": "Return Value: This method returns string buffer which will have the appended result of formatted array.Exception: This method throws NullPointerException if the result is null.Below are the examples to illustrate the format() method:Example 1: "
},
{
"code": null,
"e": 25505,
"s": 25500,
"text": "Java"
},
{
"code": "// Java program to demonstrate// format() method import java.text.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { try { // creating and initializing new MessageFormat Object MessageFormat mf = new MessageFormat(\"{0, number, #}, {0, number, #.##}, {0, number}\"); // Creating and initializing new FieldPosition Object FieldPosition fp = new FieldPosition(MessageFormat.Field.ARGUMENT); // Creating and initializing an array of type Double // to be formatted Object[] objs = { new Double(9.5678) }; // Creating and initializing StringBuffer for // appending the result StringBuffer stb = new StringBuffer(10); // Formatting an array of object // using format() method stb = mf.format(objs, stb, fp); // display the result System.out.println(\"formatted array : \" + stb.toString()); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 26700,
"s": 25505,
"text": null
},
{
"code": null,
"e": 26712,
"s": 26700,
"text": "Example 2: "
},
{
"code": null,
"e": 26717,
"s": 26712,
"text": "Java"
},
{
"code": "// Java program to demonstrate// format() method import java.text.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { try { // creating and initializing new MessageFormat Object MessageFormat mf = new MessageFormat(\"{0, number, #}, {0, number, #.##}, {0, number}\"); // Creating and initializing new FieldPosition Object FieldPosition fp = new FieldPosition(MessageFormat.Field.ARGUMENT); // Creating and initializing an array of type Double // to be formatted Object[] objs = { new Double(9.5678) }; // Creating and initializing StringBuffer for // appending the result StringBuffer stb = new StringBuffer(10); // Formatting an array of object // using format() method stb = mf.format(objs, null, fp); // display the result System.out.println(\"formatted array : \" + stb.toString()); } catch (NullPointerException e) { System.out.println(\"StringBuffer is null \" + e); System.out.println(\"Exception thrown : \" + e); } }}",
"e": 27972,
"s": 26717,
"text": null
},
{
"code": null,
"e": 28144,
"s": 27972,
"text": "old pattern : {0, date, #}, {1, date, #}, {0, number}\n\nString is Null\nStringBuffer is null java.lang.NullPointerException\nException thrown : java.lang.NullPointerException"
},
{
"code": null,
"e": 28302,
"s": 28146,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/text/MessageFormat.html#format-java.lang.Object:A-java.lang.StringBuffer-java.text.FieldPosition-"
},
{
"code": null,
"e": 28316,
"s": 28302,
"text": "sumitgumber28"
},
{
"code": null,
"e": 28331,
"s": 28316,
"text": "adnanirshad158"
},
{
"code": null,
"e": 28340,
"s": 28331,
"text": "sweetyty"
},
{
"code": null,
"e": 28356,
"s": 28340,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 28371,
"s": 28356,
"text": "Java-Functions"
},
{
"code": null,
"e": 28390,
"s": 28371,
"text": "Java-MessageFormat"
},
{
"code": null,
"e": 28408,
"s": 28390,
"text": "Java-text package"
},
{
"code": null,
"e": 28413,
"s": 28408,
"text": "Java"
},
{
"code": null,
"e": 28418,
"s": 28413,
"text": "Java"
},
{
"code": null,
"e": 28516,
"s": 28418,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28525,
"s": 28516,
"text": "Comments"
},
{
"code": null,
"e": 28538,
"s": 28525,
"text": "Old Comments"
},
{
"code": null,
"e": 28570,
"s": 28538,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28589,
"s": 28570,
"text": "Overriding in Java"
},
{
"code": null,
"e": 28621,
"s": 28589,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 28640,
"s": 28621,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 28671,
"s": 28640,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28693,
"s": 28671,
"text": "PriorityQueue in Java"
},
{
"code": null,
"e": 28711,
"s": 28693,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28731,
"s": 28711,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28755,
"s": 28731,
"text": "Queue Interface In Java"
}
] |
Get list of column headers from a Pandas DataFrame - GeeksforGeeks
|
17 Aug, 2020
Let us see how to get all the column headers of a Pandas DataFrame as a list. The df.columns.values attribute will return a list of column headers.
Example 1 :
# importing pandas as pdimport pandas as pd # creating the dataframedf = pd.DataFrame({'PassengerId': [892, 893, 894, 895, 896, 897, 898, 899], 'PassengerClass': [1, 1, 2, 1, 3, 3, 2, 2], 'PassengerName': ['John', 'Prity', 'Harry', 'Smith', 'James', 'Amora', 'Kiara', 'Joseph'], 'Age': [32, 54, 71, 21, 37, 9, 11, 54]}) display("The DataFrame :")display(df) # print the list of all the column headersdisplay("The column headers :")display(list(df.columns.values))
Output :
Example 2 :
# importing pandas as pdimport pandas as pd # creating the dataframemy_df = {'Students': ['A', 'B', 'C', 'D'], 'BMI': [22.7, 18.0, 21.4, 24.1], 'Religion': ['Hindu', 'Islam', 'Christian', 'Sikh']}df = pd.DataFrame(my_df)display("The DataFrame :")display(df) # print the list of all the column headersdisplay("The column headers :")display(list(df.columns.values))
Output :
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Python String | replace()
sum() function in Python
Python | Get unique values from a list
Python string length | len()
*args and **kwargs in Python
Check if element exists in list in Python
|
[
{
"code": null,
"e": 24595,
"s": 24567,
"text": "\n17 Aug, 2020"
},
{
"code": null,
"e": 24743,
"s": 24595,
"text": "Let us see how to get all the column headers of a Pandas DataFrame as a list. The df.columns.values attribute will return a list of column headers."
},
{
"code": null,
"e": 24755,
"s": 24743,
"text": "Example 1 :"
},
{
"code": "# importing pandas as pdimport pandas as pd # creating the dataframedf = pd.DataFrame({'PassengerId': [892, 893, 894, 895, 896, 897, 898, 899], 'PassengerClass': [1, 1, 2, 1, 3, 3, 2, 2], 'PassengerName': ['John', 'Prity', 'Harry', 'Smith', 'James', 'Amora', 'Kiara', 'Joseph'], 'Age': [32, 54, 71, 21, 37, 9, 11, 54]}) display(\"The DataFrame :\")display(df) # print the list of all the column headersdisplay(\"The column headers :\")display(list(df.columns.values))",
"e": 25386,
"s": 24755,
"text": null
},
{
"code": null,
"e": 25395,
"s": 25386,
"text": "Output :"
},
{
"code": null,
"e": 25407,
"s": 25395,
"text": "Example 2 :"
},
{
"code": "# importing pandas as pdimport pandas as pd # creating the dataframemy_df = {'Students': ['A', 'B', 'C', 'D'], 'BMI': [22.7, 18.0, 21.4, 24.1], 'Religion': ['Hindu', 'Islam', 'Christian', 'Sikh']}df = pd.DataFrame(my_df)display(\"The DataFrame :\")display(df) # print the list of all the column headersdisplay(\"The column headers :\")display(list(df.columns.values))",
"e": 25813,
"s": 25407,
"text": null
},
{
"code": null,
"e": 25822,
"s": 25813,
"text": "Output :"
},
{
"code": null,
"e": 25847,
"s": 25822,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 25871,
"s": 25847,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 25885,
"s": 25871,
"text": "Python-pandas"
},
{
"code": null,
"e": 25892,
"s": 25885,
"text": "Python"
},
{
"code": null,
"e": 25990,
"s": 25892,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25999,
"s": 25990,
"text": "Comments"
},
{
"code": null,
"e": 26012,
"s": 25999,
"text": "Old Comments"
},
{
"code": null,
"e": 26047,
"s": 26012,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26069,
"s": 26047,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26101,
"s": 26069,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26127,
"s": 26101,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26152,
"s": 26127,
"text": "sum() function in Python"
},
{
"code": null,
"e": 26191,
"s": 26152,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26220,
"s": 26191,
"text": "Python string length | len()"
},
{
"code": null,
"e": 26249,
"s": 26220,
"text": "*args and **kwargs in Python"
}
] |
End to End Deep Learning Tutorial using Azure | by Akshay Ashok | Towards Data Science
|
The goal of this article is to set up a deep learning workspace on azure, build and deploy end to end deep learning projects on azure. We will start by building a custom image data set to deploy the model in production. This article is a part of the MSP Developer Stories initiative by the Microsoft Student Partners (India) program.
We will build a Pokemon image classifier to classify the awesome starters Pikachu, Charmander, Squirtle, and Bulbasaur.
Live Demo at mini-pokedex.azurewebsites.net
Build custom image dataset using Bing image search APISet up our deep learning workspace using azure Data Science VMBuild and train model in Azure Data Science VM using fast AI.Build a web app to use our model through API and dockerizing it.Push Docker image of a web app to azure container registry.Deploying web app in Linux container VM from an azure container registry.Setting up continuous deployment using azure pipelines.
Build custom image dataset using Bing image search API
Set up our deep learning workspace using azure Data Science VM
Build and train model in Azure Data Science VM using fast AI.
Build a web app to use our model through API and dockerizing it.
Push Docker image of a web app to azure container registry.
Deploying web app in Linux container VM from an azure container registry.
Setting up continuous deployment using azure pipelines.
Before you start out, make sure you have an account on Azure with an active subscription. If you are a student in STEM, you may use the Azure for Students to get a subscription for free or else you can use Azure free account.
We will use the Bing Image Search API, go to the Bing Image Search API page and click on Try Bing Image Search and sign in. Then activate your service by filling out the required fields like this:
Give it a name, I named it dataset-search-API, you can try anything different based on its availability. Choose your appropriate subscription. For the pricing tier, F1 will be appropriate as it provides 1,000 transactions free per month. Create a resource group Search-API, you can name it anything, but an important point to keep in mind when working in Azure is to give appropriate names to a resource group, as you would later be using the resource group name to keep track of expenses and delete resources. Select a location for the resource group, accepting the terms and hit create. Then wait for your resource to be created. Once itβs created click go-to resource.
You would find the API key for your bing image search resource page.
Then git clone this repo: image-dataset-bing-API
open it in VS Code and create a new file named .env and paste contents of file .env.example into it.
Then copy your bing image search API key from your resource page and paste it in the .env file at the appropriate place.
Create a virtual environment with: python -m venv venv
Activate it using : venv\Scripts\activate.bat (in windows) or source venv/bin/activate (in Linux)
Install dependencies using: pip install -r requirements.txt
User the script like python search_bing_api.py β query βBulbasaurβ
Repeat the above process for Pikachu, Charmander, Squirtle.
Now you have a folder called dataset with folders with images of each pokemon.
Just go through the images and delete the ones with you feel are not relevant.
Add the folder (dataset) to a new git repo as I did here pokemon-image-dataset
Now you have a repo in GitHub with custom image Lets start with the next step:
We will set up an NC6 Promo which is a Linux VM with 1 x K80 NVIDIA GPU (1/2 Physical Card) which is 12 GB GPU and six CPU cores.
You can learn more about the VM here.
If you need a detailed installation procedure you can refer fast ai azure page else you can follow below instructions.
We will use the template created by the fast ai team to set up the VM: Click this link to take you to the VM creation page.
Create a new resource group named DSVM, set the location as your preference.
setup admin username(make lowercase or Jupyter Hub login will fail with 500 Internal Server Error), and set password
Set appropriate VM name, I named it DSVM-DL and select NC6 Promo in VM size
Select accept terms and click purchase.
Now wait until the resource is created. Click the notification icon to know if itβs created and click go to resource group when itβs created.
In the resource, group page click on the Virtual Machine with the name you gave it above. And click your public IP as in the image below
Clicking the IP will take you to a Configuration for your public IP, now change the assignment to Static from dynamic, and you can also set a DNS name label.Due to this step, your VM IP will not change after the restart. The page will look like below image
Now we have completed setting up the DSVM, let's move to next step
As you have set up a DSVM with GPU you can either with azure notebooks OR use by ssh into it DSVM and use. I recommend the second method as it gives you more flexibility. First, let me show you the azure notebooks method and then we will start using the VM with SSH.
Using Azure DSVM with azure notebooks.
Go to notebooks.azure.com, sign in and create a user id.
Then click My Notebooks and Create a New Notebook.
Now to use your VM with GPU in an azure notebook, change the option Run on Free Compute to Run on Direct Compute.
Now you can begin using the azure notebook on DSVM with GPU.
SSH into the DSVM to use from there
This method gives you more flexibility than the above one. For windows users, I recommend using wsl before this step, just type wsl into the current shell to start it.
To connect to your VM use :
ssh <username>@<VM Public IP> and enter password
Setup Jupyter Notebook and start Jupyter with the commands below
jupyter notebook password// Enter password:// Verify password:jupyter notebook --port 8888
Create a ssh tunnel to localhost:9999 from VM
ssh -L 9999:127.0.0.1:8888 <username>@<VM Public IP>
Now go to localhost:9999 to use jupyter notebook, enter a password to start using it.
You can create a folder and make a notebook called pokedex-dl and start working on it.
Note: Please refer to pokedex.ipynb to train and export your model to the outputs folder. Iβm have explained every step in the notebook if you have any queries regarding it comment below.
After following pokedex.ipynb you would have a outputs folder with the model named poke_predictor_resnet34, download this from the Jupyter notebook. Upload the model to dropbox and get the sharable link.
First git clone : pokedex-deploy locally. Replace the dropbox link in server.py with your sharable link. You should also change index.html as per your preference.
You can run pokedex-deploy in docker with
docker build -t poke-image . && docker run --rm -it -p 5000:5000 poke-image
You can also replace poke-imagewith a image name you like.
Now as we have our docker image ready we can move to next step
First we need to setup azure CLI, please refer docs.microsoft.com/en-us/cli/azure/install-azure for it. Tip for Windows users:- Try Chocolatey you can refer chocolatey.org/packages/azure-cli for installation.
Donβt forget az login
Now we will create a private container registry using Azure CLI. Container registry is basically a GitHub for docker images, docker hub is a public container registry.
If you need more details of below steps please refer container-registry-get-started-azure-CLI
# create a resource group named container_registry_rgaz group create - name container_registry_rg - location eastus# create container registry named pokeRegistryaz acr create --resource-group container_registry_rg --name pokeRegistry --sku Basic# Login to your container registryaz acr login --name pokeregistry# tag your container registry in following format,docker tag poke-image pokeregistry.azurecr.io/poke-image:v1# Push image to container registry, it will take a whiledocker push pokeregistry.azurecr.io/poke-image:v1# You can verify if it's uploaded by az acr repository list --name pokeregistry --output table# Important Please don't forget this,important for deploymentaz acr update -n pokeregistry --admin-enabled true
Go to Azure at portal.azure.com. and choose to Create a resource, Web, then choose Web App for Containers or you can directly click this link to go there.
Hit create and in the page fill the details and create a new resource group. Please change the Sku and size default option: B1 Basic in Dev/Test as it will be enough for basic needs. Donβt forget to set the image source as Azure Container Registry in the Docker tab.
Once itβs completed click on goto resource and you can find your web app URL at URL
Congrats now you have deployed your Deep Learning model π
Now on your web app page in azure, you will find a thing called Deployment Center, this is one of the coolest things in azure. It will help us in creating a CI/CD pipeline in Azure.
Click deployment center
Select Source code location (Github) and Authorize it
Select your repository
It will automatically detect the docker file, just click next
Create Azure DevOps organization and select use Existing in container registry, Click Done
Click release pipeline in after itβs the finished page
Above steps can be seen in the gif below:
Now you must be in dev.azure.com if not go to it and find your project inside your organization in dev.azure.com.
With the current set up we already have a CI/CD pipeline set up for our project, thanks to Deployment Center.
If you make any changes to your code and push it to GitHub it will build a new image, add it to your container registry and deploy.
But we have two problems to address now
just think that you keep making changes to your code and push it, your container registry(10 GB) storage will be used by all those un unused images
If you edit your Readme.md it will build a new image and deploy it.
To solve both problems go to your project page inside your organization in dev.azure.com and follow along with the below video.
Wow. Congratulations if you reached here π. If you have any doubts, post them in the comments section.
|
[
{
"code": null,
"e": 506,
"s": 172,
"text": "The goal of this article is to set up a deep learning workspace on azure, build and deploy end to end deep learning projects on azure. We will start by building a custom image data set to deploy the model in production. This article is a part of the MSP Developer Stories initiative by the Microsoft Student Partners (India) program."
},
{
"code": null,
"e": 626,
"s": 506,
"text": "We will build a Pokemon image classifier to classify the awesome starters Pikachu, Charmander, Squirtle, and Bulbasaur."
},
{
"code": null,
"e": 670,
"s": 626,
"text": "Live Demo at mini-pokedex.azurewebsites.net"
},
{
"code": null,
"e": 1099,
"s": 670,
"text": "Build custom image dataset using Bing image search APISet up our deep learning workspace using azure Data Science VMBuild and train model in Azure Data Science VM using fast AI.Build a web app to use our model through API and dockerizing it.Push Docker image of a web app to azure container registry.Deploying web app in Linux container VM from an azure container registry.Setting up continuous deployment using azure pipelines."
},
{
"code": null,
"e": 1154,
"s": 1099,
"text": "Build custom image dataset using Bing image search API"
},
{
"code": null,
"e": 1217,
"s": 1154,
"text": "Set up our deep learning workspace using azure Data Science VM"
},
{
"code": null,
"e": 1279,
"s": 1217,
"text": "Build and train model in Azure Data Science VM using fast AI."
},
{
"code": null,
"e": 1344,
"s": 1279,
"text": "Build a web app to use our model through API and dockerizing it."
},
{
"code": null,
"e": 1404,
"s": 1344,
"text": "Push Docker image of a web app to azure container registry."
},
{
"code": null,
"e": 1478,
"s": 1404,
"text": "Deploying web app in Linux container VM from an azure container registry."
},
{
"code": null,
"e": 1534,
"s": 1478,
"text": "Setting up continuous deployment using azure pipelines."
},
{
"code": null,
"e": 1760,
"s": 1534,
"text": "Before you start out, make sure you have an account on Azure with an active subscription. If you are a student in STEM, you may use the Azure for Students to get a subscription for free or else you can use Azure free account."
},
{
"code": null,
"e": 1957,
"s": 1760,
"text": "We will use the Bing Image Search API, go to the Bing Image Search API page and click on Try Bing Image Search and sign in. Then activate your service by filling out the required fields like this:"
},
{
"code": null,
"e": 2629,
"s": 1957,
"text": "Give it a name, I named it dataset-search-API, you can try anything different based on its availability. Choose your appropriate subscription. For the pricing tier, F1 will be appropriate as it provides 1,000 transactions free per month. Create a resource group Search-API, you can name it anything, but an important point to keep in mind when working in Azure is to give appropriate names to a resource group, as you would later be using the resource group name to keep track of expenses and delete resources. Select a location for the resource group, accepting the terms and hit create. Then wait for your resource to be created. Once itβs created click go-to resource."
},
{
"code": null,
"e": 2698,
"s": 2629,
"text": "You would find the API key for your bing image search resource page."
},
{
"code": null,
"e": 2747,
"s": 2698,
"text": "Then git clone this repo: image-dataset-bing-API"
},
{
"code": null,
"e": 2848,
"s": 2747,
"text": "open it in VS Code and create a new file named .env and paste contents of file .env.example into it."
},
{
"code": null,
"e": 2969,
"s": 2848,
"text": "Then copy your bing image search API key from your resource page and paste it in the .env file at the appropriate place."
},
{
"code": null,
"e": 3024,
"s": 2969,
"text": "Create a virtual environment with: python -m venv venv"
},
{
"code": null,
"e": 3122,
"s": 3024,
"text": "Activate it using : venv\\Scripts\\activate.bat (in windows) or source venv/bin/activate (in Linux)"
},
{
"code": null,
"e": 3182,
"s": 3122,
"text": "Install dependencies using: pip install -r requirements.txt"
},
{
"code": null,
"e": 3249,
"s": 3182,
"text": "User the script like python search_bing_api.py β query βBulbasaurβ"
},
{
"code": null,
"e": 3309,
"s": 3249,
"text": "Repeat the above process for Pikachu, Charmander, Squirtle."
},
{
"code": null,
"e": 3388,
"s": 3309,
"text": "Now you have a folder called dataset with folders with images of each pokemon."
},
{
"code": null,
"e": 3467,
"s": 3388,
"text": "Just go through the images and delete the ones with you feel are not relevant."
},
{
"code": null,
"e": 3546,
"s": 3467,
"text": "Add the folder (dataset) to a new git repo as I did here pokemon-image-dataset"
},
{
"code": null,
"e": 3625,
"s": 3546,
"text": "Now you have a repo in GitHub with custom image Lets start with the next step:"
},
{
"code": null,
"e": 3755,
"s": 3625,
"text": "We will set up an NC6 Promo which is a Linux VM with 1 x K80 NVIDIA GPU (1/2 Physical Card) which is 12 GB GPU and six CPU cores."
},
{
"code": null,
"e": 3793,
"s": 3755,
"text": "You can learn more about the VM here."
},
{
"code": null,
"e": 3912,
"s": 3793,
"text": "If you need a detailed installation procedure you can refer fast ai azure page else you can follow below instructions."
},
{
"code": null,
"e": 4036,
"s": 3912,
"text": "We will use the template created by the fast ai team to set up the VM: Click this link to take you to the VM creation page."
},
{
"code": null,
"e": 4113,
"s": 4036,
"text": "Create a new resource group named DSVM, set the location as your preference."
},
{
"code": null,
"e": 4230,
"s": 4113,
"text": "setup admin username(make lowercase or Jupyter Hub login will fail with 500 Internal Server Error), and set password"
},
{
"code": null,
"e": 4306,
"s": 4230,
"text": "Set appropriate VM name, I named it DSVM-DL and select NC6 Promo in VM size"
},
{
"code": null,
"e": 4346,
"s": 4306,
"text": "Select accept terms and click purchase."
},
{
"code": null,
"e": 4488,
"s": 4346,
"text": "Now wait until the resource is created. Click the notification icon to know if itβs created and click go to resource group when itβs created."
},
{
"code": null,
"e": 4625,
"s": 4488,
"text": "In the resource, group page click on the Virtual Machine with the name you gave it above. And click your public IP as in the image below"
},
{
"code": null,
"e": 4882,
"s": 4625,
"text": "Clicking the IP will take you to a Configuration for your public IP, now change the assignment to Static from dynamic, and you can also set a DNS name label.Due to this step, your VM IP will not change after the restart. The page will look like below image"
},
{
"code": null,
"e": 4949,
"s": 4882,
"text": "Now we have completed setting up the DSVM, let's move to next step"
},
{
"code": null,
"e": 5216,
"s": 4949,
"text": "As you have set up a DSVM with GPU you can either with azure notebooks OR use by ssh into it DSVM and use. I recommend the second method as it gives you more flexibility. First, let me show you the azure notebooks method and then we will start using the VM with SSH."
},
{
"code": null,
"e": 5255,
"s": 5216,
"text": "Using Azure DSVM with azure notebooks."
},
{
"code": null,
"e": 5312,
"s": 5255,
"text": "Go to notebooks.azure.com, sign in and create a user id."
},
{
"code": null,
"e": 5363,
"s": 5312,
"text": "Then click My Notebooks and Create a New Notebook."
},
{
"code": null,
"e": 5477,
"s": 5363,
"text": "Now to use your VM with GPU in an azure notebook, change the option Run on Free Compute to Run on Direct Compute."
},
{
"code": null,
"e": 5538,
"s": 5477,
"text": "Now you can begin using the azure notebook on DSVM with GPU."
},
{
"code": null,
"e": 5574,
"s": 5538,
"text": "SSH into the DSVM to use from there"
},
{
"code": null,
"e": 5742,
"s": 5574,
"text": "This method gives you more flexibility than the above one. For windows users, I recommend using wsl before this step, just type wsl into the current shell to start it."
},
{
"code": null,
"e": 5770,
"s": 5742,
"text": "To connect to your VM use :"
},
{
"code": null,
"e": 5819,
"s": 5770,
"text": "ssh <username>@<VM Public IP> and enter password"
},
{
"code": null,
"e": 5884,
"s": 5819,
"text": "Setup Jupyter Notebook and start Jupyter with the commands below"
},
{
"code": null,
"e": 5975,
"s": 5884,
"text": "jupyter notebook password// Enter password:// Verify password:jupyter notebook --port 8888"
},
{
"code": null,
"e": 6021,
"s": 5975,
"text": "Create a ssh tunnel to localhost:9999 from VM"
},
{
"code": null,
"e": 6074,
"s": 6021,
"text": "ssh -L 9999:127.0.0.1:8888 <username>@<VM Public IP>"
},
{
"code": null,
"e": 6160,
"s": 6074,
"text": "Now go to localhost:9999 to use jupyter notebook, enter a password to start using it."
},
{
"code": null,
"e": 6247,
"s": 6160,
"text": "You can create a folder and make a notebook called pokedex-dl and start working on it."
},
{
"code": null,
"e": 6435,
"s": 6247,
"text": "Note: Please refer to pokedex.ipynb to train and export your model to the outputs folder. Iβm have explained every step in the notebook if you have any queries regarding it comment below."
},
{
"code": null,
"e": 6639,
"s": 6435,
"text": "After following pokedex.ipynb you would have a outputs folder with the model named poke_predictor_resnet34, download this from the Jupyter notebook. Upload the model to dropbox and get the sharable link."
},
{
"code": null,
"e": 6802,
"s": 6639,
"text": "First git clone : pokedex-deploy locally. Replace the dropbox link in server.py with your sharable link. You should also change index.html as per your preference."
},
{
"code": null,
"e": 6844,
"s": 6802,
"text": "You can run pokedex-deploy in docker with"
},
{
"code": null,
"e": 6920,
"s": 6844,
"text": "docker build -t poke-image . && docker run --rm -it -p 5000:5000 poke-image"
},
{
"code": null,
"e": 6979,
"s": 6920,
"text": "You can also replace poke-imagewith a image name you like."
},
{
"code": null,
"e": 7042,
"s": 6979,
"text": "Now as we have our docker image ready we can move to next step"
},
{
"code": null,
"e": 7251,
"s": 7042,
"text": "First we need to setup azure CLI, please refer docs.microsoft.com/en-us/cli/azure/install-azure for it. Tip for Windows users:- Try Chocolatey you can refer chocolatey.org/packages/azure-cli for installation."
},
{
"code": null,
"e": 7273,
"s": 7251,
"text": "Donβt forget az login"
},
{
"code": null,
"e": 7441,
"s": 7273,
"text": "Now we will create a private container registry using Azure CLI. Container registry is basically a GitHub for docker images, docker hub is a public container registry."
},
{
"code": null,
"e": 7535,
"s": 7441,
"text": "If you need more details of below steps please refer container-registry-get-started-azure-CLI"
},
{
"code": null,
"e": 8266,
"s": 7535,
"text": "# create a resource group named container_registry_rgaz group create - name container_registry_rg - location eastus# create container registry named pokeRegistryaz acr create --resource-group container_registry_rg --name pokeRegistry --sku Basic# Login to your container registryaz acr login --name pokeregistry# tag your container registry in following format,docker tag poke-image pokeregistry.azurecr.io/poke-image:v1# Push image to container registry, it will take a whiledocker push pokeregistry.azurecr.io/poke-image:v1# You can verify if it's uploaded by az acr repository list --name pokeregistry --output table# Important Please don't forget this,important for deploymentaz acr update -n pokeregistry --admin-enabled true"
},
{
"code": null,
"e": 8421,
"s": 8266,
"text": "Go to Azure at portal.azure.com. and choose to Create a resource, Web, then choose Web App for Containers or you can directly click this link to go there."
},
{
"code": null,
"e": 8688,
"s": 8421,
"text": "Hit create and in the page fill the details and create a new resource group. Please change the Sku and size default option: B1 Basic in Dev/Test as it will be enough for basic needs. Donβt forget to set the image source as Azure Container Registry in the Docker tab."
},
{
"code": null,
"e": 8772,
"s": 8688,
"text": "Once itβs completed click on goto resource and you can find your web app URL at URL"
},
{
"code": null,
"e": 8830,
"s": 8772,
"text": "Congrats now you have deployed your Deep Learning model π"
},
{
"code": null,
"e": 9012,
"s": 8830,
"text": "Now on your web app page in azure, you will find a thing called Deployment Center, this is one of the coolest things in azure. It will help us in creating a CI/CD pipeline in Azure."
},
{
"code": null,
"e": 9036,
"s": 9012,
"text": "Click deployment center"
},
{
"code": null,
"e": 9090,
"s": 9036,
"text": "Select Source code location (Github) and Authorize it"
},
{
"code": null,
"e": 9113,
"s": 9090,
"text": "Select your repository"
},
{
"code": null,
"e": 9175,
"s": 9113,
"text": "It will automatically detect the docker file, just click next"
},
{
"code": null,
"e": 9266,
"s": 9175,
"text": "Create Azure DevOps organization and select use Existing in container registry, Click Done"
},
{
"code": null,
"e": 9321,
"s": 9266,
"text": "Click release pipeline in after itβs the finished page"
},
{
"code": null,
"e": 9363,
"s": 9321,
"text": "Above steps can be seen in the gif below:"
},
{
"code": null,
"e": 9477,
"s": 9363,
"text": "Now you must be in dev.azure.com if not go to it and find your project inside your organization in dev.azure.com."
},
{
"code": null,
"e": 9587,
"s": 9477,
"text": "With the current set up we already have a CI/CD pipeline set up for our project, thanks to Deployment Center."
},
{
"code": null,
"e": 9719,
"s": 9587,
"text": "If you make any changes to your code and push it to GitHub it will build a new image, add it to your container registry and deploy."
},
{
"code": null,
"e": 9759,
"s": 9719,
"text": "But we have two problems to address now"
},
{
"code": null,
"e": 9907,
"s": 9759,
"text": "just think that you keep making changes to your code and push it, your container registry(10 GB) storage will be used by all those un unused images"
},
{
"code": null,
"e": 9975,
"s": 9907,
"text": "If you edit your Readme.md it will build a new image and deploy it."
},
{
"code": null,
"e": 10103,
"s": 9975,
"text": "To solve both problems go to your project page inside your organization in dev.azure.com and follow along with the below video."
}
] |
How do we set the Java environment variable in cmd.exe?
|
When you install Java in your system first of all you need to set the environment variables which are path and class path.
PATHβ The path environment variable is used to specify the set of directories which contains executional programs.When you try to execute a program from command line, the operating system searches for the specified program in the current directly, if available, executes it.In case the programs are not available in the current directory, operating system verifies in the set of directories specified in the βPATHβ environment variable.You need to set path for compiler (javac.exe) and JVM(java.exe),which exists in the bin folder of the JDK.
PATHβ The path environment variable is used to specify the set of directories which contains executional programs.
When you try to execute a program from command line, the operating system searches for the specified program in the current directly, if available, executes it.
In case the programs are not available in the current directory, operating system verifies in the set of directories specified in the βPATHβ environment variable.
You need to set path for compiler (javac.exe) and JVM(java.exe),which exists in the bin folder of the JDK.
CLASSPATH β The class path environment variable is used to specify the location of the classes and packages.When we try to import classes and packages other that those that are available with Java Standard Library.JVM verifies the current directly for them, if not available it verifies the set of directories specified in the βCLASSPATHβ environment variable.The rt.jar file in the lib folder of JRE contains all the basic packages for Java therefore, you need to set classpath for this folder.
CLASSPATH β The class path environment variable is used to specify the location of the classes and packages.
When we try to import classes and packages other that those that are available with Java Standard Library.
JVM verifies the current directly for them, if not available it verifies the set of directories specified in the βCLASSPATHβ environment variable.
The rt.jar file in the lib folder of JRE contains all the basic packages for Java therefore, you need to set classpath for this folder.
To set path β
Open command prompt.
Copy the location of the javac and java commands i.e. bin folder of JDK example: C:\Program Files\Java\jdk1.8.0_101\bin
Using the SET command set the path variable in the command prompt as β
SET PATH=C:\Program Files\Java\jdk_version\bin
To set classpath β
Open command prompt.
Copy the location of the rt.jar file i.e. lib folder of JDK example: C:\Program Files\Java\jdk1.8.0_101\lib
Using the SET command set the classpath variable in the command prompt as β
SET CLASSPATH= C:\Program Files\Java\jdk1.8.0_101\lib
|
[
{
"code": null,
"e": 1185,
"s": 1062,
"text": "When you install Java in your system first of all you need to set the environment variables which are path and class path."
},
{
"code": null,
"e": 1728,
"s": 1185,
"text": "PATHβ The path environment variable is used to specify the set of directories which contains executional programs.When you try to execute a program from command line, the operating system searches for the specified program in the current directly, if available, executes it.In case the programs are not available in the current directory, operating system verifies in the set of directories specified in the βPATHβ environment variable.You need to set path for compiler (javac.exe) and JVM(java.exe),which exists in the bin folder of the JDK."
},
{
"code": null,
"e": 1843,
"s": 1728,
"text": "PATHβ The path environment variable is used to specify the set of directories which contains executional programs."
},
{
"code": null,
"e": 2004,
"s": 1843,
"text": "When you try to execute a program from command line, the operating system searches for the specified program in the current directly, if available, executes it."
},
{
"code": null,
"e": 2167,
"s": 2004,
"text": "In case the programs are not available in the current directory, operating system verifies in the set of directories specified in the βPATHβ environment variable."
},
{
"code": null,
"e": 2274,
"s": 2167,
"text": "You need to set path for compiler (javac.exe) and JVM(java.exe),which exists in the bin folder of the JDK."
},
{
"code": null,
"e": 2770,
"s": 2274,
"text": "CLASSPATH β The class path environment variable is used to specify the location of the classes and packages.When we try to import classes and packages other that those that are available with Java Standard Library.JVM verifies the current directly for them, if not available it verifies the set of directories specified in the βCLASSPATHβ environment variable.The rt.jar file in the lib folder of JRE contains all the basic packages for Java therefore, you need to set classpath for this folder."
},
{
"code": null,
"e": 2879,
"s": 2770,
"text": "CLASSPATH β The class path environment variable is used to specify the location of the classes and packages."
},
{
"code": null,
"e": 2986,
"s": 2879,
"text": "When we try to import classes and packages other that those that are available with Java Standard Library."
},
{
"code": null,
"e": 3133,
"s": 2986,
"text": "JVM verifies the current directly for them, if not available it verifies the set of directories specified in the βCLASSPATHβ environment variable."
},
{
"code": null,
"e": 3269,
"s": 3133,
"text": "The rt.jar file in the lib folder of JRE contains all the basic packages for Java therefore, you need to set classpath for this folder."
},
{
"code": null,
"e": 3283,
"s": 3269,
"text": "To set path β"
},
{
"code": null,
"e": 3304,
"s": 3283,
"text": "Open command prompt."
},
{
"code": null,
"e": 3424,
"s": 3304,
"text": "Copy the location of the javac and java commands i.e. bin folder of JDK example: C:\\Program Files\\Java\\jdk1.8.0_101\\bin"
},
{
"code": null,
"e": 3495,
"s": 3424,
"text": "Using the SET command set the path variable in the command prompt as β"
},
{
"code": null,
"e": 3542,
"s": 3495,
"text": "SET PATH=C:\\Program Files\\Java\\jdk_version\\bin"
},
{
"code": null,
"e": 3561,
"s": 3542,
"text": "To set classpath β"
},
{
"code": null,
"e": 3582,
"s": 3561,
"text": "Open command prompt."
},
{
"code": null,
"e": 3690,
"s": 3582,
"text": "Copy the location of the rt.jar file i.e. lib folder of JDK example: C:\\Program Files\\Java\\jdk1.8.0_101\\lib"
},
{
"code": null,
"e": 3766,
"s": 3690,
"text": "Using the SET command set the classpath variable in the command prompt as β"
},
{
"code": null,
"e": 3820,
"s": 3766,
"text": "SET CLASSPATH= C:\\Program Files\\Java\\jdk1.8.0_101\\lib"
}
] |
What is the difference between ajaxStop() and ajaxComplete() functions in jQuery?
|
ajaxStop() method
The ajaxStop( callback ) method attaches a function to be executed whenever all AJAX requests have ended.
Here is the description of all the parameters used by this method β
callback β The function to execute.
Assuming we have following HTML content in result.html file:
<h1>THIS IS RESULT...</h1>
The following is an example showing the usage of this method:
Live Demo
<html>
<head>
<title>jQuery ajaxStop() method</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
/* Global variable */
var count = 0;
$("#driver").click(function(event){
$('#stage0').load('result.html');
});
/* Gets called when request starts */
$(document).ajaxStart(function(){
count++;
$("#stage1").html("<h1>Starts, Count :" + count + "</h1>");
});
/* Gets called when request is sent */
$(document).ajaxSend(function(evt, req, set){
count++;
$("#stage2").html("<h1>Sends, Count :" + count + "</h1>");
$("#stage2").append("<h1>URL :" + set.url + "</h1>");
});
/* Gets called when request complete */
$(document).ajaxComplete(function(event,request,settings){
count++;
$("#stage3").html("<h1>Completes, Count :" + count + "</h1>");
});
/* Gets called when all requests are ended */
$(document).ajaxStop(function(event,request,settings){
count++;
$("#stage4").html("<h1>Stops, Count :" + count + "</h1>");
});
});
</script>
</head>
<body>
<p>Click on the button to load result.html file:</p>
<div id = "stage0" style = "background-color:blue;">
STAGE - 0
</div>
<div id = "stage1" style = "background-color:blue;">
STAGE - 1
</div>
<div id = "stage2" style="background-color:blue;">
STAGE - 2
</div>
<div id ="stage3" style = "background-color:blue;">
STAGE - 3
</div>
<div id = "stage4" style = "background-color:blue;">
STAGE - 4
</div>
<input type = "button" id = "driver" value = "Load Data" />
</body>
</html>
ajaxComplete() method
The ajaxComplete( callback ) method attaches a function to be executed whenever an AJAX request completes.
Here is the description of all the parameters used by this method:
callback β The function to execute. The XMLHttpRequest and settings used for that request are passed as arguments to this function.
Assuming we have the following HTML content in result.html file:
<h1>THIS IS RESULT...</h1>
The following is the code snippet showing the usage of this method:
<html>
<head>
<title>jQuery ajaxComplete() method</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#driver").click(function(event){
$('#stage1').load('result.html');
});
$(document).ajaxComplete(function(event, request, settings){
$("#stage2").html("<h1>Request Complete.</h1>");
});
});
</script>
</head>
<body>
<p>Click on the button to load result.html file:</p>
<div id = "stage1" style = "background-color:blue;">
STAGE - 1
</div>
<div id = "stage2" style = "background-color:blue;">
STAGE - 2
</div>
<input type = "button" id = "driver" value = "Load Data" />
</body>
</html>
|
[
{
"code": null,
"e": 1080,
"s": 1062,
"text": "ajaxStop() method"
},
{
"code": null,
"e": 1186,
"s": 1080,
"text": "The ajaxStop( callback ) method attaches a function to be executed whenever all AJAX requests have ended."
},
{
"code": null,
"e": 1254,
"s": 1186,
"text": "Here is the description of all the parameters used by this method β"
},
{
"code": null,
"e": 1290,
"s": 1254,
"text": "callback β The function to execute."
},
{
"code": null,
"e": 1351,
"s": 1290,
"text": "Assuming we have following HTML content in result.html file:"
},
{
"code": null,
"e": 1378,
"s": 1351,
"text": "<h1>THIS IS RESULT...</h1>"
},
{
"code": null,
"e": 1440,
"s": 1378,
"text": "The following is an example showing the usage of this method:"
},
{
"code": null,
"e": 1450,
"s": 1440,
"text": "Live Demo"
},
{
"code": null,
"e": 3615,
"s": 1450,
"text": "<html>\n\n <head>\n <title>jQuery ajaxStop() method</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function() {\n \n /* Global variable */\n var count = 0;\n\n $(\"#driver\").click(function(event){\n $('#stage0').load('result.html');\n });\n \n /* Gets called when request starts */\n $(document).ajaxStart(function(){\n count++;\n $(\"#stage1\").html(\"<h1>Starts, Count :\" + count + \"</h1>\");\n });\n \n /* Gets called when request is sent */\n $(document).ajaxSend(function(evt, req, set){\n count++;\n $(\"#stage2\").html(\"<h1>Sends, Count :\" + count + \"</h1>\");\n $(\"#stage2\").append(\"<h1>URL :\" + set.url + \"</h1>\");\n });\n \n /* Gets called when request complete */\n $(document).ajaxComplete(function(event,request,settings){\n count++;\n $(\"#stage3\").html(\"<h1>Completes, Count :\" + count + \"</h1>\");\n });\n \n /* Gets called when all requests are ended */\n $(document).ajaxStop(function(event,request,settings){\n count++;\n $(\"#stage4\").html(\"<h1>Stops, Count :\" + count + \"</h1>\");\n });\n \n });\n </script>\n </head>\n \n <body>\n \n <p>Click on the button to load result.html file:</p>\n \n <div id = \"stage0\" style = \"background-color:blue;\">\n STAGE - 0\n </div>\n \n <div id = \"stage1\" style = \"background-color:blue;\">\n STAGE - 1\n </div>\n \n <div id = \"stage2\" style=\"background-color:blue;\">\n STAGE - 2\n </div>\n \n <div id =\"stage3\" style = \"background-color:blue;\">\n STAGE - 3\n </div>\n \n <div id = \"stage4\" style = \"background-color:blue;\">\n STAGE - 4\n </div>\n \n <input type = \"button\" id = \"driver\" value = \"Load Data\" />\n \n </body>\n</html>"
},
{
"code": null,
"e": 3637,
"s": 3615,
"text": "ajaxComplete() method"
},
{
"code": null,
"e": 3744,
"s": 3637,
"text": "The ajaxComplete( callback ) method attaches a function to be executed whenever an AJAX request completes."
},
{
"code": null,
"e": 3811,
"s": 3744,
"text": "Here is the description of all the parameters used by this method:"
},
{
"code": null,
"e": 3943,
"s": 3811,
"text": "callback β The function to execute. The XMLHttpRequest and settings used for that request are passed as arguments to this function."
},
{
"code": null,
"e": 4008,
"s": 3943,
"text": "Assuming we have the following HTML content in result.html file:"
},
{
"code": null,
"e": 4035,
"s": 4008,
"text": "<h1>THIS IS RESULT...</h1>"
},
{
"code": null,
"e": 4103,
"s": 4035,
"text": "The following is the code snippet showing the usage of this method:"
},
{
"code": null,
"e": 5039,
"s": 4103,
"text": "<html>\n\n <head>\n <title>jQuery ajaxComplete() method</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function() {\n \n $(\"#driver\").click(function(event){\n $('#stage1').load('result.html');\n });\n\n $(document).ajaxComplete(function(event, request, settings){\n $(\"#stage2\").html(\"<h1>Request Complete.</h1>\");\n });\n \n });\n </script>\n </head>\n\n <body>\n \n <p>Click on the button to load result.html file:</p>\n \n <div id = \"stage1\" style = \"background-color:blue;\">\n STAGE - 1\n </div>\n \n <div id = \"stage2\" style = \"background-color:blue;\">\n STAGE - 2\n </div>\n \n <input type = \"button\" id = \"driver\" value = \"Load Data\" />\n \n </body>\n</html>"
}
] |
IDE | GeeksforGeeks | A computer science portal for geeks
|
Please enter your email address or userHandle.
12345678910111213141516171819202122232425262728293031323334353637https://c.mi.com/thread-3967156-1-1.html https://forums.ubisoft.com/showthread.php/2371427-44-Free-Cookie-Run-Cookies-Generator-2022iwd?p=15523073#post15523073https://cash-app-free-gift-card-code.tumblr.comhttps://garena-free-fire-diamonds-2022.tumblr.comhttps://dragon-ball-crystals-2022.tumblr.comhttps://free-coc-gems-generator-2022.tumblr.comhttps://coin-master-free-spins-generator.tumblr.comhttps://google-play-gift-card-codes.tumblr.comhttps://cash-app-free-money-generator.tumblr.comhttps://fifa-22-free-coins-generator.tumblr.comhttps://mobile-legends-free-diamonds.tumblr.comhttps://among-us-free-pets-skins.tumblr.comhttps://among-us-pets-skins-hats-2022.tumblr.comhttps://forums.ubisoft.com/showthread.php/2371430-IUuy3f3009f98ue0e-wfe4wfff4?p=15523076#post15523076http://zacriley.ning.com/photo/albums/wfdewfoiewfwef-we4fr4rf445t5thttps://paiza.io/projects/fylW-6np9rBzhtLSaRlrYg?language=phphttps://jsfiddle.net/a2ebu819/https://notes.io/ABDihttps://onecompiler.com/java/3xq29geuahttps://paste2.org/ykVtXAwehttps://pasteio.com/xVXvgREx400xhttps://ideone.com/PZrZpwhttps://authors.curseforge.com/paste/bc9967f1https://paste.feed-the-beast.com/view/6989eb88http://cpp.sh/7cjoahttps://brainly.co.id/tugas/47544095https://pasteall.org/Lktnhttps://ide.geeksforgeeks.org/pbSMl0qoXkhttps://pastebin.com/https://paste.centos.org/view/ac106b53https://paste.in/mNdSuFhttps://ctxt.io/2/AABgqeCsFAhttps://wow.curseforge.com/paste/932882fbhttp://paste.jp/c24e28f0/https://paste.ofcode.org/FWYYPpDUAHGMv5Q8yAzBYBhttps://www.onfeetnation.com/profiles/blogs/efe0ofier9gf9ekr-vgfer4gt54rhttps://www.mydigoo.com/forums-topicdetail-393715.htmlΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
https://ide.geeksforgeeks.org/qIQMPK9mJd
prog.c:1:6: error: expected aΜΒΒ=aΜΒΒ, aΜΒΒ,aΜΒΒ, aΜΒΒ;aΜΒΒ, aΜΒΒasmaΜΒΒ or aΜΒΒ__attribute__aΜΒΒ before aΜΒΒ:aΜΒΒ token
|
[
{
"code": null,
"e": 164,
"s": 117,
"text": "Please enter your email address or userHandle."
},
{
"code": null,
"e": 2380,
"s": 164,
"text": "12345678910111213141516171819202122232425262728293031323334353637https://c.mi.com/thread-3967156-1-1.html https://forums.ubisoft.com/showthread.php/2371427-44-Free-Cookie-Run-Cookies-Generator-2022iwd?p=15523073#post15523073https://cash-app-free-gift-card-code.tumblr.comhttps://garena-free-fire-diamonds-2022.tumblr.comhttps://dragon-ball-crystals-2022.tumblr.comhttps://free-coc-gems-generator-2022.tumblr.comhttps://coin-master-free-spins-generator.tumblr.comhttps://google-play-gift-card-codes.tumblr.comhttps://cash-app-free-money-generator.tumblr.comhttps://fifa-22-free-coins-generator.tumblr.comhttps://mobile-legends-free-diamonds.tumblr.comhttps://among-us-free-pets-skins.tumblr.comhttps://among-us-pets-skins-hats-2022.tumblr.comhttps://forums.ubisoft.com/showthread.php/2371430-IUuy3f3009f98ue0e-wfe4wfff4?p=15523076#post15523076http://zacriley.ning.com/photo/albums/wfdewfoiewfwef-we4fr4rf445t5thttps://paiza.io/projects/fylW-6np9rBzhtLSaRlrYg?language=phphttps://jsfiddle.net/a2ebu819/https://notes.io/ABDihttps://onecompiler.com/java/3xq29geuahttps://paste2.org/ykVtXAwehttps://pasteio.com/xVXvgREx400xhttps://ideone.com/PZrZpwhttps://authors.curseforge.com/paste/bc9967f1https://paste.feed-the-beast.com/view/6989eb88http://cpp.sh/7cjoahttps://brainly.co.id/tugas/47544095https://pasteall.org/Lktnhttps://ide.geeksforgeeks.org/pbSMl0qoXkhttps://pastebin.com/https://paste.centos.org/view/ac106b53https://paste.in/mNdSuFhttps://ctxt.io/2/AABgqeCsFAhttps://wow.curseforge.com/paste/932882fbhttp://paste.jp/c24e28f0/https://paste.ofcode.org/FWYYPpDUAHGMv5Q8yAzBYBhttps://www.onfeetnation.com/profiles/blogs/efe0ofier9gf9ekr-vgfer4gt54rhttps://www.mydigoo.com/forums-topicdetail-393715.htmlΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧΧXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
},
{
"code": null,
"e": 2421,
"s": 2380,
"text": "https://ide.geeksforgeeks.org/qIQMPK9mJd"
}
] |
Data Handling using Pandas; Machine Learning in Real Life | by Saptashwa Bhattacharyya | Towards Data Science
|
Today we will see some essential techniques to handle a bit more complex data, than the examples I have used before from sklearndata-set, using various features of pandas. This post will help you to arrange complex data-set dealing with real-life problems and eventually we will work our way through an example of logistic regression on the data. For more on data cleaning you can check this post.
You can download the data file from my github repository under the name βbank.csvβ or from the original source, where a detailed description of the data-set is available.
Before describing the data file, letβs import it and see the basic shape
import pandas as pdbankdf = pd.read_csv('bank.csv',sep=';') # check the csv file before to know that 'comma' here is ';'print bankdf.head(3)print list(bankdf.columns)# show the features and label print bankdf.shape # instances vs features + label (4521, 17)
Output is as below
From the output we see that the data-set has 16 feature and the label is designated with 'y' . A detailed description of the features are given in the main repository. The overview of the data-set as found in the main repository is
The data is related with direct marketing campaigns of a Portuguese banking institution. The marketing campaigns were based on phone calls. Often, more than one contact to the same client was required, in order to access if the product (bank term deposit) would be (βyesβ) or not (βnoβ) subscribed.
We can produce a seaborncount plot to see how the output is dominated by one of the classes.
import matplotlib.pyplot as pltimport seaborn as snssns.set(font_scale=1.5)countplt=sns.countplot(x='y', data=bankdf, palette ='hls')plt.show()
We can count the number with the snippet of a code below
count_no_sub = len(bankdf[bankdf['y']=='no'])print count_no_sub>>> 4000
Since the label of the data-set are given in terms of βyesβ and βnoβ, itβs necessary to replace them with numbers, possibly with 1 and 0 respectively, so that they can be used in modelling of the data. In the first step we will convert the output labels of the data-set from binary strings of yes/no to integers 1/0.
bankdf['y'] = (bankdf['y']=='yes').astype(int) # changing yes to 1 and no to 0print bankdf['y'].value_counts()>>> 0 4000 1 521Name: y, dtype: int64
Since the output labels are converted to integers now, we can use the groupbyfeature of pandas to investigate the data-set a bit more. Depending upon the output label (yes/no), we can see how the numbers in the features vary.
out_label = bankdf.groupby('y')print out_label.agg(np.mean)# above two lines can be written using a single line of code#print bankdf.groupby('y').mean()>>> age balance day duration campaign pdays previousy 0 40.99 1403.2117 15.948 226.347 2.862 36.006 0.471 1 42.49 1571.9558 15.658 552.742 2.266 68.639 1.090
First, here we see only 7 features out of 16, as the remaining features are objects and not integers or floats. You can check it typing bankdf.info(). We see that the feature βdurationβ, which tells us about the duration of the last call in seconds, is more than twice for the customers who bought the products than for customers who didnβt. βCampaignβ, which denotes the number of calls made during the current campaign, are lower for customers who purchased the products. groupby can give us some important information about the relationship between features and labels. Interested ones can check a similar βgroupbyβ operation on βeducationβ feature to verify that customers with tertiary education has the highest βbalanceβ (average yearly balance in Euros)!
Some of the features of the data-set have many categories which can be checked by using the uniquemethod of a series object. Examples are as below
print bankdf["education"].unique()print bankdf["marital"].unique()>>> ['primary' 'secondary' 'tertiary' 'unknown'] ['married' 'single' 'divorced']
These variables are known as categorical variables and in terms of pandas, these are called βobjectβ. To retrieve information using the categorical variables, we need to convert them into βdummyβ variables so that they can be used for modelling. We do that using pandas.get_dummies feature. First we create a list of the categorical variables
cat_list = ['job','marital','education','default','housing','loan','contact','month','poutcome']
Then we convert these variables into dummy variables as below
for ele in cat_list: add = pd.get_dummies(bankdf[ele], prefix=ele) bankdf1 = bankdf.join(add)# join columns with old dataframe bankdf = bankdf1#print bankdf.head(3)#print bankdf.info()
We have created dummy variables for each categorical variables and printing out the head of the new data-frame will result in as below
You can understand, how the categorical variables are converted to dummy variables which are ready to be used in the modelling of this data-set. But, we have a slight problem here. The actual categorical variables still exist and they need to be removed to make the data-frame ready for machine learning. We do that by first converting the column headers of the new data-frame to a list using tolist() attribute. Then we create a new list of column headers with no categorical variable and rename the headers. We do this using the following code
bank_vars = bankdf.columns.values.tolist() # column headers are converted into a listto_keep = [i for i in bank_vars if i not in cat_list] #create a new list by comparing with the list of categorical variables - 'cat_list'print to_keep # check the list of headers to make sure no categorical variable remains
We are ready to create a new data-frame with no categorical variables and we do this by -
bank_final = bankdf[to_keep]
Carefully note that to create the new data-frame, here we are passing a list (βto_keepβ) to the indexing operator (βbankdfβ). If you donβt pass the indexing operator a list of column names it will return a keyerror . To select multiple columns as a data-frame, we should pass a list to the indexing operator. However you can select a single column as a βseriesβ and you can see it below
bank_final = bankdf[to_keep] # to_keep is a 'list'print type(bank_final) >>> <class 'pandas.core.frame.DataFrame'>bank_final = bankdf['age']print type(bank_final)>>> <class 'pandas.core.series.Series'>bank_final = bankdf['age','y']print type(bank_final)>>> KeyError: ('age', 'y')
We can verify the headers of the columns of the new data-frame bank-final.
print bank_final.columns.values>>> ['age' 'balance' 'day' 'duration' 'campaign' 'pdays' 'previous' 'y' 'job_admin.' 'job_blue-collar' 'job_entrepreneur' 'job_housemaid' 'job_management' 'job_retired' 'job_self-employed' 'job_services' 'job_student' 'job_technician' 'job_unemployed' 'job_unknown' 'marital_divorced' 'marital_married' 'marital_single' 'education_primary' 'education_secondary' 'education_tertiary' 'education_unknown' 'default_no' 'default_yes' 'housing_no' 'housing_yes' 'loan_no' 'loan_yes' 'contact_cellular' 'contact_telephone' 'contact_unknown' 'month_apr' 'month_aug' 'month_dec' 'month_feb' 'month_jan' 'month_jul' 'month_jun' 'month_mar' 'month_may' 'month_nov' 'month_oct' 'month_sep' 'poutcome_failure' 'poutcome_other' 'poutcome_success' 'poutcome_unknown']
We are in a position to separate feature variables and labels, so that itβs possible to test some machine learning algorithm on the data set. Selecting feature and label from this new data-frame is done using the code below
bank_final_vars=bank_final.columns.values.tolist()# just like before converting the headers into a listY = ['y']X = [i for i in bank_final_vars if i not in Y]
Since there are too many features, we can choose some of the most important features with Recursive Feature Elimination (RFE) under sklearn, which works in two steps. In my later posts I may discuss why feature selection is not possible with Logistic Regression but for now letβs use a RFE to select few of the important features. First the classifier is passed to RFE with number of features to be selected and then the fit method is called. This is depicted in the code below
model = LogisticRegression()rfe = RFE(model, 15) # we have selected here 15 features rfe = rfe.fit(bank_final[X], bank_final[Y])
We can use the support_ attribute to find which features are selected.
print rfe.support_>>> [False False False False False False False False False False False False True False False False False False False False True False False False False False True False False False False True False False True False False True False True True True True False False True True True False True True]
rfe.support_produces an array, where the features that are selected are labelled as True and you can see 15 of them, as we have selected best 15 features. Another attribute of RFE is ranking_ where the value 1 in the array will highlight the selected features.
print rfe.ranking_>>> [33 37 32 35 23 36 31 18 11 29 27 30 1 28 17 7 12 10 5 9 1 21 16 25 22 4 1 26 24 13 20 1 14 15 1 34 6 1 19 1 1 1 1 3 2 1 1 1 8 1 1]
We can explicitly print out the name of the features that are selected using RFE, with the code below
rfe_rankinglist = rfe.ranking_.tolist()selected_columns = []for im in range(len(X)): if rfe_rankinglist[im]==1: selected_columns.append(X[im]) print selected_columns>>> ['job_retired', 'marital_married', 'default_no', 'loan_yes', 'contact_unknown', 'month_dec', 'month_jan', 'month_jul', 'month_jun', 'month_mar', 'month_oct', 'month_sep', 'poutcome_failure', 'poutcome_success', 'poutcome_unknown']
Finally we can proceed with .fit() and .score() attributes to check how well the model performs.
On a separate post I will discuss in detail about the mathematics behind the Logistic Regression and we will see that Logistic regression cannot select the features, it just shrinks the coefficients of a linear model, similar to Ridge Regression. Below is the code that you can use to check the effect of feature selection. Here we have used the whole data-set, but best practice is to divide the data in training and test-set. As a mini exercise you can try this, and remember that the label of the data-set is highly skewed and using stratify can be a good idea. Good luck !
X_new = bank_final[selected_columns]Y = bank_final['y']X_old = bank_final[X]clasf = LogisticRegression()clasf_sel = LogisticRegression()clasf.fit(X_old,Y)clasf_sel.fit(X_new,Y)print "score using all features", clasf.score(X_old,Y)print "score using selected features", clasf_sel.score(X_new,Y)
So to conclude this post letβs summarize the most important points
We have learnt to use pandasto deal with some of the problems that a realistic data-set can have.
We have learnt to convert strings (βyesβ, βnoβ) to binary variables (1, 0).
How groupby attribute of a pandas data-frame can help us understand some of the key connections between features and labels.
Changing categorical variables to dummy variables and using them in modelling of the data-set.
How to select part of a data-frame by passing a list to the indexing operator.
Using RFE to select some of the main features of a complex data-set.
For more on data cleaning and processing, you can check my post on data handling using pandas. For more on using Pandas Groupby and Crosstab, you can check my Global Terrorism Data analysis post. Hopefully this post will help you to be bit-more confident in dealing with realistic data-set. Stay strong and happy. Cheers !!
|
[
{
"code": null,
"e": 569,
"s": 171,
"text": "Today we will see some essential techniques to handle a bit more complex data, than the examples I have used before from sklearndata-set, using various features of pandas. This post will help you to arrange complex data-set dealing with real-life problems and eventually we will work our way through an example of logistic regression on the data. For more on data cleaning you can check this post."
},
{
"code": null,
"e": 740,
"s": 569,
"text": "You can download the data file from my github repository under the name βbank.csvβ or from the original source, where a detailed description of the data-set is available."
},
{
"code": null,
"e": 813,
"s": 740,
"text": "Before describing the data file, letβs import it and see the basic shape"
},
{
"code": null,
"e": 1072,
"s": 813,
"text": "import pandas as pdbankdf = pd.read_csv('bank.csv',sep=';') # check the csv file before to know that 'comma' here is ';'print bankdf.head(3)print list(bankdf.columns)# show the features and label print bankdf.shape # instances vs features + label (4521, 17) "
},
{
"code": null,
"e": 1091,
"s": 1072,
"text": "Output is as below"
},
{
"code": null,
"e": 1323,
"s": 1091,
"text": "From the output we see that the data-set has 16 feature and the label is designated with 'y' . A detailed description of the features are given in the main repository. The overview of the data-set as found in the main repository is"
},
{
"code": null,
"e": 1622,
"s": 1323,
"text": "The data is related with direct marketing campaigns of a Portuguese banking institution. The marketing campaigns were based on phone calls. Often, more than one contact to the same client was required, in order to access if the product (bank term deposit) would be (βyesβ) or not (βnoβ) subscribed."
},
{
"code": null,
"e": 1715,
"s": 1622,
"text": "We can produce a seaborncount plot to see how the output is dominated by one of the classes."
},
{
"code": null,
"e": 1859,
"s": 1715,
"text": "import matplotlib.pyplot as pltimport seaborn as snssns.set(font_scale=1.5)countplt=sns.countplot(x='y', data=bankdf, palette ='hls')plt.show()"
},
{
"code": null,
"e": 1916,
"s": 1859,
"text": "We can count the number with the snippet of a code below"
},
{
"code": null,
"e": 1988,
"s": 1916,
"text": "count_no_sub = len(bankdf[bankdf['y']=='no'])print count_no_sub>>> 4000"
},
{
"code": null,
"e": 2305,
"s": 1988,
"text": "Since the label of the data-set are given in terms of βyesβ and βnoβ, itβs necessary to replace them with numbers, possibly with 1 and 0 respectively, so that they can be used in modelling of the data. In the first step we will convert the output labels of the data-set from binary strings of yes/no to integers 1/0."
},
{
"code": null,
"e": 2464,
"s": 2305,
"text": "bankdf['y'] = (bankdf['y']=='yes').astype(int) # changing yes to 1 and no to 0print bankdf['y'].value_counts()>>> 0 4000 1 521Name: y, dtype: int64"
},
{
"code": null,
"e": 2690,
"s": 2464,
"text": "Since the output labels are converted to integers now, we can use the groupbyfeature of pandas to investigate the data-set a bit more. Depending upon the output label (yes/no), we can see how the numbers in the features vary."
},
{
"code": null,
"e": 3084,
"s": 2690,
"text": "out_label = bankdf.groupby('y')print out_label.agg(np.mean)# above two lines can be written using a single line of code#print bankdf.groupby('y').mean()>>> age balance day duration campaign pdays previousy 0 40.99 1403.2117 15.948 226.347 2.862 36.006 0.471 1 42.49 1571.9558 15.658 552.742 2.266 68.639 1.090"
},
{
"code": null,
"e": 3846,
"s": 3084,
"text": "First, here we see only 7 features out of 16, as the remaining features are objects and not integers or floats. You can check it typing bankdf.info(). We see that the feature βdurationβ, which tells us about the duration of the last call in seconds, is more than twice for the customers who bought the products than for customers who didnβt. βCampaignβ, which denotes the number of calls made during the current campaign, are lower for customers who purchased the products. groupby can give us some important information about the relationship between features and labels. Interested ones can check a similar βgroupbyβ operation on βeducationβ feature to verify that customers with tertiary education has the highest βbalanceβ (average yearly balance in Euros)!"
},
{
"code": null,
"e": 3993,
"s": 3846,
"text": "Some of the features of the data-set have many categories which can be checked by using the uniquemethod of a series object. Examples are as below"
},
{
"code": null,
"e": 4143,
"s": 3993,
"text": "print bankdf[\"education\"].unique()print bankdf[\"marital\"].unique()>>> ['primary' 'secondary' 'tertiary' 'unknown'] ['married' 'single' 'divorced']"
},
{
"code": null,
"e": 4486,
"s": 4143,
"text": "These variables are known as categorical variables and in terms of pandas, these are called βobjectβ. To retrieve information using the categorical variables, we need to convert them into βdummyβ variables so that they can be used for modelling. We do that using pandas.get_dummies feature. First we create a list of the categorical variables"
},
{
"code": null,
"e": 4583,
"s": 4486,
"text": "cat_list = ['job','marital','education','default','housing','loan','contact','month','poutcome']"
},
{
"code": null,
"e": 4645,
"s": 4583,
"text": "Then we convert these variables into dummy variables as below"
},
{
"code": null,
"e": 4830,
"s": 4645,
"text": "for ele in cat_list: add = pd.get_dummies(bankdf[ele], prefix=ele) bankdf1 = bankdf.join(add)# join columns with old dataframe bankdf = bankdf1#print bankdf.head(3)#print bankdf.info()"
},
{
"code": null,
"e": 4965,
"s": 4830,
"text": "We have created dummy variables for each categorical variables and printing out the head of the new data-frame will result in as below"
},
{
"code": null,
"e": 5511,
"s": 4965,
"text": "You can understand, how the categorical variables are converted to dummy variables which are ready to be used in the modelling of this data-set. But, we have a slight problem here. The actual categorical variables still exist and they need to be removed to make the data-frame ready for machine learning. We do that by first converting the column headers of the new data-frame to a list using tolist() attribute. Then we create a new list of column headers with no categorical variable and rename the headers. We do this using the following code"
},
{
"code": null,
"e": 5820,
"s": 5511,
"text": "bank_vars = bankdf.columns.values.tolist() # column headers are converted into a listto_keep = [i for i in bank_vars if i not in cat_list] #create a new list by comparing with the list of categorical variables - 'cat_list'print to_keep # check the list of headers to make sure no categorical variable remains"
},
{
"code": null,
"e": 5910,
"s": 5820,
"text": "We are ready to create a new data-frame with no categorical variables and we do this by -"
},
{
"code": null,
"e": 5939,
"s": 5910,
"text": "bank_final = bankdf[to_keep]"
},
{
"code": null,
"e": 6326,
"s": 5939,
"text": "Carefully note that to create the new data-frame, here we are passing a list (βto_keepβ) to the indexing operator (βbankdfβ). If you donβt pass the indexing operator a list of column names it will return a keyerror . To select multiple columns as a data-frame, we should pass a list to the indexing operator. However you can select a single column as a βseriesβ and you can see it below"
},
{
"code": null,
"e": 6606,
"s": 6326,
"text": "bank_final = bankdf[to_keep] # to_keep is a 'list'print type(bank_final) >>> <class 'pandas.core.frame.DataFrame'>bank_final = bankdf['age']print type(bank_final)>>> <class 'pandas.core.series.Series'>bank_final = bankdf['age','y']print type(bank_final)>>> KeyError: ('age', 'y')"
},
{
"code": null,
"e": 6681,
"s": 6606,
"text": "We can verify the headers of the columns of the new data-frame bank-final."
},
{
"code": null,
"e": 7466,
"s": 6681,
"text": "print bank_final.columns.values>>> ['age' 'balance' 'day' 'duration' 'campaign' 'pdays' 'previous' 'y' 'job_admin.' 'job_blue-collar' 'job_entrepreneur' 'job_housemaid' 'job_management' 'job_retired' 'job_self-employed' 'job_services' 'job_student' 'job_technician' 'job_unemployed' 'job_unknown' 'marital_divorced' 'marital_married' 'marital_single' 'education_primary' 'education_secondary' 'education_tertiary' 'education_unknown' 'default_no' 'default_yes' 'housing_no' 'housing_yes' 'loan_no' 'loan_yes' 'contact_cellular' 'contact_telephone' 'contact_unknown' 'month_apr' 'month_aug' 'month_dec' 'month_feb' 'month_jan' 'month_jul' 'month_jun' 'month_mar' 'month_may' 'month_nov' 'month_oct' 'month_sep' 'poutcome_failure' 'poutcome_other' 'poutcome_success' 'poutcome_unknown']"
},
{
"code": null,
"e": 7690,
"s": 7466,
"text": "We are in a position to separate feature variables and labels, so that itβs possible to test some machine learning algorithm on the data set. Selecting feature and label from this new data-frame is done using the code below"
},
{
"code": null,
"e": 7849,
"s": 7690,
"text": "bank_final_vars=bank_final.columns.values.tolist()# just like before converting the headers into a listY = ['y']X = [i for i in bank_final_vars if i not in Y]"
},
{
"code": null,
"e": 8327,
"s": 7849,
"text": "Since there are too many features, we can choose some of the most important features with Recursive Feature Elimination (RFE) under sklearn, which works in two steps. In my later posts I may discuss why feature selection is not possible with Logistic Regression but for now letβs use a RFE to select few of the important features. First the classifier is passed to RFE with number of features to be selected and then the fit method is called. This is depicted in the code below"
},
{
"code": null,
"e": 8456,
"s": 8327,
"text": "model = LogisticRegression()rfe = RFE(model, 15) # we have selected here 15 features rfe = rfe.fit(bank_final[X], bank_final[Y])"
},
{
"code": null,
"e": 8527,
"s": 8456,
"text": "We can use the support_ attribute to find which features are selected."
},
{
"code": null,
"e": 8856,
"s": 8527,
"text": "print rfe.support_>>> [False False False False False False False False False False False False True False False False False False False False True False False False False False True False False False False True False False True False False True False True True True True False False True True True False True True]"
},
{
"code": null,
"e": 9117,
"s": 8856,
"text": "rfe.support_produces an array, where the features that are selected are labelled as True and you can see 15 of them, as we have selected best 15 features. Another attribute of RFE is ranking_ where the value 1 in the array will highlight the selected features."
},
{
"code": null,
"e": 9293,
"s": 9117,
"text": "print rfe.ranking_>>> [33 37 32 35 23 36 31 18 11 29 27 30 1 28 17 7 12 10 5 9 1 21 16 25 22 4 1 26 24 13 20 1 14 15 1 34 6 1 19 1 1 1 1 3 2 1 1 1 8 1 1]"
},
{
"code": null,
"e": 9395,
"s": 9293,
"text": "We can explicitly print out the name of the features that are selected using RFE, with the code below"
},
{
"code": null,
"e": 9796,
"s": 9395,
"text": "rfe_rankinglist = rfe.ranking_.tolist()selected_columns = []for im in range(len(X)): if rfe_rankinglist[im]==1: selected_columns.append(X[im]) print selected_columns>>> ['job_retired', 'marital_married', 'default_no', 'loan_yes', 'contact_unknown', 'month_dec', 'month_jan', 'month_jul', 'month_jun', 'month_mar', 'month_oct', 'month_sep', 'poutcome_failure', 'poutcome_success', 'poutcome_unknown']"
},
{
"code": null,
"e": 9893,
"s": 9796,
"text": "Finally we can proceed with .fit() and .score() attributes to check how well the model performs."
},
{
"code": null,
"e": 10470,
"s": 9893,
"text": "On a separate post I will discuss in detail about the mathematics behind the Logistic Regression and we will see that Logistic regression cannot select the features, it just shrinks the coefficients of a linear model, similar to Ridge Regression. Below is the code that you can use to check the effect of feature selection. Here we have used the whole data-set, but best practice is to divide the data in training and test-set. As a mini exercise you can try this, and remember that the label of the data-set is highly skewed and using stratify can be a good idea. Good luck !"
},
{
"code": null,
"e": 10764,
"s": 10470,
"text": "X_new = bank_final[selected_columns]Y = bank_final['y']X_old = bank_final[X]clasf = LogisticRegression()clasf_sel = LogisticRegression()clasf.fit(X_old,Y)clasf_sel.fit(X_new,Y)print \"score using all features\", clasf.score(X_old,Y)print \"score using selected features\", clasf_sel.score(X_new,Y)"
},
{
"code": null,
"e": 10831,
"s": 10764,
"text": "So to conclude this post letβs summarize the most important points"
},
{
"code": null,
"e": 10929,
"s": 10831,
"text": "We have learnt to use pandasto deal with some of the problems that a realistic data-set can have."
},
{
"code": null,
"e": 11005,
"s": 10929,
"text": "We have learnt to convert strings (βyesβ, βnoβ) to binary variables (1, 0)."
},
{
"code": null,
"e": 11130,
"s": 11005,
"text": "How groupby attribute of a pandas data-frame can help us understand some of the key connections between features and labels."
},
{
"code": null,
"e": 11225,
"s": 11130,
"text": "Changing categorical variables to dummy variables and using them in modelling of the data-set."
},
{
"code": null,
"e": 11304,
"s": 11225,
"text": "How to select part of a data-frame by passing a list to the indexing operator."
},
{
"code": null,
"e": 11373,
"s": 11304,
"text": "Using RFE to select some of the main features of a complex data-set."
}
] |
How to Permanently Disable Swap in Linux? - GeeksforGeeks
|
08 Oct, 2021
Swapping or swapping space is a physical memory page placed at the top of a disk partition or a special disk file that is used to expand a systemβs RAM as the physical memory fills up. Inactive memory pages are often dumped into the swap area when no RAM is available, using this method of expanding RAM resources. However, swap space is much lower in transfer speeds and access time compared to RAM, due to the spinning speed of standard hard disks.
Reserving a small partition for swapping will significantly increase access time and speed transfer compared to conventional HDD on newer machines with fast SSD hard drives, but the speed is still lower than RAM memory. Some say that it is appropriate to set the swap space to twice the amount of computer RAM. However, swap space should be set to 2 or 4 GB on systems with more than 4 GB of RAM.
If your server has sufficient RAM memory or does not need the use of swap space or your device output is significantly reduced by swapping, you can consider disabling the swap field.
You first need to visualize your degree of memory load before actually disabling swap space, and then identify the partition that holds the swap area by issuing the commands below.
free -h
Look for the Used Swap Space size. If 0B or close to 0 bytes is the size used, it can be assumed that swap space is not used intensively and can be disabled for protection.
Next, check for TYPE=βswapβ line after the blkid command to define the swap partition, as shown in the screenshot below.
blkid
check swap partition type
Again, issue the following lsblk command to search and identify the [SWAP] partition as shown in the below screenshot.
lsblk
Search Confirm Swap Partition
Run the below command to deactivate the swap area after you have identified the swap partition or file.
swapoff /dev/mapper/centos-swap
Or disable all swaps from /proc/swaps.
swapoff -a
To check if the swap area has been disabled, run the free command.
free -h
Disable Swap Partition
To permanently disable Linux swap space, open the /etc/fstab file, search for a swap line and add a # (hashtag) sign in front of the line to comment on the entire line, as shown in the screenshot below.
vi /etc/fstab
Afterwards, reboot the system in order to apply the new swap setting or issuing mount -a command in some cases might do the trick.
mount -a
After a system reboot, the commands presented at the beginning of this tutorial should be issued to indicate that the swap area in your system has been completely and permanently disabled.
free -h
blkid
lsblk
In simple ways or the other step:
If you really want to disable swapping (note: this is not suggested, even if youβre pretty sure thereβs more than enough physical RAM), follow these steps:
Run swapoff -a: this will immediately disable the swap.
Remove any swap entry from /etc/fstab.
Get the system rebooted. Ok, if the swap is gone. If itβs still here for some reason, you have to remove the swap partition.
Repeat steps 1 and 2 and, after that, use fdisk or parted to delete the (now unused) swap partition. Use great caution here: removing the wrong partition would have devastating results!
sooda367
Picked
Technical Scripter 2020
How To
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install FFmpeg on Windows?
How to Install Jupyter Notebook on MacOS?
How to Install Flutter on Visual Studio Code?
How to Override compareTo Method in Java?
How to Install Python Pandas on MacOS?
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
TCP Server-Client implementation in C
cut command in Linux with examples
|
[
{
"code": null,
"e": 24898,
"s": 24870,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 25349,
"s": 24898,
"text": "Swapping or swapping space is a physical memory page placed at the top of a disk partition or a special disk file that is used to expand a systemβs RAM as the physical memory fills up. Inactive memory pages are often dumped into the swap area when no RAM is available, using this method of expanding RAM resources. However, swap space is much lower in transfer speeds and access time compared to RAM, due to the spinning speed of standard hard disks."
},
{
"code": null,
"e": 25746,
"s": 25349,
"text": "Reserving a small partition for swapping will significantly increase access time and speed transfer compared to conventional HDD on newer machines with fast SSD hard drives, but the speed is still lower than RAM memory. Some say that it is appropriate to set the swap space to twice the amount of computer RAM. However, swap space should be set to 2 or 4 GB on systems with more than 4 GB of RAM."
},
{
"code": null,
"e": 25929,
"s": 25746,
"text": "If your server has sufficient RAM memory or does not need the use of swap space or your device output is significantly reduced by swapping, you can consider disabling the swap field."
},
{
"code": null,
"e": 26110,
"s": 25929,
"text": "You first need to visualize your degree of memory load before actually disabling swap space, and then identify the partition that holds the swap area by issuing the commands below."
},
{
"code": null,
"e": 26119,
"s": 26110,
"text": "free -h "
},
{
"code": null,
"e": 26292,
"s": 26119,
"text": "Look for the Used Swap Space size. If 0B or close to 0 bytes is the size used, it can be assumed that swap space is not used intensively and can be disabled for protection."
},
{
"code": null,
"e": 26413,
"s": 26292,
"text": "Next, check for TYPE=βswapβ line after the blkid command to define the swap partition, as shown in the screenshot below."
},
{
"code": null,
"e": 26419,
"s": 26413,
"text": "blkid"
},
{
"code": null,
"e": 26445,
"s": 26419,
"text": "check swap partition type"
},
{
"code": null,
"e": 26564,
"s": 26445,
"text": "Again, issue the following lsblk command to search and identify the [SWAP] partition as shown in the below screenshot."
},
{
"code": null,
"e": 26570,
"s": 26564,
"text": "lsblk"
},
{
"code": null,
"e": 26601,
"s": 26570,
"text": "Search Confirm Swap Partition "
},
{
"code": null,
"e": 26705,
"s": 26601,
"text": "Run the below command to deactivate the swap area after you have identified the swap partition or file."
},
{
"code": null,
"e": 26738,
"s": 26705,
"text": "swapoff /dev/mapper/centos-swap "
},
{
"code": null,
"e": 26777,
"s": 26738,
"text": "Or disable all swaps from /proc/swaps."
},
{
"code": null,
"e": 26789,
"s": 26777,
"text": "swapoff -a "
},
{
"code": null,
"e": 26856,
"s": 26789,
"text": "To check if the swap area has been disabled, run the free command."
},
{
"code": null,
"e": 26864,
"s": 26856,
"text": "free -h"
},
{
"code": null,
"e": 26887,
"s": 26864,
"text": "Disable Swap Partition"
},
{
"code": null,
"e": 27090,
"s": 26887,
"text": "To permanently disable Linux swap space, open the /etc/fstab file, search for a swap line and add a # (hashtag) sign in front of the line to comment on the entire line, as shown in the screenshot below."
},
{
"code": null,
"e": 27104,
"s": 27090,
"text": "vi /etc/fstab"
},
{
"code": null,
"e": 27235,
"s": 27104,
"text": "Afterwards, reboot the system in order to apply the new swap setting or issuing mount -a command in some cases might do the trick."
},
{
"code": null,
"e": 27244,
"s": 27235,
"text": "mount -a"
},
{
"code": null,
"e": 27433,
"s": 27244,
"text": "After a system reboot, the commands presented at the beginning of this tutorial should be issued to indicate that the swap area in your system has been completely and permanently disabled."
},
{
"code": null,
"e": 27456,
"s": 27433,
"text": "free -h\nblkid \nlsblk "
},
{
"code": null,
"e": 27490,
"s": 27456,
"text": "In simple ways or the other step:"
},
{
"code": null,
"e": 27646,
"s": 27490,
"text": "If you really want to disable swapping (note: this is not suggested, even if youβre pretty sure thereβs more than enough physical RAM), follow these steps:"
},
{
"code": null,
"e": 27702,
"s": 27646,
"text": "Run swapoff -a: this will immediately disable the swap."
},
{
"code": null,
"e": 27741,
"s": 27702,
"text": "Remove any swap entry from /etc/fstab."
},
{
"code": null,
"e": 27866,
"s": 27741,
"text": "Get the system rebooted. Ok, if the swap is gone. If itβs still here for some reason, you have to remove the swap partition."
},
{
"code": null,
"e": 28052,
"s": 27866,
"text": "Repeat steps 1 and 2 and, after that, use fdisk or parted to delete the (now unused) swap partition. Use great caution here: removing the wrong partition would have devastating results!"
},
{
"code": null,
"e": 28061,
"s": 28052,
"text": "sooda367"
},
{
"code": null,
"e": 28068,
"s": 28061,
"text": "Picked"
},
{
"code": null,
"e": 28092,
"s": 28068,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28099,
"s": 28092,
"text": "How To"
},
{
"code": null,
"e": 28110,
"s": 28099,
"text": "Linux-Unix"
},
{
"code": null,
"e": 28129,
"s": 28110,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28227,
"s": 28129,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28236,
"s": 28227,
"text": "Comments"
},
{
"code": null,
"e": 28249,
"s": 28236,
"text": "Old Comments"
},
{
"code": null,
"e": 28283,
"s": 28249,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 28325,
"s": 28283,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 28371,
"s": 28325,
"text": "How to Install Flutter on Visual Studio Code?"
},
{
"code": null,
"e": 28413,
"s": 28371,
"text": "How to Override compareTo Method in Java?"
},
{
"code": null,
"e": 28452,
"s": 28413,
"text": "How to Install Python Pandas on MacOS?"
},
{
"code": null,
"e": 28492,
"s": 28452,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 28532,
"s": 28492,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 28559,
"s": 28532,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 28597,
"s": 28559,
"text": "TCP Server-Client implementation in C"
}
] |
Program for incrementing/decrementing triangle pattern - GeeksforGeeks
|
14 May, 2021
Numeric incrementing triangle pattern Write a program to print a Numeric incrementing triangle pattern starting with a given number N.Examples:
Input : 3
Output : 3
4 5
6 7 8
4 5
3
Given below is the implementation for the above-stated problem.
C++
Java
Python 3
C#
PHP
Javascript
#include <iostream>using namespace std;int main(){ int i, j, r, N, count; N = 3; // initializing N N--; r = 5; for (i = 0; i < r; i++) { if (i <= r / 2) { count = N + 1; for (j = 0; j <= i; j++) { N++; cout << N << " "; } cout << endl; } else { N = count - (r - i); count = N; for (j = i; j < r; j++) { cout << N << " "; N++; } cout << endl; } }}
// Java Program for incrementing// or decrementing triangle patternimport java.io.*; class GFG{public static void main(String args[]){ int i, j, r, N, count = 0; N = 3; // initializing N N--; r = 5; for (i = 0; i < r; i++) { if (i <= r / 2) { count = N + 1; for (j = 0; j <= i; j++) { N++; System.out.print(N + " "); } System.out.println(); } else { N = count - (r - i); count = N; for (j = i; j < r; j++) { System.out.print(N + " "); N++; } System.out.println(); } }}} // This code is contributed// by Subhadeep Gupta
# python 3 program to print incrementing# and decrementing triangle patternif __name__ == "__main__": N = 3 # initializing N N -= 1 r = 5 for i in range( r): if i <= r // 2: count = N + 1 for j in range(i + 1): N += 1 print(str(N), end = " ") print() else : N = count - (r - i) count = N for j in range(i, r): print(str(N), end = " ") N += 1 print() # This code is contributed# by ChitraNayal
// C# Program for incrementing// or decrementing triangle patternusing System; class GFG{public static void Main(){ int i, j, r, N, count = 0; N = 3; // initializing N N--; r = 5; for (i = 0; i < r; i++) { if (i <= r / 2) { count = N + 1; for (j = 0; j <= i; j++) { N++; Console.Write(N + " "); } Console.Write("\n"); } else { N = count - (r - i); count = N; for (j = i; j < r; j++) { Console.Write(N + " "); N++; } Console.Write("\n"); } }}} // This code is contributed// by ChitraNayal
<?php// PHP program for incrementing// or decrementing triangle pattern$N = 3; // initializing N$N--;$r = 5;for ($i = 0; $i < $r; $i++){if ($i <= $r / 2){ $count = $N + 1; for ($j = 0; $j <= $i; $j++) { $N++; echo $N . " "; } echo "\n";}else{ $N = $count - ($r - $i); $count = $N; for ($j = $i; $j < $r; $j++) { echo $N . " "; $N++; } echo "\n";}} // This code is contributed// by ChitraNayal?>
<script> var i, j, r, N, count; N = 3; // initializing N N--; r = 5; for (i = 0; i < r; i++) { if (i <= r / 2) { count = N + 1; for (j = 0; j <= i; j++) { N++; document.write(N + " "); } document.write("<br>"); } else { N = count - (r - i); count = N; for (j = i; j < r; j++) { document.write(N + " "); N++; } document.write("<br>"); } } </script>
3
4 5
6 7 8
4 5
3
Numeric decrementing triangle pattern Write a program to print a Numeric decrementing triangle pattern starting with a given number N.Examples:
Input : 3
Output : 3
5 4
8 7 6
5 4
3
Given below is the implementation for the above-stated problem.
C++
Java
Python 3
C#
PHP
Javascript
#include <iostream>using namespace std;int main(){ int i, j, r, N, N1; N1 = 3; N = 0; r = 5; for (i = 0; i < r; i++) { if (i <= r / 2) { N = N1; for (j = 0; j <= i; j++) { N++; } N1 = N; for (j = 0; j <= i; j++) { N--; cout << N << " "; } cout << endl; } else { for (j = i; j < r; j++) { N--; cout << N << " "; } cout << endl; } }}
// Java program for incrementing// and decrementing triangle patternclass GFG{public static void main(String[] args){ int i, j, r, N, N1; N1 = 3; N = 0; r = 5; for (i = 0; i < r; i++) { if (i <= r / 2) { N = N1; for (j = 0; j <= i; j++) { N++; } N1 = N; for (j = 0; j <= i; j++) { N--; System.out.print(N + " "); } System.out.println(); } else { for (j = i; j < r; j++) { N--; System.out.print(N + " "); } System.out.println(); } }}}; // This code is contributed// by ChitraNayal
# python 3 program for incrementing# and decrementing triangle patternif __name__ == "__main__": N1 = 3 N = 0; r = 5; for i in range( r): if i <= r // 2: N = N1 for j in range(i + 1): N += 1 N1 = N for j in range(i + 1): N -= 1 print(N, end = " ") print() else : for j in range(i, r): N -= 1 print(N, end = " ") print() # This code is contributed# by ChitraNayal
// C# program for incrementing// and decrementing triangle patternusing System; class GFG{public static void Main(){ int i, j, r, N, N1; N1 = 3; N = 0; r = 5; for (i = 0; i < r; i++) { if (i <= r / 2) { N = N1; for (j = 0; j <= i; j++) { N++; } N1 = N; for (j = 0; j <= i; j++) { N--; Console.Write(N + " "); } Console.Write("\n"); } else { for (j = i; j < r; j++) { N--; Console.Write(N + " "); } Console.Write("\n"); } }}}; // This code is contributed// by ChitraNayal
<?php// PHP program for incrementing// and decrementing triangle pattern$N1 = 3;$N = 0;$r = 5;for ($i = 0; $i < $r; $i++){ if ($i <= $r / 2) { $N = $N1; for ($j = 0; $j <= $i; $j++) { $N++; } $N1 = $N; for ($j = 0; $j <= $i; $j++) { $N--; echo $N ." "; } echo "\n"; } else { for ($j = $i; $j < $r; $j++) { $N--; echo $N ." "; } echo "\n"; }} // This code is contributed// by ChitraNayal?>
<script>// Javascript program for incrementing// and decrementing triangle pattern let i, j, r, N, N1; N1 = 3; N = 0; r = 5; for (i = 0; i < r; i++) { if (i <= r / 2) { N = N1; for (j = 0; j <= i; j++) { N++; } N1 = N; for (j = 0; j <= i; j++) { N--; document.write(N + " "); } document.write("<br>"); } else { for (j = i; j < r; j++) { N--; document.write(N + " "); } document.write("<br>"); } } // This code is contributed by avanitrachhadiya2155</script>
3
5 4
8 7 6
5 4
3
tufan_gupta2000
ukasp
ManasChhabra2
rdtank
avanitrachhadiya2155
pattern-printing
triangle
School Programming
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Exceptions in Java
Ternary Operator in Python
Inline Functions in C++
Difference between Abstract Class and Interface in Java
Exception Handling in C++
Destructors in C++
Python Exception Handling
'this' pointer in C++
Python program to add two numbers
|
[
{
"code": null,
"e": 24126,
"s": 24098,
"text": "\n14 May, 2021"
},
{
"code": null,
"e": 24272,
"s": 24126,
"text": "Numeric incrementing triangle pattern Write a program to print a Numeric incrementing triangle pattern starting with a given number N.Examples: "
},
{
"code": null,
"e": 24350,
"s": 24272,
"text": "Input : 3\nOutput : 3 \n 4 5 \n 6 7 8 \n 4 5 \n 3 "
},
{
"code": null,
"e": 24416,
"s": 24350,
"text": "Given below is the implementation for the above-stated problem. "
},
{
"code": null,
"e": 24420,
"s": 24416,
"text": "C++"
},
{
"code": null,
"e": 24425,
"s": 24420,
"text": "Java"
},
{
"code": null,
"e": 24434,
"s": 24425,
"text": "Python 3"
},
{
"code": null,
"e": 24437,
"s": 24434,
"text": "C#"
},
{
"code": null,
"e": 24441,
"s": 24437,
"text": "PHP"
},
{
"code": null,
"e": 24452,
"s": 24441,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std;int main(){ int i, j, r, N, count; N = 3; // initializing N N--; r = 5; for (i = 0; i < r; i++) { if (i <= r / 2) { count = N + 1; for (j = 0; j <= i; j++) { N++; cout << N << \" \"; } cout << endl; } else { N = count - (r - i); count = N; for (j = i; j < r; j++) { cout << N << \" \"; N++; } cout << endl; } }}",
"e": 25004,
"s": 24452,
"text": null
},
{
"code": "// Java Program for incrementing// or decrementing triangle patternimport java.io.*; class GFG{public static void main(String args[]){ int i, j, r, N, count = 0; N = 3; // initializing N N--; r = 5; for (i = 0; i < r; i++) { if (i <= r / 2) { count = N + 1; for (j = 0; j <= i; j++) { N++; System.out.print(N + \" \"); } System.out.println(); } else { N = count - (r - i); count = N; for (j = i; j < r; j++) { System.out.print(N + \" \"); N++; } System.out.println(); } }}} // This code is contributed// by Subhadeep Gupta",
"e": 25767,
"s": 25004,
"text": null
},
{
"code": "# python 3 program to print incrementing# and decrementing triangle patternif __name__ == \"__main__\": N = 3 # initializing N N -= 1 r = 5 for i in range( r): if i <= r // 2: count = N + 1 for j in range(i + 1): N += 1 print(str(N), end = \" \") print() else : N = count - (r - i) count = N for j in range(i, r): print(str(N), end = \" \") N += 1 print() # This code is contributed# by ChitraNayal",
"e": 26359,
"s": 25767,
"text": null
},
{
"code": "// C# Program for incrementing// or decrementing triangle patternusing System; class GFG{public static void Main(){ int i, j, r, N, count = 0; N = 3; // initializing N N--; r = 5; for (i = 0; i < r; i++) { if (i <= r / 2) { count = N + 1; for (j = 0; j <= i; j++) { N++; Console.Write(N + \" \"); } Console.Write(\"\\n\"); } else { N = count - (r - i); count = N; for (j = i; j < r; j++) { Console.Write(N + \" \"); N++; } Console.Write(\"\\n\"); } }}} // This code is contributed// by ChitraNayal",
"e": 27091,
"s": 26359,
"text": null
},
{
"code": "<?php// PHP program for incrementing// or decrementing triangle pattern$N = 3; // initializing N$N--;$r = 5;for ($i = 0; $i < $r; $i++){if ($i <= $r / 2){ $count = $N + 1; for ($j = 0; $j <= $i; $j++) { $N++; echo $N . \" \"; } echo \"\\n\";}else{ $N = $count - ($r - $i); $count = $N; for ($j = $i; $j < $r; $j++) { echo $N . \" \"; $N++; } echo \"\\n\";}} // This code is contributed// by ChitraNayal?>",
"e": 27547,
"s": 27091,
"text": null
},
{
"code": "<script> var i, j, r, N, count; N = 3; // initializing N N--; r = 5; for (i = 0; i < r; i++) { if (i <= r / 2) { count = N + 1; for (j = 0; j <= i; j++) { N++; document.write(N + \" \"); } document.write(\"<br>\"); } else { N = count - (r - i); count = N; for (j = i; j < r; j++) { document.write(N + \" \"); N++; } document.write(\"<br>\"); } } </script>",
"e": 28076,
"s": 27547,
"text": null
},
{
"code": null,
"e": 28100,
"s": 28078,
"text": "3 \n4 5 \n6 7 8 \n4 5 \n3"
},
{
"code": null,
"e": 28250,
"s": 28104,
"text": "Numeric decrementing triangle pattern Write a program to print a Numeric decrementing triangle pattern starting with a given number N.Examples: "
},
{
"code": null,
"e": 28328,
"s": 28250,
"text": "Input : 3\nOutput : 3 \n 5 4 \n 8 7 6 \n 5 4 \n 3 "
},
{
"code": null,
"e": 28394,
"s": 28328,
"text": "Given below is the implementation for the above-stated problem. "
},
{
"code": null,
"e": 28398,
"s": 28394,
"text": "C++"
},
{
"code": null,
"e": 28403,
"s": 28398,
"text": "Java"
},
{
"code": null,
"e": 28412,
"s": 28403,
"text": "Python 3"
},
{
"code": null,
"e": 28415,
"s": 28412,
"text": "C#"
},
{
"code": null,
"e": 28419,
"s": 28415,
"text": "PHP"
},
{
"code": null,
"e": 28430,
"s": 28419,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std;int main(){ int i, j, r, N, N1; N1 = 3; N = 0; r = 5; for (i = 0; i < r; i++) { if (i <= r / 2) { N = N1; for (j = 0; j <= i; j++) { N++; } N1 = N; for (j = 0; j <= i; j++) { N--; cout << N << \" \"; } cout << endl; } else { for (j = i; j < r; j++) { N--; cout << N << \" \"; } cout << endl; } }}",
"e": 28994,
"s": 28430,
"text": null
},
{
"code": "// Java program for incrementing// and decrementing triangle patternclass GFG{public static void main(String[] args){ int i, j, r, N, N1; N1 = 3; N = 0; r = 5; for (i = 0; i < r; i++) { if (i <= r / 2) { N = N1; for (j = 0; j <= i; j++) { N++; } N1 = N; for (j = 0; j <= i; j++) { N--; System.out.print(N + \" \"); } System.out.println(); } else { for (j = i; j < r; j++) { N--; System.out.print(N + \" \"); } System.out.println(); } }}}; // This code is contributed// by ChitraNayal",
"e": 29756,
"s": 28994,
"text": null
},
{
"code": "# python 3 program for incrementing# and decrementing triangle patternif __name__ == \"__main__\": N1 = 3 N = 0; r = 5; for i in range( r): if i <= r // 2: N = N1 for j in range(i + 1): N += 1 N1 = N for j in range(i + 1): N -= 1 print(N, end = \" \") print() else : for j in range(i, r): N -= 1 print(N, end = \" \") print() # This code is contributed# by ChitraNayal",
"e": 30334,
"s": 29756,
"text": null
},
{
"code": "// C# program for incrementing// and decrementing triangle patternusing System; class GFG{public static void Main(){ int i, j, r, N, N1; N1 = 3; N = 0; r = 5; for (i = 0; i < r; i++) { if (i <= r / 2) { N = N1; for (j = 0; j <= i; j++) { N++; } N1 = N; for (j = 0; j <= i; j++) { N--; Console.Write(N + \" \"); } Console.Write(\"\\n\"); } else { for (j = i; j < r; j++) { N--; Console.Write(N + \" \"); } Console.Write(\"\\n\"); } }}}; // This code is contributed// by ChitraNayal",
"e": 31087,
"s": 30334,
"text": null
},
{
"code": "<?php// PHP program for incrementing// and decrementing triangle pattern$N1 = 3;$N = 0;$r = 5;for ($i = 0; $i < $r; $i++){ if ($i <= $r / 2) { $N = $N1; for ($j = 0; $j <= $i; $j++) { $N++; } $N1 = $N; for ($j = 0; $j <= $i; $j++) { $N--; echo $N .\" \"; } echo \"\\n\"; } else { for ($j = $i; $j < $r; $j++) { $N--; echo $N .\" \"; } echo \"\\n\"; }} // This code is contributed// by ChitraNayal?>",
"e": 31617,
"s": 31087,
"text": null
},
{
"code": "<script>// Javascript program for incrementing// and decrementing triangle pattern let i, j, r, N, N1; N1 = 3; N = 0; r = 5; for (i = 0; i < r; i++) { if (i <= r / 2) { N = N1; for (j = 0; j <= i; j++) { N++; } N1 = N; for (j = 0; j <= i; j++) { N--; document.write(N + \" \"); } document.write(\"<br>\"); } else { for (j = i; j < r; j++) { N--; document.write(N + \" \"); } document.write(\"<br>\"); } } // This code is contributed by avanitrachhadiya2155</script>",
"e": 32353,
"s": 31617,
"text": null
},
{
"code": null,
"e": 32377,
"s": 32355,
"text": "3 \n5 4 \n8 7 6 \n5 4 \n3"
},
{
"code": null,
"e": 32397,
"s": 32381,
"text": "tufan_gupta2000"
},
{
"code": null,
"e": 32403,
"s": 32397,
"text": "ukasp"
},
{
"code": null,
"e": 32417,
"s": 32403,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 32424,
"s": 32417,
"text": "rdtank"
},
{
"code": null,
"e": 32445,
"s": 32424,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 32462,
"s": 32445,
"text": "pattern-printing"
},
{
"code": null,
"e": 32471,
"s": 32462,
"text": "triangle"
},
{
"code": null,
"e": 32490,
"s": 32471,
"text": "School Programming"
},
{
"code": null,
"e": 32507,
"s": 32490,
"text": "pattern-printing"
},
{
"code": null,
"e": 32605,
"s": 32507,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32614,
"s": 32605,
"text": "Comments"
},
{
"code": null,
"e": 32627,
"s": 32614,
"text": "Old Comments"
},
{
"code": null,
"e": 32648,
"s": 32627,
"text": "Constructors in Java"
},
{
"code": null,
"e": 32667,
"s": 32648,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 32694,
"s": 32667,
"text": "Ternary Operator in Python"
},
{
"code": null,
"e": 32718,
"s": 32694,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 32774,
"s": 32718,
"text": "Difference between Abstract Class and Interface in Java"
},
{
"code": null,
"e": 32800,
"s": 32774,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 32819,
"s": 32800,
"text": "Destructors in C++"
},
{
"code": null,
"e": 32845,
"s": 32819,
"text": "Python Exception Handling"
},
{
"code": null,
"e": 32867,
"s": 32845,
"text": "'this' pointer in C++"
}
] |
Configure exim4 smtp relay server
|
This article will guide you to configure Exim4 SMTP relay server which will allow you to relay emails for the know Domains names and IP address only. In general, this type of service is used to relay emails for notifications for the server health status reports, where the actual email address does not exist or send auto response emails.
Exim4 is a Message Transfer Agent (MTA) developed at the University of Cambridge for use on Unix systems connected to the internet. Exim4 can be installed to replace of Sendmail or Postfix, although the configuration of Exim4 is quite different to that of sendmail.
To install exim4, use the following command β
# hostname testserver.com
# sudo βi (to Enter with root permissions)
# apt-get update
# apt-get install exim4
The sample output should be like this β
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
exim4-base exim4-config exim4-daemon-light heirloom-mailx
Suggested packages:
mail-reader eximon4 exim4-doc-html exim4-doc-info spf-tools-perl swaks
Recommended packages:
mailx
The following NEW packages will be installed:
exim4 exim4-base exim4-config exim4-daemon-light heirloom-mailx
0 upgraded, 5 newly installed, 0 to remove and 66 not upgraded.
Need to get 1,862 kB of archives.
After this operation, 4,258 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://us.archive.ubuntu.com/ubuntu/ wily/main exim4-config all 4.86-3 ubuntu1 [299 kB]
Get:2 http://us.archive.ubuntu.com/ubuntu/ wily/main exim4-base amd64 4.86-3ubuntu1 [869 kB]
Get:3 http://us.archive.ubuntu.com/ubuntu/ wily/main exim4-daemon-light amd64 4.86-3ubuntu1 [465 kB]
Get:4 http://us.archive.ubuntu.com/ubuntu/ wily/main exim4 all 4.86-3ubuntu1 [7,916 B]
Get:5 http://us.archive.ubuntu.com/ubuntu/ wily/universe heirloom-mailx amd64 12.5-5 [221 kB]
Fetched 1,862 kB in 49s (37.7 kB/s)
Preconfiguring packages ...
Selecting previously unselected package exim4-config.
(Reading database ... 91615 files and directories currently installed.)
Preparing to unpack .../exim4-config_4.86-3ubuntu1_all.deb ...
Unpacking exim4-config (4.86-3ubuntu1) ...
................................................
We need to configure exim4 to relay the emails.
# dpkg-reconfigure exim4-config
The output should be like this β
Select βinternet site; mail is sent and received directly using SMTPβ option
Provide the server name for the Exim4 SMTP server. By default, it will take the hostname of the machine.
Provide the IP address from which you want to receive the request and send emails.
Here, you can give a semicolon-separated list of IP address for multiple IPβs.
Enter the domain address of the clientsβ recipient domains for which this SMTP will relay the mails.
Please note that, you can give a semicolon-separated list of domain address for multiple domains.
Enter a semicolon-separated list of IP address ranges for which this system will unconditionally relay mails. (Functioning as a smart host). This is generally the localhost which will be taken.
Select Keep number of DNS-queries minimal (Dial-on-Demand) to No ( previously, we used to have Dial-up connection, but currently most of the internet users are having broadband connections)
Select the delivery method for the local mailβs. Here, I have selected Maildir format in the home directory
Select Split configuration into small files? to No . If you are interested to store the configuration into small files, then you can choose YES
Now you are done and your SMTP servers which are ready to relay emails sent for any notifications. Use this machine IP or if registered domain then, use domain name in the SMTP server address in configurations.
After the configuration we can add the client using the same configuration command or we can directly edit the configuration file and add the additional client to use with this SMTP server.
Open the configuration file and edit or add the clients IP or domain names
# vi /etc/exim4/update-exim4.conf.conf
update-exim4.conf.conf file should be like this β
## Edit this file and /etc/mailname by hand and execute update-exim4.conf
# yourself or use 'dpkg-reconfigure exim4-config'#
# Please note that this is _not_ a dpkg-conffile and that automatically changes
# to this file might happen. The code handling this will honor your local
# changes, so this is usually fine, but will break local schemes that mess
# around with multiple versions of the file.
## update-exim4.conf uses this file to determine variable values to generate
# exim configuration macros for the configuration file.
## Most settings found in here do have corresponding questions in the
# Debconf configuration, but not all of them.
## This is a Debian specific file
dc_eximconfig_configtype='internet'
dc_other_hostnames='server.com'
dc_local_interfaces='127.0.0.1'
dc_readhost=''
dc_relay_domains='192.168.1.1'
dc_minimaldns='false'
dc_relay_nets='cgi.com'
dc_smarthost=''
CFILEMODE='644'
dc_use_split_config='false'
dc_hide_mailname=''
dc_mailname_in_oh='true'
dc_localdelivery='maildir_home'
Now, edit the following lines in the configuration with semicolon separated
dc_relay_nets are used to add the IP address of the client/servers
dc_relay_domains are used to add the domain names of the client/servers
After the successful configuration, you are allowed to use this server for sending or relaying emails from your servers and client for sending the notifications for your programs or projects.
|
[
{
"code": null,
"e": 1401,
"s": 1062,
"text": "This article will guide you to configure Exim4 SMTP relay server which will allow you to relay emails for the know Domains names and IP address only. In general, this type of service is used to relay emails for notifications for the server health status reports, where the actual email address does not exist or send auto response emails."
},
{
"code": null,
"e": 1667,
"s": 1401,
"text": "Exim4 is a Message Transfer Agent (MTA) developed at the University of Cambridge for use on Unix systems connected to the internet. Exim4 can be installed to replace of Sendmail or Postfix, although the configuration of Exim4 is quite different to that of sendmail."
},
{
"code": null,
"e": 1713,
"s": 1667,
"text": "To install exim4, use the following command β"
},
{
"code": null,
"e": 1823,
"s": 1713,
"text": "# hostname testserver.com\n# sudo βi (to Enter with root permissions)\n# apt-get update\n# apt-get install exim4"
},
{
"code": null,
"e": 1863,
"s": 1823,
"text": "The sample output should be like this β"
},
{
"code": null,
"e": 3302,
"s": 1863,
"text": "Reading package lists... Done\nBuilding dependency tree\nReading state information... Done\nThe following extra packages will be installed:\nexim4-base exim4-config exim4-daemon-light heirloom-mailx\nSuggested packages:\nmail-reader eximon4 exim4-doc-html exim4-doc-info spf-tools-perl swaks\nRecommended packages:\nmailx\nThe following NEW packages will be installed:\nexim4 exim4-base exim4-config exim4-daemon-light heirloom-mailx\n0 upgraded, 5 newly installed, 0 to remove and 66 not upgraded.\nNeed to get 1,862 kB of archives.\nAfter this operation, 4,258 kB of additional disk space will be used.\nDo you want to continue? [Y/n] y\nGet:1 http://us.archive.ubuntu.com/ubuntu/ wily/main exim4-config all 4.86-3 ubuntu1 [299 kB]\nGet:2 http://us.archive.ubuntu.com/ubuntu/ wily/main exim4-base amd64 4.86-3ubuntu1 [869 kB]\nGet:3 http://us.archive.ubuntu.com/ubuntu/ wily/main exim4-daemon-light amd64 4.86-3ubuntu1 [465 kB]\nGet:4 http://us.archive.ubuntu.com/ubuntu/ wily/main exim4 all 4.86-3ubuntu1 [7,916 B]\nGet:5 http://us.archive.ubuntu.com/ubuntu/ wily/universe heirloom-mailx amd64 12.5-5 [221 kB]\nFetched 1,862 kB in 49s (37.7 kB/s)\nPreconfiguring packages ...\nSelecting previously unselected package exim4-config.\n(Reading database ... 91615 files and directories currently installed.)\nPreparing to unpack .../exim4-config_4.86-3ubuntu1_all.deb ...\nUnpacking exim4-config (4.86-3ubuntu1) ...\n................................................"
},
{
"code": null,
"e": 3350,
"s": 3302,
"text": "We need to configure exim4 to relay the emails."
},
{
"code": null,
"e": 3382,
"s": 3350,
"text": "# dpkg-reconfigure exim4-config"
},
{
"code": null,
"e": 3415,
"s": 3382,
"text": "The output should be like this β"
},
{
"code": null,
"e": 3492,
"s": 3415,
"text": "Select βinternet site; mail is sent and received directly using SMTPβ option"
},
{
"code": null,
"e": 3597,
"s": 3492,
"text": "Provide the server name for the Exim4 SMTP server. By default, it will take the hostname of the machine."
},
{
"code": null,
"e": 3680,
"s": 3597,
"text": "Provide the IP address from which you want to receive the request and send emails."
},
{
"code": null,
"e": 3759,
"s": 3680,
"text": "Here, you can give a semicolon-separated list of IP address for multiple IPβs."
},
{
"code": null,
"e": 3860,
"s": 3759,
"text": "Enter the domain address of the clientsβ recipient domains for which this SMTP will relay the mails."
},
{
"code": null,
"e": 3958,
"s": 3860,
"text": "Please note that, you can give a semicolon-separated list of domain address for multiple domains."
},
{
"code": null,
"e": 4152,
"s": 3958,
"text": "Enter a semicolon-separated list of IP address ranges for which this system will unconditionally relay mails. (Functioning as a smart host). This is generally the localhost which will be taken."
},
{
"code": null,
"e": 4342,
"s": 4152,
"text": "Select Keep number of DNS-queries minimal (Dial-on-Demand) to No ( previously, we used to have Dial-up connection, but currently most of the internet users are having broadband connections)"
},
{
"code": null,
"e": 4450,
"s": 4342,
"text": "Select the delivery method for the local mailβs. Here, I have selected Maildir format in the home directory"
},
{
"code": null,
"e": 4594,
"s": 4450,
"text": "Select Split configuration into small files? to No . If you are interested to store the configuration into small files, then you can choose YES"
},
{
"code": null,
"e": 4805,
"s": 4594,
"text": "Now you are done and your SMTP servers which are ready to relay emails sent for any notifications. Use this machine IP or if registered domain then, use domain name in the SMTP server address in configurations."
},
{
"code": null,
"e": 4995,
"s": 4805,
"text": "After the configuration we can add the client using the same configuration command or we can directly edit the configuration file and add the additional client to use with this SMTP server."
},
{
"code": null,
"e": 5070,
"s": 4995,
"text": "Open the configuration file and edit or add the clients IP or domain names"
},
{
"code": null,
"e": 5109,
"s": 5070,
"text": "# vi /etc/exim4/update-exim4.conf.conf"
},
{
"code": null,
"e": 5159,
"s": 5109,
"text": "update-exim4.conf.conf file should be like this β"
},
{
"code": null,
"e": 6170,
"s": 5159,
"text": "## Edit this file and /etc/mailname by hand and execute update-exim4.conf\n# yourself or use 'dpkg-reconfigure exim4-config'#\n# Please note that this is _not_ a dpkg-conffile and that automatically changes\n# to this file might happen. The code handling this will honor your local\n# changes, so this is usually fine, but will break local schemes that mess\n# around with multiple versions of the file.\n## update-exim4.conf uses this file to determine variable values to generate\n# exim configuration macros for the configuration file.\n## Most settings found in here do have corresponding questions in the\n# Debconf configuration, but not all of them.\n## This is a Debian specific file\ndc_eximconfig_configtype='internet'\ndc_other_hostnames='server.com'\ndc_local_interfaces='127.0.0.1'\ndc_readhost=''\ndc_relay_domains='192.168.1.1'\ndc_minimaldns='false'\ndc_relay_nets='cgi.com'\ndc_smarthost=''\nCFILEMODE='644'\ndc_use_split_config='false'\ndc_hide_mailname=''\ndc_mailname_in_oh='true'\ndc_localdelivery='maildir_home'"
},
{
"code": null,
"e": 6246,
"s": 6170,
"text": "Now, edit the following lines in the configuration with semicolon separated"
},
{
"code": null,
"e": 6313,
"s": 6246,
"text": "dc_relay_nets are used to add the IP address of the client/servers"
},
{
"code": null,
"e": 6385,
"s": 6313,
"text": "dc_relay_domains are used to add the domain names of the client/servers"
},
{
"code": null,
"e": 6577,
"s": 6385,
"text": "After the successful configuration, you are allowed to use this server for sending or relaying emails from your servers and client for sending the notifications for your programs or projects."
}
] |
3D scatter plot using Plotly in Python - GeeksforGeeks
|
10 Jul, 2020
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
A scatterplot can be used with several semantic groupings which can help to understand well in a graph. They can plot two-dimensional graphics that can be enhanced by mapping up to three additional variables while using the semantics of hue, size, and style parameters. All the parameter control visual semantic which are used to identify the different subsets. Using redundant semantics can be helpful for making graphics more accessible. It can be created using the scatter_3d function of plotly.express class.
Syntax: plotly.express.scatter_3d(data_frame=None, x=None, y=None, z=None, color=None, symbol=None, size=None, text=None, hover_name=None, hover_data=None, custom_data=None, error_x=None, error_x_minus=None, error_y=None, error_y_minus=None, error_z=None, error_z_minus=None, animation_frame=None, animation_group=None, category_orders={}, labels={}, size_max=None, color_discrete_sequence=None, color_discrete_map={}, color_continuous_scale=None, range_color=None, color_continuous_midpoint=None, symbol_sequence=None, symbol_map={}, opacity=None, log_x=False, log_y=False, log_z=False, range_x=None, range_y=None, range_z=None, title=None, template=None, width=None, height=None)
Parameters:
data_frame (DataFrame or array-like or dict) β This argument needs to be passed for column names (and not keyword names) to be used.
x (str or int or Series or array-like) β Either a name of a column in data_frame, or a pandas Series or array_like object.
y (str or int or Series or array-like) β Either a name of a column in data_frame, or a pandas Series or array_like object.
color (str or int or Series or array-like) β Either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to assign color to marks.
Example 1: Using Iris Dataset
Python3
import plotly.express as px df = px.data.iris() fig = px.scatter_3d(df, x = 'sepal_width', y = 'sepal_length', z = 'petal_width', color = 'species') fig.show()
Output:
Example 2: Using tips dataset
Python3
import plotly.express as px df = px.data.tips() fig = px.scatter_3d(df, x = 'total_bill', y = 'day', z = 'time', color = 'sex') fig.show()
Output:
In Plotly, through the parameters of px.scatter_3d, it is possible to customize the style of the figure for some option.
Example 1: Using the Iris dataset.
Python3
import plotly.express as px df = px.data.iris() fig = px.scatter_3d(df, x = 'sepal_width', y = 'sepal_length', z = 'petal_width', color = 'species', size='petal_length', size_max = 20, opacity = 0.5) fig.show()
Output:
Example 2: Using tips dataset
Python3
import plotly.express as px df = px.data.tips() fig = px.scatter_3d(df, x = 'total_bill', y = 'day', z = 'time', color = 'sex', size='tip', size_max = 20, opacity = 0.7) fig.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24828,
"s": 24800,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 25130,
"s": 24828,
"text": "Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library."
},
{
"code": null,
"e": 25643,
"s": 25130,
"text": "A scatterplot can be used with several semantic groupings which can help to understand well in a graph. They can plot two-dimensional graphics that can be enhanced by mapping up to three additional variables while using the semantics of hue, size, and style parameters. All the parameter control visual semantic which are used to identify the different subsets. Using redundant semantics can be helpful for making graphics more accessible. It can be created using the scatter_3d function of plotly.express class."
},
{
"code": null,
"e": 26325,
"s": 25643,
"text": "Syntax: plotly.express.scatter_3d(data_frame=None, x=None, y=None, z=None, color=None, symbol=None, size=None, text=None, hover_name=None, hover_data=None, custom_data=None, error_x=None, error_x_minus=None, error_y=None, error_y_minus=None, error_z=None, error_z_minus=None, animation_frame=None, animation_group=None, category_orders={}, labels={}, size_max=None, color_discrete_sequence=None, color_discrete_map={}, color_continuous_scale=None, range_color=None, color_continuous_midpoint=None, symbol_sequence=None, symbol_map={}, opacity=None, log_x=False, log_y=False, log_z=False, range_x=None, range_y=None, range_z=None, title=None, template=None, width=None, height=None)"
},
{
"code": null,
"e": 26337,
"s": 26325,
"text": "Parameters:"
},
{
"code": null,
"e": 26471,
"s": 26337,
"text": "data_frame (DataFrame or array-like or dict) β This argument needs to be passed for column names (and not keyword names) to be used. "
},
{
"code": null,
"e": 26595,
"s": 26471,
"text": "x (str or int or Series or array-like) β Either a name of a column in data_frame, or a pandas Series or array_like object. "
},
{
"code": null,
"e": 26718,
"s": 26595,
"text": "y (str or int or Series or array-like) β Either a name of a column in data_frame, or a pandas Series or array_like object."
},
{
"code": null,
"e": 26918,
"s": 26718,
"text": "color (str or int or Series or array-like) β Either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to assign color to marks."
},
{
"code": null,
"e": 26948,
"s": 26918,
"text": "Example 1: Using Iris Dataset"
},
{
"code": null,
"e": 26956,
"s": 26948,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.iris() fig = px.scatter_3d(df, x = 'sepal_width', y = 'sepal_length', z = 'petal_width', color = 'species') fig.show()",
"e": 27178,
"s": 26956,
"text": null
},
{
"code": null,
"e": 27186,
"s": 27178,
"text": "Output:"
},
{
"code": null,
"e": 27216,
"s": 27186,
"text": "Example 2: Using tips dataset"
},
{
"code": null,
"e": 27224,
"s": 27216,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.tips() fig = px.scatter_3d(df, x = 'total_bill', y = 'day', z = 'time', color = 'sex') fig.show()",
"e": 27405,
"s": 27224,
"text": null
},
{
"code": null,
"e": 27413,
"s": 27405,
"text": "Output:"
},
{
"code": null,
"e": 27535,
"s": 27413,
"text": "In Plotly, through the parameters of px.scatter_3d, it is possible to customize the style of the figure for some option."
},
{
"code": null,
"e": 27570,
"s": 27535,
"text": "Example 1: Using the Iris dataset."
},
{
"code": null,
"e": 27578,
"s": 27570,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.iris() fig = px.scatter_3d(df, x = 'sepal_width', y = 'sepal_length', z = 'petal_width', color = 'species', size='petal_length', size_max = 20, opacity = 0.5) fig.show()",
"e": 27910,
"s": 27578,
"text": null
},
{
"code": null,
"e": 27918,
"s": 27910,
"text": "Output:"
},
{
"code": null,
"e": 27948,
"s": 27918,
"text": "Example 2: Using tips dataset"
},
{
"code": null,
"e": 27956,
"s": 27948,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.tips() fig = px.scatter_3d(df, x = 'total_bill', y = 'day', z = 'time', color = 'sex', size='tip', size_max = 20, opacity = 0.7) fig.show()",
"e": 28257,
"s": 27956,
"text": null
},
{
"code": null,
"e": 28265,
"s": 28257,
"text": "Output:"
},
{
"code": null,
"e": 28279,
"s": 28265,
"text": "Python-Plotly"
},
{
"code": null,
"e": 28286,
"s": 28279,
"text": "Python"
},
{
"code": null,
"e": 28384,
"s": 28286,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28393,
"s": 28384,
"text": "Comments"
},
{
"code": null,
"e": 28406,
"s": 28393,
"text": "Old Comments"
},
{
"code": null,
"e": 28424,
"s": 28406,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28456,
"s": 28424,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28491,
"s": 28456,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28513,
"s": 28491,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28543,
"s": 28513,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28585,
"s": 28543,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28628,
"s": 28585,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28665,
"s": 28628,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28691,
"s": 28665,
"text": "Python String | replace()"
}
] |
Jupyter Standalone Might Just Be Better Than Anaconda | by Emmett Boudreau | Towards Data Science
|
If youβve been in the data science space for even a fraction of a second, youβre probably well aware of Anaconda navigator, and Jupyter notebook. They are both great tools for data-scientists when they need cell-by-cell execution on a virtual kernel. But is it possible to drop Anaconda Navigator without dropping Jupyter?
At the roots of Anaconda is environment virtualization. Of course, this can be seen as a huge advantage to using Anaconda over standalone Jupyter. Additionally, Anaconda comes with the β Condaβ package manager, which isnβt quite as expansive as the regular Python Package Index.
As a result of these features, to an inexperienced soul, the startup learning curve of Anaconda Navigator isnβt as fierce as setting up docker images and virtual environments to run Jupyter out of. However, a significant disadvantage of Conda is the lack of the regular package index. Therefore, it is possible through only a pretty challenging loophole to install traditional Python packages that havenβt been published to Conda. For someone that uses a lot of APIs and assorted packages, this, of course, is a problem.
With that in mind, Anaconda certainly is a great tool for Data Scientists, with extension applications like VSCode, Spark managers, and much more all easily implemented into the navigator to work inside of your Conda terminal, itβs easy to see why this is a common choice among Windows developers. Interestingly, a lot of my Windows friends use their Conda REPL like a terminal, so the value is certainly there for them.
But with the ease of use on Windows with Anaconda, what is to come of the situation on operating systems where we already have a package manager and a terminal to push commands through? Well, for me personally, I much more prefer Jupyter SH, and hopefully I can justify myself in my pros and cons to this approach.
Although we all-in-all lose our Conda Environment, we retain any virtual environment we utilize when we launch from the terminal, so if I were to
$ - source env/bin/activate
and then run Jupyter Notebook,
$ (env) - jupyter notebook
I would retain my virtual env pip environment. For obvious reasons, this is a great way to manage your dependency ecosystem inside of Jupyter.
Another reason I love using Jupyter over Anaconda is folder selection, anytime a notebook is buried deep inside a maze of folders in your computer, it can be very hard to get said notebook open in Jupyter. Jupyterβs file interface isnβt exactly well known for being flawless in any sense of the word, although it certainly gets the job done. Using standalone Jupyter with SH, I can open a terminal in any location on my computer and type β Jupyter Notebook,β and already be navigated right to the file that I would like to tamper with.
I also am a strong Docker user, and using Conda with Docker can be quite a chore... However, setting up a completely virtual operating system running inside of regular Jupyter SH with Docker is fluid and super easy.
Although these opinions are certainly not universally agreed upon, I use Jupyter Standalone because I love the versatility. I appreciate Anaconda, and have no particular yield to installing it other than that I donβt need it. It doesnβt really matter how you go about installing Jupyter as long as you donβt do it through the snap package manager (it breaks everything.)
And with that in mind, Iβm curious as to how many people use Jupyter in standalone versus using it with Anaconda, and what their thoughts may be on the experience. They are both fantastic tools and illustrate that sometimes there are two completely different ways to do the exact same thing.
|
[
{
"code": null,
"e": 495,
"s": 172,
"text": "If youβve been in the data science space for even a fraction of a second, youβre probably well aware of Anaconda navigator, and Jupyter notebook. They are both great tools for data-scientists when they need cell-by-cell execution on a virtual kernel. But is it possible to drop Anaconda Navigator without dropping Jupyter?"
},
{
"code": null,
"e": 774,
"s": 495,
"text": "At the roots of Anaconda is environment virtualization. Of course, this can be seen as a huge advantage to using Anaconda over standalone Jupyter. Additionally, Anaconda comes with the β Condaβ package manager, which isnβt quite as expansive as the regular Python Package Index."
},
{
"code": null,
"e": 1295,
"s": 774,
"text": "As a result of these features, to an inexperienced soul, the startup learning curve of Anaconda Navigator isnβt as fierce as setting up docker images and virtual environments to run Jupyter out of. However, a significant disadvantage of Conda is the lack of the regular package index. Therefore, it is possible through only a pretty challenging loophole to install traditional Python packages that havenβt been published to Conda. For someone that uses a lot of APIs and assorted packages, this, of course, is a problem."
},
{
"code": null,
"e": 1716,
"s": 1295,
"text": "With that in mind, Anaconda certainly is a great tool for Data Scientists, with extension applications like VSCode, Spark managers, and much more all easily implemented into the navigator to work inside of your Conda terminal, itβs easy to see why this is a common choice among Windows developers. Interestingly, a lot of my Windows friends use their Conda REPL like a terminal, so the value is certainly there for them."
},
{
"code": null,
"e": 2031,
"s": 1716,
"text": "But with the ease of use on Windows with Anaconda, what is to come of the situation on operating systems where we already have a package manager and a terminal to push commands through? Well, for me personally, I much more prefer Jupyter SH, and hopefully I can justify myself in my pros and cons to this approach."
},
{
"code": null,
"e": 2177,
"s": 2031,
"text": "Although we all-in-all lose our Conda Environment, we retain any virtual environment we utilize when we launch from the terminal, so if I were to"
},
{
"code": null,
"e": 2206,
"s": 2177,
"text": "$ - source env/bin/activate"
},
{
"code": null,
"e": 2237,
"s": 2206,
"text": "and then run Jupyter Notebook,"
},
{
"code": null,
"e": 2264,
"s": 2237,
"text": "$ (env) - jupyter notebook"
},
{
"code": null,
"e": 2407,
"s": 2264,
"text": "I would retain my virtual env pip environment. For obvious reasons, this is a great way to manage your dependency ecosystem inside of Jupyter."
},
{
"code": null,
"e": 2943,
"s": 2407,
"text": "Another reason I love using Jupyter over Anaconda is folder selection, anytime a notebook is buried deep inside a maze of folders in your computer, it can be very hard to get said notebook open in Jupyter. Jupyterβs file interface isnβt exactly well known for being flawless in any sense of the word, although it certainly gets the job done. Using standalone Jupyter with SH, I can open a terminal in any location on my computer and type β Jupyter Notebook,β and already be navigated right to the file that I would like to tamper with."
},
{
"code": null,
"e": 3159,
"s": 2943,
"text": "I also am a strong Docker user, and using Conda with Docker can be quite a chore... However, setting up a completely virtual operating system running inside of regular Jupyter SH with Docker is fluid and super easy."
},
{
"code": null,
"e": 3530,
"s": 3159,
"text": "Although these opinions are certainly not universally agreed upon, I use Jupyter Standalone because I love the versatility. I appreciate Anaconda, and have no particular yield to installing it other than that I donβt need it. It doesnβt really matter how you go about installing Jupyter as long as you donβt do it through the snap package manager (it breaks everything.)"
}
] |
How to set default date time as system date time in MySQL?
|
You can use CURRENT_TIMESTAMP to set system date time.
Let us first create a table β
mysql> create table DemoTable
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
ClientFirstName varchar(20),
ClientLastName varchar(20),
ClientAge int
);
Query OK, 0 rows affected (0.66 sec)
Following is the query to set default datetime as system date time in MySQL β
mysql> alter table DemoTable add column ClientProjectDeadline timestamp default current_timestamp;
Query OK, 0 rows affected (0.46 sec)
Records: 0 Duplicates: 0 Warnings: 0
Let us check the description of table once again β
mysql> desc DemoTable;
This will produce the following output β
+-----------------------+-------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------------+-------------+------+-----+-------------------+----------------+
| Id | int(11) | NO | PRI | NULL | auto_increment |
| ClientFirstName | varchar(20) | YES | | NULL | |
| ClientLastName | varchar(20) | YES | | NULL | |
| ClientAge | int(11) | YES | | NULL | |
| ClientProjectDeadline | timestamp | YES | | CURRENT_TIMESTAMP | |
+-----------------------+-------------+------+-----+-------------------+----------------+
5 rows in set (0.22 sec)
|
[
{
"code": null,
"e": 1117,
"s": 1062,
"text": "You can use CURRENT_TIMESTAMP to set system date time."
},
{
"code": null,
"e": 1148,
"s": 1117,
"text": " Let us first create a table β"
},
{
"code": null,
"e": 1347,
"s": 1148,
"text": "mysql> create table DemoTable\n(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n ClientFirstName varchar(20),\n ClientLastName varchar(20),\n ClientAge int\n);\nQuery OK, 0 rows affected (0.66 sec)"
},
{
"code": null,
"e": 1425,
"s": 1347,
"text": "Following is the query to set default datetime as system date time in MySQL β"
},
{
"code": null,
"e": 1598,
"s": 1425,
"text": "mysql> alter table DemoTable add column ClientProjectDeadline timestamp default current_timestamp;\nQuery OK, 0 rows affected (0.46 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 1649,
"s": 1598,
"text": "Let us check the description of table once again β"
},
{
"code": null,
"e": 1672,
"s": 1649,
"text": "mysql> desc DemoTable;"
},
{
"code": null,
"e": 1713,
"s": 1672,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2548,
"s": 1713,
"text": "+-----------------------+-------------+------+-----+-------------------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+-----------------------+-------------+------+-----+-------------------+----------------+\n| Id | int(11) | NO | PRI | NULL | auto_increment |\n| ClientFirstName | varchar(20) | YES | | NULL | |\n| ClientLastName | varchar(20) | YES | | NULL | |\n| ClientAge | int(11) | YES | | NULL | |\n| ClientProjectDeadline | timestamp | YES | | CURRENT_TIMESTAMP | |\n+-----------------------+-------------+------+-----+-------------------+----------------+\n5 rows in set (0.22 sec)"
}
] |
Materialize CSS Dropdown - GeeksforGeeks
|
15 Sep, 2020
Materialize CSS provides a dropdown facility that allows the user to choose one value from a set of given values in a list. To add a dropdown list to any button, it has to be made sure that the data-target attribute matches with the id in the <ul> tag.
The main class and attribute used in a dropdown are:
The dropdown-content class is used to identify which <ul> tag should be made a Materialize dropdown component.The data-activates attribute is used to specify the id of the dropdown <ul> element.
The dropdown-content class is used to identify which <ul> tag should be made a Materialize dropdown component.
The data-activates attribute is used to specify the id of the dropdown <ul> element.
Syntax:
HTML
<!-- Dropdown Trigger --><h5> <a class='dropdown-button btn green' href='#' data-activates='dropdown1'> Drop Me! <i class="large material-icons"> arrow_drop_down </i> </a></h5>
In dropdown list following elements can be added:
A divider is added by using the divider class. It can be added to an empty <li> tag to show a divider.
Icons are added by using the material-icons class using the <i> tag. The icon to be used can be specified and it would be displayed next to the text of the list item.
Example:
HTML
<!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css"> <script type="text/javascript" src= "https://code.jquery.com/jquery-2.1.1.min.js"> </script> <!-- Let the browser know that the website is optimized for mobile --> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /></head> <body> <h4>Dropdown in Materialize:</h4> <!-- Dropdown Trigger --> <h5><a class='dropdown-button btn green' href='#' data-activates='dropdown1'> Drop Me! <i class="large material-icons"> arrow_drop_down </i> </a> </h5> <!-- Dropdown Structure --> <ul id='dropdown1' class='dropdown-content'> <!-- Define the links in the dropdown --> <li> <a href="https://www.geeksforgeeks.org/materialize-css-collections/?ref=rp"> Collections </a> </li> <li> <a href="https://www.geeksforgeeks.org/materialize-css-icons/?ref=rp"> Icons </a> </li> <!-- Define a divider --> <li class="divider"></li> <li><a href="#!">Table</a></li> <!-- Define a list item with an icon --> <li> <a href="#!"> <i class="material-icons"> view_module </i> Home </a> </li> </ul> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"> </script></body> </html>
Output:
Materialize-CSS
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 27655,
"s": 27627,
"text": "\n15 Sep, 2020"
},
{
"code": null,
"e": 27909,
"s": 27655,
"text": "Materialize CSS provides a dropdown facility that allows the user to choose one value from a set of given values in a list. To add a dropdown list to any button, it has to be made sure that the data-target attribute matches with the id in the <ul> tag. "
},
{
"code": null,
"e": 27963,
"s": 27909,
"text": "The main class and attribute used in a dropdown are: "
},
{
"code": null,
"e": 28158,
"s": 27963,
"text": "The dropdown-content class is used to identify which <ul> tag should be made a Materialize dropdown component.The data-activates attribute is used to specify the id of the dropdown <ul> element."
},
{
"code": null,
"e": 28269,
"s": 28158,
"text": "The dropdown-content class is used to identify which <ul> tag should be made a Materialize dropdown component."
},
{
"code": null,
"e": 28354,
"s": 28269,
"text": "The data-activates attribute is used to specify the id of the dropdown <ul> element."
},
{
"code": null,
"e": 28362,
"s": 28354,
"text": "Syntax:"
},
{
"code": null,
"e": 28367,
"s": 28362,
"text": "HTML"
},
{
"code": "<!-- Dropdown Trigger --><h5> <a class='dropdown-button btn green' href='#' data-activates='dropdown1'> Drop Me! <i class=\"large material-icons\"> arrow_drop_down </i> </a></h5>",
"e": 28569,
"s": 28367,
"text": null
},
{
"code": null,
"e": 28619,
"s": 28569,
"text": "In dropdown list following elements can be added:"
},
{
"code": null,
"e": 28722,
"s": 28619,
"text": "A divider is added by using the divider class. It can be added to an empty <li> tag to show a divider."
},
{
"code": null,
"e": 28889,
"s": 28722,
"text": "Icons are added by using the material-icons class using the <i> tag. The icon to be used can be specified and it would be displayed next to the text of the list item."
},
{
"code": null,
"e": 28898,
"s": 28889,
"text": "Example:"
},
{
"code": null,
"e": 28903,
"s": 28898,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/icon?family=Material+Icons\"> <!-- Compiled and minified CSS --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css\"> <script type=\"text/javascript\" src= \"https://code.jquery.com/jquery-2.1.1.min.js\"> </script> <!-- Let the browser know that the website is optimized for mobile --> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /></head> <body> <h4>Dropdown in Materialize:</h4> <!-- Dropdown Trigger --> <h5><a class='dropdown-button btn green' href='#' data-activates='dropdown1'> Drop Me! <i class=\"large material-icons\"> arrow_drop_down </i> </a> </h5> <!-- Dropdown Structure --> <ul id='dropdown1' class='dropdown-content'> <!-- Define the links in the dropdown --> <li> <a href=\"https://www.geeksforgeeks.org/materialize-css-collections/?ref=rp\"> Collections </a> </li> <li> <a href=\"https://www.geeksforgeeks.org/materialize-css-icons/?ref=rp\"> Icons </a> </li> <!-- Define a divider --> <li class=\"divider\"></li> <li><a href=\"#!\">Table</a></li> <!-- Define a list item with an icon --> <li> <a href=\"#!\"> <i class=\"material-icons\"> view_module </i> Home </a> </li> </ul> <!-- Compiled and minified JavaScript --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js\"> </script></body> </html>",
"e": 30738,
"s": 28903,
"text": null
},
{
"code": null,
"e": 30746,
"s": 30738,
"text": "Output:"
},
{
"code": null,
"e": 30762,
"s": 30746,
"text": "Materialize-CSS"
},
{
"code": null,
"e": 30766,
"s": 30762,
"text": "CSS"
},
{
"code": null,
"e": 30783,
"s": 30766,
"text": "Web Technologies"
},
{
"code": null,
"e": 30881,
"s": 30783,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30890,
"s": 30881,
"text": "Comments"
},
{
"code": null,
"e": 30903,
"s": 30890,
"text": "Old Comments"
},
{
"code": null,
"e": 30965,
"s": 30903,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31015,
"s": 30965,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 31073,
"s": 31015,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 31121,
"s": 31073,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 31158,
"s": 31121,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 31214,
"s": 31158,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 31247,
"s": 31214,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31309,
"s": 31247,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31352,
"s": 31309,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Tryit Editor v3.7
|
Tryit: HTML page as an embed object
|
[] |
Java Program to Get Elements By Index from LinkedHashSet - GeeksforGeeks
|
28 Jul, 2021
LinkedHashSet is a pre-defined class in Java that is similar to HashSet. Unlike HashSet In LinkedHashSet insertion order is preserved. In order to get element by Index from LinkedHashSet in Java, we have multiple ways.
Illustration:
Input : 2, 3, 4, 2, 7;
Processing : index = 4;
Output : Element at index 4 is : 7
Methods:
A naive approach using the iteration count methodConverting LinkedHashSet to ArrayConverting LinkedHashSet to List
A naive approach using the iteration count method
Converting LinkedHashSet to Array
Converting LinkedHashSet to List
Method 1: Naive approach using iteration method for index count and to get the element at the given index.
Algorithm
Use iterator to traverse to our LinkedHashSet.Initiate out index pointer currentindex = 0Start the iteration using a while loop and if the current index becomes equal to the given index print the element.
Use iterator to traverse to our LinkedHashSet.
Initiate out index pointer currentindex = 0
Start the iteration using a while loop and if the current index becomes equal to the given index print the element.
Pseudo Code:
Iterator<Integer> it = LHS.iterator();
while(it.hasNext()) {}
Implementation:
Example 1
Java
// Java Program to Get Elements by Index from LinkedHashSet// Using iteration count method // Importing generic java librariesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Adding elements to LinkedHashSet // Custom inputs LinkedHashSet<Integer> LHS = new LinkedHashSet<>(); LHS.add(2); LHS.add(3); LHS.add(4); LHS.add(2); LHS.add(7); // Custom index chosen to get the element // present at that index int index = 4; Iterator<Integer> it = LHS.iterator(); // Assigning initial values int currIndex = 0; Integer CurrentElement = null; // Condition check using hasNext(), whick // returns true if another token as input while (it.hasNext()) { // next element using iterator is // assigned to variable CurrentElement = it.next(); // Variable condition check if (currIndex == index - 1) { System.out.println("Element at index " + index + " is : " + CurrentElement); break; } // If condition fails, so // Incrementing current index currIndex++; } }}
Element at index 4 is : 7
Time Complexity: O(n)
Method 2: LinkedHashSet is converted to Array by which element can be accessed at the given index.
Algorithm:
Convert given LinkedHashSet to Array using toArray() method.Accessing the element on the given index in the array.
Convert given LinkedHashSet to Array using toArray() method.
Accessing the element on the given index in the array.
Pseudo Code:
Integer[] LHSArray = new Integer[LHS.size()];
LHSArray = LHS.toArray(LHSArray);
Example
Java
// Java Program to Get Elements by Index from LinkedHashSet// By converting LinkedHashSet to Array // Importing generic java librariesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating a LinkedHashSet LinkedHashSet<Integer> LHS = new LinkedHashSet<>(); // Adding elements() to LinkedHashSet LHS.add(2); LHS.add(3); LHS.add(4); LHS.add(2); LHS.add(7); // Custom index chosen from LinkedHashSet int index = 4; // Converting LnkedHashMap to Array Integer[] LHSArray = new Integer[LHS.size()]; LHSArray = LHS.toArray(LHSArray); // Printing desired value at index in array, // chosen above index from LinkedHashap System.out.println("Element at index " + index + " is : " + LHSArray[index - 1]); }}
Element at index 4 is : 7
Time Complexity: O(1)
Method 3: LinkedHashSet to be converted to List to get the desired element at the given index.
Algorithm
Convert our LinkedHashMap to List like ArrayList.Using get() method to get an element in a given index.
Convert our LinkedHashMap to List like ArrayList.
Using get() method to get an element in a given index.
Pseudo Code : List<Integer> LHSList =new ArrayList<>(LHS);
where LHS is name of our LinkedHashSet
Implementation:
Java
// Java Program to Get Elements by Index from LinkedHashSet// By converting LinkedHashSet to List // Importing java generic librariesimport java.util.*;import java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating a LinkedHashSet LinkedHashSet<Integer> LHS = new LinkedHashSet<>(); // Adding elements to LinkedHashSet LHS.add(2); LHS.add(3); LHS.add(4); LHS.add(2); LHS.add(7); // Custom index chosen to retrieve value int index = 4; // Converting LinkedHashSet to List Iterator<Integer> it = LHS.iterator(); // Assigning initial values int currIndex = 0; Integer CurrentElement = null; // Condition check using hasNext(), whick // returns true if another token as input while (it.hasNext()) { CurrentElement = it.next(); if (currIndex == index - 1) { // Printing desired value at index in array, // chosen above index from LinkedHashap System.out.println("Element at index " + index + " is : " + CurrentElement); break; } // Incrementing the current index currIndex++; } }}
Element at index 4 is : 7
saurabh1990aror
skhasanj300
java-LinkedHashSet
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
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
StringBuilder Class in Java with Examples
Convert a String to Character array in Java
Java Programming Examples
Implementing a Linked List in Java using Class
Convert Double to Integer in Java
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 23868,
"s": 23840,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 24087,
"s": 23868,
"text": "LinkedHashSet is a pre-defined class in Java that is similar to HashSet. Unlike HashSet In LinkedHashSet insertion order is preserved. In order to get element by Index from LinkedHashSet in Java, we have multiple ways."
},
{
"code": null,
"e": 24101,
"s": 24087,
"text": "Illustration:"
},
{
"code": null,
"e": 24192,
"s": 24101,
"text": "Input : 2, 3, 4, 2, 7;\nProcessing : index = 4;\nOutput : Element at index 4 is : 7"
},
{
"code": null,
"e": 24201,
"s": 24192,
"text": "Methods:"
},
{
"code": null,
"e": 24316,
"s": 24201,
"text": "A naive approach using the iteration count methodConverting LinkedHashSet to ArrayConverting LinkedHashSet to List"
},
{
"code": null,
"e": 24366,
"s": 24316,
"text": "A naive approach using the iteration count method"
},
{
"code": null,
"e": 24400,
"s": 24366,
"text": "Converting LinkedHashSet to Array"
},
{
"code": null,
"e": 24433,
"s": 24400,
"text": "Converting LinkedHashSet to List"
},
{
"code": null,
"e": 24540,
"s": 24433,
"text": "Method 1: Naive approach using iteration method for index count and to get the element at the given index."
},
{
"code": null,
"e": 24550,
"s": 24540,
"text": "Algorithm"
},
{
"code": null,
"e": 24755,
"s": 24550,
"text": "Use iterator to traverse to our LinkedHashSet.Initiate out index pointer currentindex = 0Start the iteration using a while loop and if the current index becomes equal to the given index print the element."
},
{
"code": null,
"e": 24802,
"s": 24755,
"text": "Use iterator to traverse to our LinkedHashSet."
},
{
"code": null,
"e": 24846,
"s": 24802,
"text": "Initiate out index pointer currentindex = 0"
},
{
"code": null,
"e": 24962,
"s": 24846,
"text": "Start the iteration using a while loop and if the current index becomes equal to the given index print the element."
},
{
"code": null,
"e": 25038,
"s": 24962,
"text": "Pseudo Code: \nIterator<Integer> it = LHS.iterator();\nwhile(it.hasNext()) {}"
},
{
"code": null,
"e": 25054,
"s": 25038,
"text": "Implementation:"
},
{
"code": null,
"e": 25064,
"s": 25054,
"text": "Example 1"
},
{
"code": null,
"e": 25069,
"s": 25064,
"text": "Java"
},
{
"code": "// Java Program to Get Elements by Index from LinkedHashSet// Using iteration count method // Importing generic java librariesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Adding elements to LinkedHashSet // Custom inputs LinkedHashSet<Integer> LHS = new LinkedHashSet<>(); LHS.add(2); LHS.add(3); LHS.add(4); LHS.add(2); LHS.add(7); // Custom index chosen to get the element // present at that index int index = 4; Iterator<Integer> it = LHS.iterator(); // Assigning initial values int currIndex = 0; Integer CurrentElement = null; // Condition check using hasNext(), whick // returns true if another token as input while (it.hasNext()) { // next element using iterator is // assigned to variable CurrentElement = it.next(); // Variable condition check if (currIndex == index - 1) { System.out.println(\"Element at index \" + index + \" is : \" + CurrentElement); break; } // If condition fails, so // Incrementing current index currIndex++; } }}",
"e": 26446,
"s": 25069,
"text": null
},
{
"code": null,
"e": 26472,
"s": 26446,
"text": "Element at index 4 is : 7"
},
{
"code": null,
"e": 26494,
"s": 26472,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 26593,
"s": 26494,
"text": "Method 2: LinkedHashSet is converted to Array by which element can be accessed at the given index."
},
{
"code": null,
"e": 26605,
"s": 26593,
"text": "Algorithm: "
},
{
"code": null,
"e": 26720,
"s": 26605,
"text": "Convert given LinkedHashSet to Array using toArray() method.Accessing the element on the given index in the array."
},
{
"code": null,
"e": 26781,
"s": 26720,
"text": "Convert given LinkedHashSet to Array using toArray() method."
},
{
"code": null,
"e": 26836,
"s": 26781,
"text": "Accessing the element on the given index in the array."
},
{
"code": null,
"e": 26929,
"s": 26836,
"text": "Pseudo Code:\nInteger[] LHSArray = new Integer[LHS.size()];\nLHSArray = LHS.toArray(LHSArray);"
},
{
"code": null,
"e": 26939,
"s": 26929,
"text": "Example "
},
{
"code": null,
"e": 26944,
"s": 26939,
"text": "Java"
},
{
"code": "// Java Program to Get Elements by Index from LinkedHashSet// By converting LinkedHashSet to Array // Importing generic java librariesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating a LinkedHashSet LinkedHashSet<Integer> LHS = new LinkedHashSet<>(); // Adding elements() to LinkedHashSet LHS.add(2); LHS.add(3); LHS.add(4); LHS.add(2); LHS.add(7); // Custom index chosen from LinkedHashSet int index = 4; // Converting LnkedHashMap to Array Integer[] LHSArray = new Integer[LHS.size()]; LHSArray = LHS.toArray(LHSArray); // Printing desired value at index in array, // chosen above index from LinkedHashap System.out.println(\"Element at index \" + index + \" is : \" + LHSArray[index - 1]); }}",
"e": 27905,
"s": 26944,
"text": null
},
{
"code": null,
"e": 27931,
"s": 27905,
"text": "Element at index 4 is : 7"
},
{
"code": null,
"e": 27953,
"s": 27931,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 28048,
"s": 27953,
"text": "Method 3: LinkedHashSet to be converted to List to get the desired element at the given index."
},
{
"code": null,
"e": 28059,
"s": 28048,
"text": "Algorithm "
},
{
"code": null,
"e": 28163,
"s": 28059,
"text": "Convert our LinkedHashMap to List like ArrayList.Using get() method to get an element in a given index."
},
{
"code": null,
"e": 28213,
"s": 28163,
"text": "Convert our LinkedHashMap to List like ArrayList."
},
{
"code": null,
"e": 28268,
"s": 28213,
"text": "Using get() method to get an element in a given index."
},
{
"code": null,
"e": 28380,
"s": 28268,
"text": "Pseudo Code : List<Integer> LHSList =new ArrayList<>(LHS);\n where LHS is name of our LinkedHashSet"
},
{
"code": null,
"e": 28397,
"s": 28380,
"text": "Implementation: "
},
{
"code": null,
"e": 28402,
"s": 28397,
"text": "Java"
},
{
"code": "// Java Program to Get Elements by Index from LinkedHashSet// By converting LinkedHashSet to List // Importing java generic librariesimport java.util.*;import java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating a LinkedHashSet LinkedHashSet<Integer> LHS = new LinkedHashSet<>(); // Adding elements to LinkedHashSet LHS.add(2); LHS.add(3); LHS.add(4); LHS.add(2); LHS.add(7); // Custom index chosen to retrieve value int index = 4; // Converting LinkedHashSet to List Iterator<Integer> it = LHS.iterator(); // Assigning initial values int currIndex = 0; Integer CurrentElement = null; // Condition check using hasNext(), whick // returns true if another token as input while (it.hasNext()) { CurrentElement = it.next(); if (currIndex == index - 1) { // Printing desired value at index in array, // chosen above index from LinkedHashap System.out.println(\"Element at index \" + index + \" is : \" + CurrentElement); break; } // Incrementing the current index currIndex++; } }}",
"e": 29770,
"s": 28402,
"text": null
},
{
"code": null,
"e": 29796,
"s": 29770,
"text": "Element at index 4 is : 7"
},
{
"code": null,
"e": 29812,
"s": 29796,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 29824,
"s": 29812,
"text": "skhasanj300"
},
{
"code": null,
"e": 29843,
"s": 29824,
"text": "java-LinkedHashSet"
},
{
"code": null,
"e": 29850,
"s": 29843,
"text": "Picked"
},
{
"code": null,
"e": 29874,
"s": 29850,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29879,
"s": 29874,
"text": "Java"
},
{
"code": null,
"e": 29893,
"s": 29879,
"text": "Java Programs"
},
{
"code": null,
"e": 29912,
"s": 29893,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29917,
"s": 29912,
"text": "Java"
},
{
"code": null,
"e": 30015,
"s": 29917,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30024,
"s": 30015,
"text": "Comments"
},
{
"code": null,
"e": 30037,
"s": 30024,
"text": "Old Comments"
},
{
"code": null,
"e": 30083,
"s": 30037,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 30104,
"s": 30083,
"text": "Constructors in Java"
},
{
"code": null,
"e": 30119,
"s": 30104,
"text": "Stream In Java"
},
{
"code": null,
"e": 30138,
"s": 30119,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 30180,
"s": 30138,
"text": "StringBuilder Class in Java with Examples"
},
{
"code": null,
"e": 30224,
"s": 30180,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 30250,
"s": 30224,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 30297,
"s": 30250,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 30331,
"s": 30297,
"text": "Convert Double to Integer in Java"
}
] |
Pairwise swap elements of a linked list | Practice | GeeksforGeeks
|
Given a singly linked list of size N. The task is to swap elements in the linked list pairwise.
For example, if the input list is 1 2 3 4, the resulting list after swaps will be 2 1 4 3.
Note: You need to swap the nodes, not only the data. If only data is swapped then driver will print -1.
Example 1:
Input:
LinkedList: 1->2->2->4->5->6->7->8
Output: 2 1 4 2 6 5 8 7
Explanation: After swapping each pair
considering (1,2), (2, 4), (5, 6).. so
on as pairs, we get 2, 1, 4, 2, 6, 5,
8, 7 as a new linked list.
Example 1:
Input:
LinkedList: 1->3->4->7->9->10->1
Output: 3 1 7 4 10 9 1
Explanation: After swapping each pair
considering (1,3), (4, 7), (9, 10).. so
on as pairs, we get 3, 1, 7, 4, 10, 9,
1 as a new linked list.
Your Task:
The task is to complete the function pairWiseSwap() which takes the head node as the only argument and returns the head of modified linked list.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
Constraints:
1 β€ N β€ 103
0
abhaybaranwal41 week ago
public Node pairwiseSwap(Node head) { // code here if(head==null|| head.next==null) { return head; } Node curr=head.next.next; Node prev=head; head=head.next; head.next=prev; while(curr!=null && curr.next!=null) { prev.next=curr.next; prev=curr; Node next=curr.next.next; curr.next.next=curr; curr=next; } prev.next=curr; return head; }
0
tthakare732 weeks ago
//Java Solution -> TC -> 1.57
class Solution {
public Node pairwiseSwap(Node head){
// Veriables
Node forword = head.next, backword = head, tempBack = null, tempForword = null, pre = null;
while(backword != null && forword != null){
tempForword = forword;
tempBack = backword;
tempBack.next = tempForword.next;
tempForword.next = tempBack;
if(backword == head) head = tempForword;
backword = tempBack.next;
if(backword != null && backword.next != null) {
forword = backword.next;
tempBack.next = forword;
} else {
forword = null;
}
}
return head;
}
}
0
harshpandeyalfa22 weeks ago
C++
(0.1sec)
Node* pairWiseSwap(struct Node* head) { if(head==0 || head->next==0) return head; Node* it1=head; Node* it2=head->next; it1->next=it2->next; it2->next=it1; head=it2; Node* temp; temp=it1; it1=it2; it2=temp; Node*i=it2; if(it2->next==0) return head; if(it2->next->next==0) return head; it1=it2->next; it2=it2->next->next; while(it1 && it2) { it1->next=it2->next; it2->next=it1; temp=it1; it1=it2; it2=temp; i->next=it1; i=it2; if(it2->next==0) return head; if(it2->next->next==0) return head; it1=it2->next; it2=it2->next->next; } return head; // The task is to complete this method }
0
hharshit81183 weeks ago
Time Complexity: O(N).Auxiliary Space: O(1).
Node* pairWiseSwap(struct Node* head) { Node *curr = head; bool visit = true; Node* pre_first = curr; while(curr != NULL){ Node* pre_last = curr; Node* t1 = NULL, *t2 = NULL; for(int i = 0; i< 2 && curr != NULL; i++){ t2 = curr->next; curr->next = t1; t1 = curr; curr = t2; } if(visit){ head = t1; visit = false; } else{ pre_first->next = t1; pre_first = pre_last; } } return head; }
0
sagrikasoni3 weeks ago
class Solution {
public Node pairwiseSwap(Node head)
{
int c =0;
Node pre = null, curr = head, f =null;
while(curr!=null && c<2){
f = curr.next;
curr.next = pre;
pre = curr;
curr = f;
c++;
}
if(f!=null){
head.next = pairwiseSwap(f);
}
return pre;
}
}
+3
as0042301 month ago
In C++;
Node* pairWiseSwap(struct Node* head) { Node *first = head; Node *prev, *second, *next; while(first && first->next) { second = first->next; next = second->next; if(first == head) head = first->next; else prev->next = second; second->next = first; first->next = next; prev = first; first = next; } return head; }
0
as0042301 month ago
In C++;
//Using Recursion
Node* pairWiseSwap(struct Node* head) { Node *cur = head; Node *next = NULL; Node *prev = NULL; int count = 0; while(cur && count < 2) { next = cur->next; cur->next = prev; prev = cur; cur = next; count++; } if(next != NULL) head->next = pairWiseSwap(next); return prev; }
-1
sparhibsp20181 month ago
simple and understandable code using c++
Node* pairWiseSwap(struct Node* head) { if(head->next==NULL) { return head; } Node* first=head; Node* second=head->next; head=head->next; Node* pre; while ( second!=NULL && second->next!=NULL ) { Node* store=second->next; first->next=second->next->next; second->next=first; pre=first; first=store; second=first->next;
} if(second!=NULL) { second->next=first; first->next=NULL; } else { pre->next=first; } return head; }
0
tapanmanu20001 month ago
Node* pairWiseSwap(struct Node* head)
{
// The task is to complete this method
if(head == NULL) return head;
if(head->next == NULL) return head;
Node* nextNode = pairWiseSwap(head->next->next);
Node* pair = head->next;
pair->next = head;
head->next = nextNode;
return pair;
}
0
rafi19981 month ago
// Java Solution
public Node pairwiseSwap(Node head)
{
if(head.next==null)
return head;
Node t=head;
Node temp=t.next.next;
head=t.next;
while(temp!=null && temp.next!=null){
t.next.next=t;
t.next=temp.next;
t=temp;
temp=t.next.next;
}
t.next.next=t;
t.next=temp;
return head;
}
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": 517,
"s": 226,
"text": "Given a singly linked list of size N. The task is to swap elements in the linked list pairwise.\nFor example, if the input list is 1 2 3 4, the resulting list after swaps will be 2 1 4 3.\nNote: You need to swap the nodes, not only the data. If only data is swapped then driver will print -1."
},
{
"code": null,
"e": 528,
"s": 517,
"text": "Example 1:"
},
{
"code": null,
"e": 737,
"s": 528,
"text": "Input:\nLinkedList: 1->2->2->4->5->6->7->8\nOutput: 2 1 4 2 6 5 8 7\nExplanation: After swapping each pair\nconsidering (1,2), (2, 4), (5, 6).. so\non as pairs, we get 2, 1, 4, 2, 6, 5,\n8, 7 as a new linked list.\n"
},
{
"code": null,
"e": 750,
"s": 739,
"text": "Example 1:"
},
{
"code": null,
"e": 954,
"s": 750,
"text": "Input:\nLinkedList: 1->3->4->7->9->10->1\nOutput: 3 1 7 4 10 9 1\nExplanation: After swapping each pair\nconsidering (1,3), (4, 7), (9, 10).. so\non as pairs, we get 3, 1, 7, 4, 10, 9,\n1 as a new linked list."
},
{
"code": null,
"e": 1110,
"s": 954,
"text": "Your Task:\nThe task is to complete the function pairWiseSwap() which takes the head node as the only argument and returns the head of modified linked list."
},
{
"code": null,
"e": 1174,
"s": 1110,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 1199,
"s": 1174,
"text": "Constraints:\n1 β€ N β€ 103"
},
{
"code": null,
"e": 1201,
"s": 1199,
"text": "0"
},
{
"code": null,
"e": 1226,
"s": 1201,
"text": "abhaybaranwal41 week ago"
},
{
"code": null,
"e": 1730,
"s": 1226,
"text": " public Node pairwiseSwap(Node head) { // code here if(head==null|| head.next==null) { return head; } Node curr=head.next.next; Node prev=head; head=head.next; head.next=prev; while(curr!=null && curr.next!=null) { prev.next=curr.next; prev=curr; Node next=curr.next.next; curr.next.next=curr; curr=next; } prev.next=curr; return head; }"
},
{
"code": null,
"e": 1732,
"s": 1730,
"text": "0"
},
{
"code": null,
"e": 1754,
"s": 1732,
"text": "tthakare732 weeks ago"
},
{
"code": null,
"e": 2550,
"s": 1754,
"text": "//Java Solution -> TC -> 1.57\nclass Solution {\n public Node pairwiseSwap(Node head){\n // Veriables\n Node forword = head.next, backword = head, tempBack = null, tempForword = null, pre = null;\n while(backword != null && forword != null){\n tempForword = forword;\n tempBack = backword;\n \n tempBack.next = tempForword.next;\n tempForword.next = tempBack;\n \n if(backword == head) head = tempForword;\n \n backword = tempBack.next;\n if(backword != null && backword.next != null) {\n forword = backword.next;\n tempBack.next = forword;\n } else {\n forword = null;\n }\n }\n return head;\n \n }\n}"
},
{
"code": null,
"e": 2552,
"s": 2550,
"text": "0"
},
{
"code": null,
"e": 2580,
"s": 2552,
"text": "harshpandeyalfa22 weeks ago"
},
{
"code": null,
"e": 2584,
"s": 2580,
"text": "C++"
},
{
"code": null,
"e": 2593,
"s": 2584,
"text": "(0.1sec)"
},
{
"code": null,
"e": 3423,
"s": 2593,
"text": " Node* pairWiseSwap(struct Node* head) { if(head==0 || head->next==0) return head; Node* it1=head; Node* it2=head->next; it1->next=it2->next; it2->next=it1; head=it2; Node* temp; temp=it1; it1=it2; it2=temp; Node*i=it2; if(it2->next==0) return head; if(it2->next->next==0) return head; it1=it2->next; it2=it2->next->next; while(it1 && it2) { it1->next=it2->next; it2->next=it1; temp=it1; it1=it2; it2=temp; i->next=it1; i=it2; if(it2->next==0) return head; if(it2->next->next==0) return head; it1=it2->next; it2=it2->next->next; } return head; // The task is to complete this method }"
},
{
"code": null,
"e": 3425,
"s": 3423,
"text": "0"
},
{
"code": null,
"e": 3449,
"s": 3425,
"text": "hharshit81183 weeks ago"
},
{
"code": null,
"e": 3494,
"s": 3449,
"text": "Time Complexity: O(N).Auxiliary Space: O(1)."
},
{
"code": null,
"e": 4111,
"s": 3494,
"text": "Node* pairWiseSwap(struct Node* head) { Node *curr = head; bool visit = true; Node* pre_first = curr; while(curr != NULL){ Node* pre_last = curr; Node* t1 = NULL, *t2 = NULL; for(int i = 0; i< 2 && curr != NULL; i++){ t2 = curr->next; curr->next = t1; t1 = curr; curr = t2; } if(visit){ head = t1; visit = false; } else{ pre_first->next = t1; pre_first = pre_last; } } return head; }"
},
{
"code": null,
"e": 4113,
"s": 4111,
"text": "0"
},
{
"code": null,
"e": 4136,
"s": 4113,
"text": "sagrikasoni3 weeks ago"
},
{
"code": null,
"e": 4523,
"s": 4136,
"text": "class Solution {\n\n public Node pairwiseSwap(Node head)\n {\n int c =0;\n \n Node pre = null, curr = head, f =null;\n while(curr!=null && c<2){\n f = curr.next;\n curr.next = pre;\n pre = curr;\n curr = f;\n c++;\n }\n if(f!=null){\n head.next = pairwiseSwap(f);\n }\n \n return pre;\n }\n}"
},
{
"code": null,
"e": 4526,
"s": 4523,
"text": "+3"
},
{
"code": null,
"e": 4546,
"s": 4526,
"text": "as0042301 month ago"
},
{
"code": null,
"e": 4554,
"s": 4546,
"text": "In C++;"
},
{
"code": null,
"e": 5059,
"s": 4554,
"text": "Node* pairWiseSwap(struct Node* head) { Node *first = head; Node *prev, *second, *next; while(first && first->next) { second = first->next; next = second->next; if(first == head) head = first->next; else prev->next = second; second->next = first; first->next = next; prev = first; first = next; } return head; }"
},
{
"code": null,
"e": 5061,
"s": 5059,
"text": "0"
},
{
"code": null,
"e": 5081,
"s": 5061,
"text": "as0042301 month ago"
},
{
"code": null,
"e": 5089,
"s": 5081,
"text": "In C++;"
},
{
"code": null,
"e": 5107,
"s": 5089,
"text": "//Using Recursion"
},
{
"code": null,
"e": 5505,
"s": 5107,
"text": "Node* pairWiseSwap(struct Node* head) { Node *cur = head; Node *next = NULL; Node *prev = NULL; int count = 0; while(cur && count < 2) { next = cur->next; cur->next = prev; prev = cur; cur = next; count++; } if(next != NULL) head->next = pairWiseSwap(next); return prev; }"
},
{
"code": null,
"e": 5508,
"s": 5505,
"text": "-1"
},
{
"code": null,
"e": 5533,
"s": 5508,
"text": "sparhibsp20181 month ago"
},
{
"code": null,
"e": 5574,
"s": 5533,
"text": "simple and understandable code using c++"
},
{
"code": null,
"e": 6019,
"s": 5574,
"text": "Node* pairWiseSwap(struct Node* head) { if(head->next==NULL) { return head; } Node* first=head; Node* second=head->next; head=head->next; Node* pre; while ( second!=NULL && second->next!=NULL ) { Node* store=second->next; first->next=second->next->next; second->next=first; pre=first; first=store; second=first->next;"
},
{
"code": null,
"e": 6208,
"s": 6019,
"text": " } if(second!=NULL) { second->next=first; first->next=NULL; } else { pre->next=first; } return head; }"
},
{
"code": null,
"e": 6210,
"s": 6208,
"text": "0"
},
{
"code": null,
"e": 6235,
"s": 6210,
"text": "tapanmanu20001 month ago"
},
{
"code": null,
"e": 6602,
"s": 6235,
"text": "Node* pairWiseSwap(struct Node* head) \n {\n // The task is to complete this method\n if(head == NULL) return head;\n if(head->next == NULL) return head;\n \n Node* nextNode = pairWiseSwap(head->next->next);\n Node* pair = head->next;\n pair->next = head;\n head->next = nextNode;\n return pair;\n \n }"
},
{
"code": null,
"e": 6604,
"s": 6602,
"text": "0"
},
{
"code": null,
"e": 6624,
"s": 6604,
"text": "rafi19981 month ago"
},
{
"code": null,
"e": 7074,
"s": 6624,
"text": "// Java Solution\npublic Node pairwiseSwap(Node head)\n {\n if(head.next==null)\n return head;\n \n Node t=head;\n Node temp=t.next.next;\n head=t.next;\n \n while(temp!=null && temp.next!=null){\n t.next.next=t;\n t.next=temp.next;\n t=temp;\n temp=t.next.next;\n }\n t.next.next=t;\n t.next=temp;\n \n return head;\n }"
},
{
"code": null,
"e": 7220,
"s": 7074,
"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": 7256,
"s": 7220,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7266,
"s": 7256,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7276,
"s": 7266,
"text": "\nContest\n"
},
{
"code": null,
"e": 7339,
"s": 7276,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7487,
"s": 7339,
"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": 7695,
"s": 7487,
"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": 7801,
"s": 7695,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Final keyword in C#
|
Java has a final keyword, but C# does not have its implementation. For the same implementation, use the sealed keyword.
With sealed, you can prevent overriding of a method. When you use sealed modifiers in C# on a method, then the method loses its capabilities of overriding. The sealed method should be part of a derived class and the method must be an overridden method.
The following example wonβt allow you to override the method display() because it has a sealed modifier for the ClassTwo derived class.
ClassOne is our base class, whereas ClassTwo and ClassThree are derived classes β
class ClassOne {
public virtual void display() {
Console.WriteLine("Baseclass");
}
}
class ClassTwo : ClassOne {
public sealed override void display() {
Console.WriteLine("ClassTwo:derivedClass");
}
}
class ClassThree : ClassTwo {
public override void display() {
Console.WriteLine("ClassThree: Another Derived Class");
}
}
|
[
{
"code": null,
"e": 1182,
"s": 1062,
"text": "Java has a final keyword, but C# does not have its implementation. For the same implementation, use the sealed keyword."
},
{
"code": null,
"e": 1435,
"s": 1182,
"text": "With sealed, you can prevent overriding of a method. When you use sealed modifiers in C# on a method, then the method loses its capabilities of overriding. The sealed method should be part of a derived class and the method must be an overridden method."
},
{
"code": null,
"e": 1571,
"s": 1435,
"text": "The following example wonβt allow you to override the method display() because it has a sealed modifier for the ClassTwo derived class."
},
{
"code": null,
"e": 1653,
"s": 1571,
"text": "ClassOne is our base class, whereas ClassTwo and ClassThree are derived classes β"
},
{
"code": null,
"e": 2018,
"s": 1653,
"text": "class ClassOne {\n public virtual void display() {\n Console.WriteLine(\"Baseclass\");\n }\n}\n\nclass ClassTwo : ClassOne {\n public sealed override void display() {\n Console.WriteLine(\"ClassTwo:derivedClass\");\n }\n}\n\nclass ClassThree : ClassTwo {\n public override void display() {\n Console.WriteLine(\"ClassThree: Another Derived Class\");\n }\n}"
}
] |
How to get the current username in Python - GeeksforGeeks
|
23 Jan, 2022
In this article, we will discuss how to get the current username in python.
getlogin() method of OS library is used to get the current username.
Syntax : os.getlogin( )
In order to use this function we need to import os library first .
Python3
# importing os moduleimport os # using getlogin() returning usernameos.getlogin()
Output :
'KRISHNA KARTHIKEYA'
There is another method available in os library named path.expanduser() method. In this function, we need to pass the Tilde operator within single quotes as an argument.
syntax : os.path.expanduser( )
Note: In this method, we need to pass the tilde operator as an argument.
Python3
# importing required moduleimport os # using path.expanduser() getting usernameos.path.expanduser('~')
Output :
'C:\\Users\\KRISHNA KARTHIKEYA'
This method is also available in the os module. We need to pass USERNAME as an argument into this method. Let us see the syntax and example .
syntax : os.environ.get( β USERNAMEβ )
note : In some cases we need pass USER instead of USERNAME . Most of the cases we pass USERNAME as argument .
Python3
# importing os moduleimport os # using environ.get() method getting# current usernameos.environ.get('USERNAME')
Output :
'KRISHNA KARTHIKEYA'
In this module, we need to use getuser() method to return the current username. This getuser() method is available in getpass library.
syntax : getpass.getuser( )
Example :
Python3
# importing getpass library using import command# Here gt is a alias name for getpass# Instead of writing getpass we can use gtimport getpass as gt # using getuser() method , returning current# usernamegt.getuser()
Output :
'KRISHNA KARTHIKEYA'
pwd module works only with Linux environment. But os works with both Windows and Linux. This means some methods work with only windows and some methods work with only Linux. If we execute this method in Linux we will get output as root. Let us see the syntax and example of getpwuid() method.
syntax : getpwuid( os.getuid() )[0]
Here [0] is like index. Generally this function returns many outputs like system name , password , uid , bash..etc . Here we need username . It is at index 0 . so we are specifying [0] .
Example :
Python3
# importing required modulesimport osimport pwd # Using getpwuid() and getuid we are# printing current usernamepwd.getpwuid(os.getuid())[0]
Output :
'root'
sumitgumber28
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Defaultdict in Python
Python OOPs Concepts
Python | os.path.join() method
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n23 Jan, 2022"
},
{
"code": null,
"e": 24368,
"s": 24292,
"text": "In this article, we will discuss how to get the current username in python."
},
{
"code": null,
"e": 24437,
"s": 24368,
"text": "getlogin() method of OS library is used to get the current username."
},
{
"code": null,
"e": 24462,
"s": 24437,
"text": "Syntax : os.getlogin( ) "
},
{
"code": null,
"e": 24529,
"s": 24462,
"text": "In order to use this function we need to import os library first ."
},
{
"code": null,
"e": 24537,
"s": 24529,
"text": "Python3"
},
{
"code": "# importing os moduleimport os # using getlogin() returning usernameos.getlogin()",
"e": 24620,
"s": 24537,
"text": null
},
{
"code": null,
"e": 24629,
"s": 24620,
"text": "Output :"
},
{
"code": null,
"e": 24650,
"s": 24629,
"text": "'KRISHNA KARTHIKEYA'"
},
{
"code": null,
"e": 24820,
"s": 24650,
"text": "There is another method available in os library named path.expanduser() method. In this function, we need to pass the Tilde operator within single quotes as an argument."
},
{
"code": null,
"e": 24852,
"s": 24820,
"text": "syntax : os.path.expanduser( ) "
},
{
"code": null,
"e": 24925,
"s": 24852,
"text": "Note: In this method, we need to pass the tilde operator as an argument."
},
{
"code": null,
"e": 24933,
"s": 24925,
"text": "Python3"
},
{
"code": "# importing required moduleimport os # using path.expanduser() getting usernameos.path.expanduser('~')",
"e": 25036,
"s": 24933,
"text": null
},
{
"code": null,
"e": 25045,
"s": 25036,
"text": "Output :"
},
{
"code": null,
"e": 25077,
"s": 25045,
"text": "'C:\\\\Users\\\\KRISHNA KARTHIKEYA'"
},
{
"code": null,
"e": 25219,
"s": 25077,
"text": "This method is also available in the os module. We need to pass USERNAME as an argument into this method. Let us see the syntax and example ."
},
{
"code": null,
"e": 25258,
"s": 25219,
"text": "syntax : os.environ.get( β USERNAMEβ )"
},
{
"code": null,
"e": 25368,
"s": 25258,
"text": "note : In some cases we need pass USER instead of USERNAME . Most of the cases we pass USERNAME as argument ."
},
{
"code": null,
"e": 25376,
"s": 25368,
"text": "Python3"
},
{
"code": "# importing os moduleimport os # using environ.get() method getting# current usernameos.environ.get('USERNAME')",
"e": 25488,
"s": 25376,
"text": null
},
{
"code": null,
"e": 25497,
"s": 25488,
"text": "Output :"
},
{
"code": null,
"e": 25518,
"s": 25497,
"text": "'KRISHNA KARTHIKEYA'"
},
{
"code": null,
"e": 25653,
"s": 25518,
"text": "In this module, we need to use getuser() method to return the current username. This getuser() method is available in getpass library."
},
{
"code": null,
"e": 25681,
"s": 25653,
"text": "syntax : getpass.getuser( )"
},
{
"code": null,
"e": 25691,
"s": 25681,
"text": "Example :"
},
{
"code": null,
"e": 25699,
"s": 25691,
"text": "Python3"
},
{
"code": "# importing getpass library using import command# Here gt is a alias name for getpass# Instead of writing getpass we can use gtimport getpass as gt # using getuser() method , returning current# usernamegt.getuser()",
"e": 25914,
"s": 25699,
"text": null
},
{
"code": null,
"e": 25923,
"s": 25914,
"text": "Output :"
},
{
"code": null,
"e": 25944,
"s": 25923,
"text": "'KRISHNA KARTHIKEYA'"
},
{
"code": null,
"e": 26237,
"s": 25944,
"text": "pwd module works only with Linux environment. But os works with both Windows and Linux. This means some methods work with only windows and some methods work with only Linux. If we execute this method in Linux we will get output as root. Let us see the syntax and example of getpwuid() method."
},
{
"code": null,
"e": 26273,
"s": 26237,
"text": "syntax : getpwuid( os.getuid() )[0]"
},
{
"code": null,
"e": 26460,
"s": 26273,
"text": "Here [0] is like index. Generally this function returns many outputs like system name , password , uid , bash..etc . Here we need username . It is at index 0 . so we are specifying [0] ."
},
{
"code": null,
"e": 26472,
"s": 26460,
"text": "Example : "
},
{
"code": null,
"e": 26480,
"s": 26472,
"text": "Python3"
},
{
"code": "# importing required modulesimport osimport pwd # Using getpwuid() and getuid we are# printing current usernamepwd.getpwuid(os.getuid())[0]",
"e": 26620,
"s": 26480,
"text": null
},
{
"code": null,
"e": 26629,
"s": 26620,
"text": "Output :"
},
{
"code": null,
"e": 26636,
"s": 26629,
"text": "'root'"
},
{
"code": null,
"e": 26650,
"s": 26636,
"text": "sumitgumber28"
},
{
"code": null,
"e": 26657,
"s": 26650,
"text": "Picked"
},
{
"code": null,
"e": 26672,
"s": 26657,
"text": "python-utility"
},
{
"code": null,
"e": 26679,
"s": 26672,
"text": "Python"
},
{
"code": null,
"e": 26777,
"s": 26679,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26786,
"s": 26777,
"text": "Comments"
},
{
"code": null,
"e": 26799,
"s": 26786,
"text": "Old Comments"
},
{
"code": null,
"e": 26831,
"s": 26799,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26886,
"s": 26831,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26942,
"s": 26886,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26984,
"s": 26942,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27026,
"s": 26984,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27065,
"s": 27026,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27087,
"s": 27065,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27108,
"s": 27087,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 27139,
"s": 27108,
"text": "Python | os.path.join() method"
}
] |
How to Find the Number of Arguments Provided at Runtime in Java? - GeeksforGeeks
|
11 Nov, 2020
The Java command-line argument is an argument that is passed at the time of running of a program. i.e. in order to make a program dynamic, there may be cases where we pass the arguments at runtime. Usually, via command-line arguments, they get passed and there are ways to find the number of arguments provided and also get the value of each argument.
Each Java program gets initiated via the main method which is static that means no instantiation is required for the main method. Directly we can call. Hence, a java file name is called, the first method to get started is main() method and it has an input argument which is of String[] (String array datatype)
Syntax :
Java
// Java code with main method. // It has an input argument// with String[] datatype import java.io.*; class GFG { public static void main (String[] args) { }}
When java code is run, we can pass arguments at runtime as
command prompt > java <filename> argument1 arguement2 ........
or inside any favorite IDE like Eclipse also we can pass arguments at runtime as attached in screenshots
Example 1:
Java
// Java program to count the number of// command line arguments at runtime public class GFG { public static void main(String[] arguments) { String wordToFind = "GFG."; System.out.println("Arguments passed at runtime. " + "We can get that by using args.length and it is " + arguments.length + " here "); for(int i = 0; i < arguments.length; i++) { if (arguments[i].equalsIgnoreCase(wordToFind)) { System.out.println("Provided word "+ wordToFind + " is present " + "and it is at location " + (i+1)); } } }}
In Eclipse, we can provide arguments in the mentioned way :
Under Java Application β> Click on Arguments. Under Program Arguments, provide the required arguments as specified in the below screen
On running the code, we can see below output
Example 2: Find out whether βGFGβ is provided in the command line arguments
Java
// Java program to count// the number of arguments // using args.length // main() method is a static method which// gets called first when java program runspublic class GFG { public static void main(String[] arguments) { System.out.println("Arguments passed at runtime. "+ "We can get that by using args.length and it is = " + arguments.length + " here "); for(int i = 0; i < arguments.length; i++) { System.out.println("Argument " + i + " = " + arguments[i]); } }}
Using the command prompt, we can find the arguments as shown in the image below:
We can run the Java program using cmd prompt and the command line to find the number of arguments is:
java Class_Name βStatement β
It will give us the number of arguments in the double quotes.
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java
|
[
{
"code": null,
"e": 25347,
"s": 25319,
"text": "\n11 Nov, 2020"
},
{
"code": null,
"e": 25699,
"s": 25347,
"text": "The Java command-line argument is an argument that is passed at the time of running of a program. i.e. in order to make a program dynamic, there may be cases where we pass the arguments at runtime. Usually, via command-line arguments, they get passed and there are ways to find the number of arguments provided and also get the value of each argument."
},
{
"code": null,
"e": 26009,
"s": 25699,
"text": "Each Java program gets initiated via the main method which is static that means no instantiation is required for the main method. Directly we can call. Hence, a java file name is called, the first method to get started is main() method and it has an input argument which is of String[] (String array datatype)"
},
{
"code": null,
"e": 26018,
"s": 26009,
"text": "Syntax :"
},
{
"code": null,
"e": 26023,
"s": 26018,
"text": "Java"
},
{
"code": "// Java code with main method. // It has an input argument// with String[] datatype import java.io.*; class GFG { public static void main (String[] args) { }}",
"e": 26200,
"s": 26023,
"text": null
},
{
"code": null,
"e": 26259,
"s": 26200,
"text": "When java code is run, we can pass arguments at runtime as"
},
{
"code": null,
"e": 26322,
"s": 26259,
"text": "command prompt > java <filename> argument1 arguement2 ........"
},
{
"code": null,
"e": 26427,
"s": 26322,
"text": "or inside any favorite IDE like Eclipse also we can pass arguments at runtime as attached in screenshots"
},
{
"code": null,
"e": 26438,
"s": 26427,
"text": "Example 1:"
},
{
"code": null,
"e": 26443,
"s": 26438,
"text": "Java"
},
{
"code": "// Java program to count the number of// command line arguments at runtime public class GFG { public static void main(String[] arguments) { String wordToFind = \"GFG.\"; System.out.println(\"Arguments passed at runtime. \" + \"We can get that by using args.length and it is \" + arguments.length + \" here \"); for(int i = 0; i < arguments.length; i++) { if (arguments[i].equalsIgnoreCase(wordToFind)) { System.out.println(\"Provided word \"+ wordToFind + \" is present \" + \"and it is at location \" + (i+1)); } } }}",
"e": 27086,
"s": 26443,
"text": null
},
{
"code": null,
"e": 27146,
"s": 27086,
"text": "In Eclipse, we can provide arguments in the mentioned way :"
},
{
"code": null,
"e": 27281,
"s": 27146,
"text": "Under Java Application β> Click on Arguments. Under Program Arguments, provide the required arguments as specified in the below screen"
},
{
"code": null,
"e": 27326,
"s": 27281,
"text": "On running the code, we can see below output"
},
{
"code": null,
"e": 27402,
"s": 27326,
"text": "Example 2: Find out whether βGFGβ is provided in the command line arguments"
},
{
"code": null,
"e": 27407,
"s": 27402,
"text": "Java"
},
{
"code": "// Java program to count// the number of arguments // using args.length // main() method is a static method which// gets called first when java program runspublic class GFG { public static void main(String[] arguments) { System.out.println(\"Arguments passed at runtime. \"+ \"We can get that by using args.length and it is = \" + arguments.length + \" here \"); for(int i = 0; i < arguments.length; i++) { System.out.println(\"Argument \" + i + \" = \" + arguments[i]); } }}",
"e": 27990,
"s": 27407,
"text": null
},
{
"code": null,
"e": 28071,
"s": 27990,
"text": "Using the command prompt, we can find the arguments as shown in the image below:"
},
{
"code": null,
"e": 28173,
"s": 28071,
"text": "We can run the Java program using cmd prompt and the command line to find the number of arguments is:"
},
{
"code": null,
"e": 28203,
"s": 28173,
"text": " java Class_Name βStatement β"
},
{
"code": null,
"e": 28265,
"s": 28203,
"text": "It will give us the number of arguments in the double quotes."
},
{
"code": null,
"e": 28289,
"s": 28265,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28294,
"s": 28289,
"text": "Java"
},
{
"code": null,
"e": 28308,
"s": 28294,
"text": "Java Programs"
},
{
"code": null,
"e": 28327,
"s": 28308,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28332,
"s": 28327,
"text": "Java"
},
{
"code": null,
"e": 28430,
"s": 28332,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28445,
"s": 28430,
"text": "Stream In Java"
},
{
"code": null,
"e": 28466,
"s": 28445,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28485,
"s": 28466,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28515,
"s": 28485,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28561,
"s": 28515,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28587,
"s": 28561,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28621,
"s": 28587,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 28668,
"s": 28621,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 28700,
"s": 28668,
"text": "How to Iterate HashMap in Java?"
}
] |
Python Program to Form a Dictionary from an Object of a Class
|
When it is required to form a dictionary with the help of an object and class, a class is defined. An βinitβ function is defined, that assigns values to variables. An instance of the class is created, and the init function is called.
Below is a demonstration for the same β
Live Demo
class base_class(object):
def __init__(self):
self.A = 32
self.B = 60
my_instance = base_class()
print("An instance of the class has been created")
print(my_instance.__dict__)
An instance of the class has been created
{'A': 32, 'B': 60}
A βbase_classβ is defined, and an object is passed to it.
An βinitβ method is defined, and it assigns values to variables.
An instance of the method is created.
The method is called using the obect created, using β.β operator
|
[
{
"code": null,
"e": 1296,
"s": 1062,
"text": "When it is required to form a dictionary with the help of an object and class, a class is defined. An βinitβ function is defined, that assigns values to variables. An instance of the class is created, and the init function is called."
},
{
"code": null,
"e": 1336,
"s": 1296,
"text": "Below is a demonstration for the same β"
},
{
"code": null,
"e": 1347,
"s": 1336,
"text": " Live Demo"
},
{
"code": null,
"e": 1538,
"s": 1347,
"text": "class base_class(object):\n def __init__(self):\n self.A = 32\n self.B = 60\nmy_instance = base_class()\nprint(\"An instance of the class has been created\")\nprint(my_instance.__dict__)"
},
{
"code": null,
"e": 1599,
"s": 1538,
"text": "An instance of the class has been created\n{'A': 32, 'B': 60}"
},
{
"code": null,
"e": 1657,
"s": 1599,
"text": "A βbase_classβ is defined, and an object is passed to it."
},
{
"code": null,
"e": 1722,
"s": 1657,
"text": "An βinitβ method is defined, and it assigns values to variables."
},
{
"code": null,
"e": 1760,
"s": 1722,
"text": "An instance of the method is created."
},
{
"code": null,
"e": 1825,
"s": 1760,
"text": "The method is called using the obect created, using β.β operator"
}
] |
Google Charts - Basic Sankey Chart
|
Following is an example of a basic sankey diagram. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example.
We've used Sankey class to show sankey diagram.
//Map chart
var chart = new google.visualization.Sankey(document.getElementById('container'));
googlecharts_sankey_basic.htm
<html>
<head>
<title>Google Charts Tutorial</title>
<script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js">
</script>
<script type = "text/javascript" src = "https://www.google.com/jsapi"></script>
<script type = "text/javascript">
google.charts.load('current', {packages: ['sankey']});
</script>
</head>
<body>
<div id = "container" style = "width: 550px; height: 400px; margin: 0 auto">
</div>
<script language = "JavaScript">
function drawChart() {
// Define the chart to be drawn.
var data = new google.visualization.DataTable();
data.addColumn('string', 'From');
data.addColumn('string', 'To');
data.addColumn('number', 'Weight');
data.addRows([
[ 'Brazil', 'Portugal', 5 ],
[ 'Brazil', 'France', 1 ],
[ 'Brazil', 'Spain', 1 ],
[ 'Brazil', 'England', 1 ],
[ 'Canada', 'Portugal', 1 ],
[ 'Canada', 'France', 5 ],
[ 'Canada', 'England', 1 ],
[ 'Mexico', 'Portugal', 1 ],
[ 'Mexico', 'France', 1 ],
[ 'Mexico', 'Spain', 5 ],
[ 'Mexico', 'England', 1 ],
[ 'USA', 'Portugal', 1 ],
[ 'USA', 'France', 1 ],
[ 'USA', 'Spain', 1 ],
[ 'USA', 'England', 5 ]
]);
// Set chart options
var options = {width: 550};
// Instantiate and draw the chart.
var chart = new google.visualization.Sankey(document.getElementById('container'));
chart.draw(data, options);
}
google.charts.setOnLoadCallback(drawChart);
</script>
</body>
</html>
Verify the result.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2456,
"s": 2261,
"text": "Following is an example of a basic sankey diagram. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example."
},
{
"code": null,
"e": 2504,
"s": 2456,
"text": "We've used Sankey class to show sankey diagram."
},
{
"code": null,
"e": 2600,
"s": 2504,
"text": "//Map chart\nvar chart = new google.visualization.Sankey(document.getElementById('container'));\n"
},
{
"code": null,
"e": 2630,
"s": 2600,
"text": "googlecharts_sankey_basic.htm"
},
{
"code": null,
"e": 4538,
"s": 2630,
"text": "<html>\n <head>\n <title>Google Charts Tutorial</title>\n <script type = \"text/javascript\" src = \"https://www.gstatic.com/charts/loader.js\">\n </script>\n <script type = \"text/javascript\" src = \"https://www.google.com/jsapi\"></script>\n <script type = \"text/javascript\">\n google.charts.load('current', {packages: ['sankey']}); \n </script>\n </head>\n \n <body>\n <div id = \"container\" style = \"width: 550px; height: 400px; margin: 0 auto\">\n </div>\n <script language = \"JavaScript\">\n function drawChart() {\n // Define the chart to be drawn.\n var data = new google.visualization.DataTable(); \n data.addColumn('string', 'From');\n data.addColumn('string', 'To');\n data.addColumn('number', 'Weight');\n\n data.addRows([\n [ 'Brazil', 'Portugal', 5 ],\n [ 'Brazil', 'France', 1 ],\n [ 'Brazil', 'Spain', 1 ],\n [ 'Brazil', 'England', 1 ],\n \n [ 'Canada', 'Portugal', 1 ],\n [ 'Canada', 'France', 5 ],\n [ 'Canada', 'England', 1 ],\n \n [ 'Mexico', 'Portugal', 1 ],\n [ 'Mexico', 'France', 1 ],\n [ 'Mexico', 'Spain', 5 ],\n [ 'Mexico', 'England', 1 ],\n \n [ 'USA', 'Portugal', 1 ],\n [ 'USA', 'France', 1 ],\n [ 'USA', 'Spain', 1 ],\n [ 'USA', 'England', 5 ]\n ]);\t\n\n // Set chart options\n var options = {width: 550};\n \n // Instantiate and draw the chart.\n var chart = new google.visualization.Sankey(document.getElementById('container'));\n chart.draw(data, options);\n }\n google.charts.setOnLoadCallback(drawChart);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 4557,
"s": 4538,
"text": "Verify the result."
},
{
"code": null,
"e": 4564,
"s": 4557,
"text": " Print"
},
{
"code": null,
"e": 4575,
"s": 4564,
"text": " Add Notes"
}
] |
Creating Custom Activation Functions with Lambda Layers in TensorFlow 2 | by Arjun Sarkar | Towards Data Science
|
Previously weβve seen how to create custom loss functions β Creating custom Loss functions using TensorFlow 2
Introduction
In this article, we look at how to create custom activation functions. While TensorFlow already contains a bunch of activation functions inbuilt, there are ways to create your own custom activation function or to edit an existing activation function.
ReLU (Rectified Linear Unit) is still the most common activation function used in the hidden layers of any neural network architecture. ReLU can also be represented as a function f(x) where,
f(x) = 0, when x <0,
and, f(x) = x, when x β₯ 0.
Thus the function takes into consideration only the positive part, and is written as,
f(x) = max(0,x)
or in a code representation,
if input > 0: return inputelse: return 0
But this ReLU function is predefined. What if we want to customize this function or create our own ReLU activation. There is a very simple way to do this in TensorFlow β we just have to use Lambda layers.
How to use a lambda layer?
tf.keras.layers.Lambda(lambda x: tf.abs(x))
Lambda is just another layer that can be called directly in TensorFlow. Within the lambda layer, first, the parameter is specified. In the above code snippet, this value is βxβ (lambda x). In this case, we want to find the absolute value of x, so we use tf.abs(x). So if x has a value of -1, this lambda layer changes the value of x to 1.
How to use a lambda layer to create a custom ReLU?
def custom_relu(x): return K.maximum(0.0,x)model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(128,128)), tf.keras.layers.Dense(512), tf.keras.layers.Lambda(custom_relu), tf.keras.layers.Dense(5, activation = 'softmax')])
The above code snippet shows how a custom ReLU can be implemented in a TensorFlow model. We create a function custom_relu and return the maximum of 0 or x (same as the ReLU function would do).
In the sequential model below, after the Dense layer, we create a Lambda layer and pass it in the custom activation function. But this code still does not do anything different than what a ReLU activation function would do.
The fun starts when we start playing around with the return value of our custom function. Let's say we take the maximum of 0.5 and x, rather than 0 and x. There we have out, our own custom ReLU. These values can then be altered as required.
def custom_relu(x): return K.maximum(0.5,x)
def custom_relu(x): return K.maximum(0.5,x)model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(128,128)), tf.keras.layers.Dense(512), tf.keras.layers.Lambda(custom_relu), tf.keras.layers.Dense(5, activation = 'softmax')])
Example of using lambda activations on the mnist dataset
#using absolute value (Lambda layer example 1)import tensorflow as tffrom tensorflow.keras import backend as Kmnist = tf.keras.datasets.mnist(x_train, y_train),(x_test, y_test) = mnist.load_data()x_train, x_test = x_train / 255.0, x_test / 255.0model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128), tf.keras.layers.Lambda(lambda x: tf.abs(x)), tf.keras.layers.Dense(10, activation='softmax')])model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])model.fit(x_train, y_train, epochs=5)model.evaluate(x_test, y_test)
Replacing the ReLU activation with the absolute values on the mnist dataset gives a test accuracy of 97.384%.
#using custom ReLU activation (Lambda layer example 2)import tensorflow as tffrom tensorflow.keras import backend as Kmnist = tf.keras.datasets.mnist(x_train, y_train),(x_test, y_test) = mnist.load_data()x_train, x_test = x_train / 255.0, x_test / 255.0def my_relu(x): return K.maximum(-0.1, x)model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128), tf.keras.layers.Lambda(my_relu), tf.keras.layers.Dense(10, activation='softmax')])model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])model.fit(x_train, y_train, epochs=5)model.evaluate(x_test, y_test)
Replacing the ReLU activation with the custom ReLU activation, taking a maximum of -0.1 or x, on the mnist dataset gives a test accuracy of 97.778%.
Conclusion
Even though lambda layers are very simple to use, they have many limitations. In the next article, I will write about creating fully custom layers in TensorFlow that are also trainable.
|
[
{
"code": null,
"e": 282,
"s": 172,
"text": "Previously weβve seen how to create custom loss functions β Creating custom Loss functions using TensorFlow 2"
},
{
"code": null,
"e": 295,
"s": 282,
"text": "Introduction"
},
{
"code": null,
"e": 546,
"s": 295,
"text": "In this article, we look at how to create custom activation functions. While TensorFlow already contains a bunch of activation functions inbuilt, there are ways to create your own custom activation function or to edit an existing activation function."
},
{
"code": null,
"e": 737,
"s": 546,
"text": "ReLU (Rectified Linear Unit) is still the most common activation function used in the hidden layers of any neural network architecture. ReLU can also be represented as a function f(x) where,"
},
{
"code": null,
"e": 758,
"s": 737,
"text": "f(x) = 0, when x <0,"
},
{
"code": null,
"e": 785,
"s": 758,
"text": "and, f(x) = x, when x β₯ 0."
},
{
"code": null,
"e": 871,
"s": 785,
"text": "Thus the function takes into consideration only the positive part, and is written as,"
},
{
"code": null,
"e": 887,
"s": 871,
"text": "f(x) = max(0,x)"
},
{
"code": null,
"e": 916,
"s": 887,
"text": "or in a code representation,"
},
{
"code": null,
"e": 961,
"s": 916,
"text": "if input > 0: return inputelse: return 0"
},
{
"code": null,
"e": 1166,
"s": 961,
"text": "But this ReLU function is predefined. What if we want to customize this function or create our own ReLU activation. There is a very simple way to do this in TensorFlow β we just have to use Lambda layers."
},
{
"code": null,
"e": 1193,
"s": 1166,
"text": "How to use a lambda layer?"
},
{
"code": null,
"e": 1237,
"s": 1193,
"text": "tf.keras.layers.Lambda(lambda x: tf.abs(x))"
},
{
"code": null,
"e": 1576,
"s": 1237,
"text": "Lambda is just another layer that can be called directly in TensorFlow. Within the lambda layer, first, the parameter is specified. In the above code snippet, this value is βxβ (lambda x). In this case, we want to find the absolute value of x, so we use tf.abs(x). So if x has a value of -1, this lambda layer changes the value of x to 1."
},
{
"code": null,
"e": 1627,
"s": 1576,
"text": "How to use a lambda layer to create a custom ReLU?"
},
{
"code": null,
"e": 1890,
"s": 1627,
"text": "def custom_relu(x): return K.maximum(0.0,x)model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(128,128)), tf.keras.layers.Dense(512), tf.keras.layers.Lambda(custom_relu), tf.keras.layers.Dense(5, activation = 'softmax')])"
},
{
"code": null,
"e": 2083,
"s": 1890,
"text": "The above code snippet shows how a custom ReLU can be implemented in a TensorFlow model. We create a function custom_relu and return the maximum of 0 or x (same as the ReLU function would do)."
},
{
"code": null,
"e": 2307,
"s": 2083,
"text": "In the sequential model below, after the Dense layer, we create a Lambda layer and pass it in the custom activation function. But this code still does not do anything different than what a ReLU activation function would do."
},
{
"code": null,
"e": 2548,
"s": 2307,
"text": "The fun starts when we start playing around with the return value of our custom function. Let's say we take the maximum of 0.5 and x, rather than 0 and x. There we have out, our own custom ReLU. These values can then be altered as required."
},
{
"code": null,
"e": 2592,
"s": 2548,
"text": "def custom_relu(x): return K.maximum(0.5,x)"
},
{
"code": null,
"e": 2855,
"s": 2592,
"text": "def custom_relu(x): return K.maximum(0.5,x)model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(128,128)), tf.keras.layers.Dense(512), tf.keras.layers.Lambda(custom_relu), tf.keras.layers.Dense(5, activation = 'softmax')])"
},
{
"code": null,
"e": 2912,
"s": 2855,
"text": "Example of using lambda activations on the mnist dataset"
},
{
"code": null,
"e": 3555,
"s": 2912,
"text": "#using absolute value (Lambda layer example 1)import tensorflow as tffrom tensorflow.keras import backend as Kmnist = tf.keras.datasets.mnist(x_train, y_train),(x_test, y_test) = mnist.load_data()x_train, x_test = x_train / 255.0, x_test / 255.0model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128), tf.keras.layers.Lambda(lambda x: tf.abs(x)), tf.keras.layers.Dense(10, activation='softmax')])model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])model.fit(x_train, y_train, epochs=5)model.evaluate(x_test, y_test)"
},
{
"code": null,
"e": 3665,
"s": 3555,
"text": "Replacing the ReLU activation with the absolute values on the mnist dataset gives a test accuracy of 97.384%."
},
{
"code": null,
"e": 4356,
"s": 3665,
"text": "#using custom ReLU activation (Lambda layer example 2)import tensorflow as tffrom tensorflow.keras import backend as Kmnist = tf.keras.datasets.mnist(x_train, y_train),(x_test, y_test) = mnist.load_data()x_train, x_test = x_train / 255.0, x_test / 255.0def my_relu(x): return K.maximum(-0.1, x)model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128), tf.keras.layers.Lambda(my_relu), tf.keras.layers.Dense(10, activation='softmax')])model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])model.fit(x_train, y_train, epochs=5)model.evaluate(x_test, y_test)"
},
{
"code": null,
"e": 4505,
"s": 4356,
"text": "Replacing the ReLU activation with the custom ReLU activation, taking a maximum of -0.1 or x, on the mnist dataset gives a test accuracy of 97.778%."
},
{
"code": null,
"e": 4516,
"s": 4505,
"text": "Conclusion"
}
] |
How to use NavigationView in Android?
|
This example demonstrates how do I Use NavigationView in android.
Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project.
Step 2 β Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
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:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.drawerlayout.widget.DrawerLayout>
Step 3 β Add the following code to src/MainActivity.java
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow, R.id.nav_tools, R.id.nav_share,
R.id.nav_send).setDrawerLayout(drawer).build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration) || super.onSupportNavigateUp();
}
}
Step 4 β Create a Layout resource file (fragment_home.xml) and the following 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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text_home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step 5 β Create a Java class (HomeFragment.java) and add the following code β
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import app.com.myapplication.R;
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
final TextView textView = root.findViewById(R.id.text_home);
homeViewModel.getText().observe(this, new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
Step 6 β Create a Java class (HomeViewModel.java) and add the following code β
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import app.com.myapplication.R;
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
final TextView textView = root.findViewById(R.id.text_home);
homeViewModel.getText().observe(this, new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
Similar coding can be followed for other options like the gallery, send, share.
Kindly note the naming convention is very important.
Step 7 β Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β
Click here to download the project code.
|
[
{
"code": null,
"e": 1128,
"s": 1062,
"text": "This example demonstrates how do I Use NavigationView in android."
},
{
"code": null,
"e": 1257,
"s": 1128,
"text": "Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1322,
"s": 1257,
"text": "Step 2 β Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2276,
"s": 1322,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.drawerlayout.widget.DrawerLayout\nxmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/drawer_layout\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:fitsSystemWindows=\"true\"\n tools:openDrawer=\"start\">\n <com.google.android.material.navigation.NavigationView\n android:id=\"@+id/nav_view\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"match_parent\"\n android:layout_gravity=\"start\"\n android:fitsSystemWindows=\"true\"\n app:headerLayout=\"@layout/nav_header_main\"\n app:menu=\"@menu/activity_main_drawer\" />\n <include\n layout=\"@layout/app_bar_main\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n</androidx.drawerlayout.widget.DrawerLayout>"
},
{
"code": null,
"e": 2333,
"s": 2276,
"text": "Step 3 β Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4607,
"s": 2333,
"text": "import android.os.Bundle;\nimport com.google.android.material.floatingactionbutton.FloatingActionButton;\nimport com.google.android.material.snackbar.Snackbar;\nimport android.view.View;\nimport androidx.navigation.NavController;\nimport androidx.navigation.Navigation;\nimport androidx.navigation.ui.AppBarConfiguration;\nimport androidx.navigation.ui.NavigationUI;\nimport com.google.android.material.navigation.NavigationView;\nimport androidx.drawerlayout.widget.DrawerLayout;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.appcompat.widget.Toolbar;\nimport android.view.Menu;\npublic class MainActivity extends AppCompatActivity {\n private AppBarConfiguration mAppBarConfiguration;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Toolbar toolbar = findViewById(R.id.toolbar);\n setSupportActionBar(toolbar);\n FloatingActionButton fab = findViewById(R.id.fab);\n fab.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n Snackbar.make(view, \"Replace with your own action\", Snackbar.LENGTH_LONG).setAction(\"Action\", null).show();\n }\n });\n DrawerLayout drawer = findViewById(R.id.drawer_layout);\n NavigationView navigationView = findViewById(R.id.nav_view);\n mAppBarConfiguration = new AppBarConfiguration.Builder(\n R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow, R.id.nav_tools, R.id.nav_share,\n R.id.nav_send).setDrawerLayout(drawer).build();\n NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);\n NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);\n NavigationUI.setupWithNavController(navigationView, navController);\n }\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n @Override\n public boolean onSupportNavigateUp() {\n NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);\n return NavigationUI.navigateUp(navController, mAppBarConfiguration) || super.onSupportNavigateUp();\n }\n}"
},
{
"code": null,
"e": 4691,
"s": 4607,
"text": "Step 4 β Create a Layout resource file (fragment_home.xml) and the following code β"
},
{
"code": null,
"e": 5491,
"s": 4691,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout\nxmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n <TextView\n android:id=\"@+id/text_home\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginStart=\"8dp\"\n android:layout_marginTop=\"8dp\"\n android:layout_marginEnd=\"8dp\"\n android:textAlignment=\"center\"\n android:textSize=\"20sp\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n</androidx.constraintlayout.widget.ConstraintLayout>"
},
{
"code": null,
"e": 5569,
"s": 5491,
"text": "Step 5 β Create a Java class (HomeFragment.java) and add the following code β"
},
{
"code": null,
"e": 6585,
"s": 5569,
"text": "import android.os.Bundle;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.NonNull;\nimport androidx.fragment.app.Fragment;\nimport androidx.lifecycle.Observer;\nimport androidx.lifecycle.ViewModelProviders;\nimport app.com.myapplication.R;\npublic class HomeFragment extends Fragment {\n private HomeViewModel homeViewModel;\n public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);\n View root = inflater.inflate(R.layout.fragment_home, container, false);\n final TextView textView = root.findViewById(R.id.text_home);\n homeViewModel.getText().observe(this, new Observer<String>() {\n @Override\n public void onChanged(@Nullable String s) {\n textView.setText(s);\n }\n });\n return root;\n }\n}"
},
{
"code": null,
"e": 6664,
"s": 6585,
"text": "Step 6 β Create a Java class (HomeViewModel.java) and add the following code β"
},
{
"code": null,
"e": 7680,
"s": 6664,
"text": "import android.os.Bundle;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.NonNull;\nimport androidx.fragment.app.Fragment;\nimport androidx.lifecycle.Observer;\nimport androidx.lifecycle.ViewModelProviders;\nimport app.com.myapplication.R;\npublic class HomeFragment extends Fragment {\n private HomeViewModel homeViewModel;\n public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);\n View root = inflater.inflate(R.layout.fragment_home, container, false);\n final TextView textView = root.findViewById(R.id.text_home);\n homeViewModel.getText().observe(this, new Observer<String>() {\n @Override\n public void onChanged(@Nullable String s) {\n textView.setText(s);\n }\n });\n return root;\n }\n}"
},
{
"code": null,
"e": 7813,
"s": 7680,
"text": "Similar coding can be followed for other options like the gallery, send, share.\nKindly note the naming convention is very important."
},
{
"code": null,
"e": 7868,
"s": 7813,
"text": "Step 7 β Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 8667,
"s": 7868,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.myapplication\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity\n android:name=\".MainActivity\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme.NoActionBar\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 9018,
"s": 8667,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β"
},
{
"code": null,
"e": 9059,
"s": 9018,
"text": "Click here to download the project code."
}
] |
Implementation of Artificial Neural Network for AND Logic Gate with 2-bit Binary Input - GeeksforGeeks
|
29 May, 2021
Artificial Neural Network (ANN) is a computational model based on the biological neural networks of animal brains. ANN is modeled with three types of layers: an input layer, hidden layers (one or more), and an output layer. Each layer comprises nodes (like biological neurons) are called Artificial Neurons. All nodes are connected with weighted edges (like synapses in biological brains) between two layers. Initially, with the forward propagation function, the output is predicted. Then through backpropagation, the weight and bias to the nodes are updated to minimizing the error in prediction to attain the convergence of cost function in determining the final output. AND logical function truth table for 2-bit binary variables, i.e, the input vector and the corresponding output β
Approach: Step1: Import the required Python libraries Step2: Define Activation Function : Sigmoid Function Step3: Initialize neural network parameters (weights, bias) and define model hyperparameters (number of iterations, learning rate) Step4: Forward Propagation Step5: Backward Propagation Step6: Update weight and bias parameters Step7: Train the learning model Step8: Plot Loss value vs Epoch Step9: Test the model performance
Python Implementation:
Python3
# import Python Librariesimport numpy as npfrom matplotlib import pyplot as plt # Sigmoid Functiondef sigmoid(z): return 1 / (1 + np.exp(-z)) # Initialization of the neural network parameters# Initialized all the weights in the range of between 0 and 1# Bias values are initialized to 0def initializeParameters(inputFeatures, neuronsInHiddenLayers, outputFeatures): W1 = np.random.randn(neuronsInHiddenLayers, inputFeatures) W2 = np.random.randn(outputFeatures, neuronsInHiddenLayers) b1 = np.zeros((neuronsInHiddenLayers, 1)) b2 = np.zeros((outputFeatures, 1)) parameters = {"W1" : W1, "b1": b1, "W2" : W2, "b2": b2} return parameters # Forward Propagationdef forwardPropagation(X, Y, parameters): m = X.shape[1] W1 = parameters["W1"] W2 = parameters["W2"] b1 = parameters["b1"] b2 = parameters["b2"] Z1 = np.dot(W1, X) + b1 A1 = sigmoid(Z1) Z2 = np.dot(W2, A1) + b2 A2 = sigmoid(Z2) cache = (Z1, A1, W1, b1, Z2, A2, W2, b2) logprobs = np.multiply(np.log(A2), Y) + np.multiply(np.log(1 - A2), (1 - Y)) cost = -np.sum(logprobs) / m return cost, cache, A2 # Backward Propagationdef backwardPropagation(X, Y, cache): m = X.shape[1] (Z1, A1, W1, b1, Z2, A2, W2, b2) = cache dZ2 = A2 - Y dW2 = np.dot(dZ2, A1.T) / m db2 = np.sum(dZ2, axis = 1, keepdims = True) dA1 = np.dot(W2.T, dZ2) dZ1 = np.multiply(dA1, A1 * (1- A1)) dW1 = np.dot(dZ1, X.T) / m db1 = np.sum(dZ1, axis = 1, keepdims = True) / m gradients = {"dZ2": dZ2, "dW2": dW2, "db2": db2, "dZ1": dZ1, "dW1": dW1, "db1": db1} return gradients # Updating the weights based on the negative gradientsdef updateParameters(parameters, gradients, learningRate): parameters["W1"] = parameters["W1"] - learningRate * gradients["dW1"] parameters["W2"] = parameters["W2"] - learningRate * gradients["dW2"] parameters["b1"] = parameters["b1"] - learningRate * gradients["db1"] parameters["b2"] = parameters["b2"] - learningRate * gradients["db2"] return parameters # Model to learn the AND truth tableX = np.array([[0, 0, 1, 1], [0, 1, 0, 1]]) # AND inputY = np.array([[0, 0, 0, 1]]) # AND output # Define model parametersneuronsInHiddenLayers = 2 # number of hidden layer neurons (2)inputFeatures = X.shape[0] # number of input features (2)outputFeatures = Y.shape[0] # number of output features (1)parameters = initializeParameters(inputFeatures, neuronsInHiddenLayers, outputFeatures)epoch = 100000learningRate = 0.01losses = np.zeros((epoch, 1)) for i in range(epoch): losses[i, 0], cache, A2 = forwardPropagation(X, Y, parameters) gradients = backwardPropagation(X, Y, cache) parameters = updateParameters(parameters, gradients, learningRate) # Evaluating the performanceplt.figure()plt.plot(losses)plt.xlabel("EPOCHS")plt.ylabel("Loss value")plt.show() # TestingX = np.array([[1, 1, 0, 0], [0, 1, 0, 1]]) # AND inputcost, _, A2 = forwardPropagation(X, Y, parameters)prediction = (A2 > 0.5) * 1.0# print(A2)print(prediction)
[[ 0. 1. 0. 0.]]
Here, the model predicted output for each of the test inputs are exactly matched with the AND logic gate conventional output () according to the truth table and the cost function is also continuously converging. Hence, it signifies that the Artificial Neural Network for the AND logic gate is correctly implemented.
Akanksha_Rai
Neural Network
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Decision Tree
Python | Decision tree implementation
Search Algorithms in AI
Decision Tree Introduction with example
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": 25618,
"s": 25590,
"text": "\n29 May, 2021"
},
{
"code": null,
"e": 26406,
"s": 25618,
"text": "Artificial Neural Network (ANN) is a computational model based on the biological neural networks of animal brains. ANN is modeled with three types of layers: an input layer, hidden layers (one or more), and an output layer. Each layer comprises nodes (like biological neurons) are called Artificial Neurons. All nodes are connected with weighted edges (like synapses in biological brains) between two layers. Initially, with the forward propagation function, the output is predicted. Then through backpropagation, the weight and bias to the nodes are updated to minimizing the error in prediction to attain the convergence of cost function in determining the final output. AND logical function truth table for 2-bit binary variables, i.e, the input vector and the corresponding output β "
},
{
"code": null,
"e": 26844,
"s": 26410,
"text": "Approach: Step1: Import the required Python libraries Step2: Define Activation Function : Sigmoid Function Step3: Initialize neural network parameters (weights, bias) and define model hyperparameters (number of iterations, learning rate) Step4: Forward Propagation Step5: Backward Propagation Step6: Update weight and bias parameters Step7: Train the learning model Step8: Plot Loss value vs Epoch Step9: Test the model performance "
},
{
"code": null,
"e": 26869,
"s": 26844,
"text": "Python Implementation: "
},
{
"code": null,
"e": 26877,
"s": 26869,
"text": "Python3"
},
{
"code": "# import Python Librariesimport numpy as npfrom matplotlib import pyplot as plt # Sigmoid Functiondef sigmoid(z): return 1 / (1 + np.exp(-z)) # Initialization of the neural network parameters# Initialized all the weights in the range of between 0 and 1# Bias values are initialized to 0def initializeParameters(inputFeatures, neuronsInHiddenLayers, outputFeatures): W1 = np.random.randn(neuronsInHiddenLayers, inputFeatures) W2 = np.random.randn(outputFeatures, neuronsInHiddenLayers) b1 = np.zeros((neuronsInHiddenLayers, 1)) b2 = np.zeros((outputFeatures, 1)) parameters = {\"W1\" : W1, \"b1\": b1, \"W2\" : W2, \"b2\": b2} return parameters # Forward Propagationdef forwardPropagation(X, Y, parameters): m = X.shape[1] W1 = parameters[\"W1\"] W2 = parameters[\"W2\"] b1 = parameters[\"b1\"] b2 = parameters[\"b2\"] Z1 = np.dot(W1, X) + b1 A1 = sigmoid(Z1) Z2 = np.dot(W2, A1) + b2 A2 = sigmoid(Z2) cache = (Z1, A1, W1, b1, Z2, A2, W2, b2) logprobs = np.multiply(np.log(A2), Y) + np.multiply(np.log(1 - A2), (1 - Y)) cost = -np.sum(logprobs) / m return cost, cache, A2 # Backward Propagationdef backwardPropagation(X, Y, cache): m = X.shape[1] (Z1, A1, W1, b1, Z2, A2, W2, b2) = cache dZ2 = A2 - Y dW2 = np.dot(dZ2, A1.T) / m db2 = np.sum(dZ2, axis = 1, keepdims = True) dA1 = np.dot(W2.T, dZ2) dZ1 = np.multiply(dA1, A1 * (1- A1)) dW1 = np.dot(dZ1, X.T) / m db1 = np.sum(dZ1, axis = 1, keepdims = True) / m gradients = {\"dZ2\": dZ2, \"dW2\": dW2, \"db2\": db2, \"dZ1\": dZ1, \"dW1\": dW1, \"db1\": db1} return gradients # Updating the weights based on the negative gradientsdef updateParameters(parameters, gradients, learningRate): parameters[\"W1\"] = parameters[\"W1\"] - learningRate * gradients[\"dW1\"] parameters[\"W2\"] = parameters[\"W2\"] - learningRate * gradients[\"dW2\"] parameters[\"b1\"] = parameters[\"b1\"] - learningRate * gradients[\"db1\"] parameters[\"b2\"] = parameters[\"b2\"] - learningRate * gradients[\"db2\"] return parameters # Model to learn the AND truth tableX = np.array([[0, 0, 1, 1], [0, 1, 0, 1]]) # AND inputY = np.array([[0, 0, 0, 1]]) # AND output # Define model parametersneuronsInHiddenLayers = 2 # number of hidden layer neurons (2)inputFeatures = X.shape[0] # number of input features (2)outputFeatures = Y.shape[0] # number of output features (1)parameters = initializeParameters(inputFeatures, neuronsInHiddenLayers, outputFeatures)epoch = 100000learningRate = 0.01losses = np.zeros((epoch, 1)) for i in range(epoch): losses[i, 0], cache, A2 = forwardPropagation(X, Y, parameters) gradients = backwardPropagation(X, Y, cache) parameters = updateParameters(parameters, gradients, learningRate) # Evaluating the performanceplt.figure()plt.plot(losses)plt.xlabel(\"EPOCHS\")plt.ylabel(\"Loss value\")plt.show() # TestingX = np.array([[1, 1, 0, 0], [0, 1, 0, 1]]) # AND inputcost, _, A2 = forwardPropagation(X, Y, parameters)prediction = (A2 > 0.5) * 1.0# print(A2)print(prediction)",
"e": 29921,
"s": 26877,
"text": null
},
{
"code": null,
"e": 29943,
"s": 29923,
"text": "[[ 0. 1. 0. 0.]]"
},
{
"code": null,
"e": 30262,
"s": 29945,
"text": "Here, the model predicted output for each of the test inputs are exactly matched with the AND logic gate conventional output () according to the truth table and the cost function is also continuously converging. Hence, it signifies that the Artificial Neural Network for the AND logic gate is correctly implemented. "
},
{
"code": null,
"e": 30275,
"s": 30262,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 30290,
"s": 30275,
"text": "Neural Network"
},
{
"code": null,
"e": 30307,
"s": 30290,
"text": "Machine Learning"
},
{
"code": null,
"e": 30314,
"s": 30307,
"text": "Python"
},
{
"code": null,
"e": 30331,
"s": 30314,
"text": "Machine Learning"
},
{
"code": null,
"e": 30429,
"s": 30331,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30452,
"s": 30429,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 30466,
"s": 30452,
"text": "Decision Tree"
},
{
"code": null,
"e": 30504,
"s": 30466,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 30528,
"s": 30504,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 30568,
"s": 30528,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 30596,
"s": 30568,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 30646,
"s": 30596,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 30668,
"s": 30646,
"text": "Python map() function"
}
] |
Makefile - Other Features
|
In this chapter, we shall look into various other features of Makefile.
Recursive use of make means using make as a command in a makefile. This technique is useful when you want separate makefiles for various subsystems that compose a larger system. For example, suppose you have a subdirectory named `subdir' which has its own makefile, and you would like the containing directory's makefile to run make on the subdirectory. You can do it by writing the below code β
subsystem:
cd subdir && $(MAKE)
or, equivalently:
subsystem:
$(MAKE) -C subdir
You can write recursive make commands just by copying this example. However, you need to know about how they work and why, and how the sub-make relates to the top-level make.
Variable values of the top-level make can be passed to the sub-make through the environment by explicit request. These variables are defined in the sub-make as defaults. You cannot override what is specified in the makefile used by the sub-make makefile unless you use the `-e' switch.
To pass down, or export, a variable, make adds the variable and its value to the environment for running each command. The sub-make, in turn, uses the environment to initialize its table of variable values.
The special variables SHELL and MAKEFLAGS are always exported (unless you unexport them). MAKEFILES is exported if you set it to anything.
If you want to export specific variables to a sub-make, use the export directive, as shown below β
export variable ...
If you want to prevent a variable from being exported, use the unexport directive, as shown below β
unexport variable ...
If the environment variable MAKEFILES is defined, make considers its value as a list of names (separated by white space) of additional makefiles to be read before the others. This works much like the include directive: various directories are searched for those files.
The main use of MAKEFILES is in communication between recursive invocations of the make.
If you have put the header files in different directories and you are running make in a different directory, then it is required to provide the path of header files. This can be done using -I option in makefile. Assuming that functions.h file is available in /home/tutorialspoint/header folder and rest of the files are available in /home/tutorialspoint/src/ folder, then the makefile would be written as follows β
INCLUDES = -I "/home/tutorialspoint/header"
CC = gcc
LIBS = -lm
CFLAGS = -g -Wall
OBJ = main.o factorial.o hello.o
hello: ${OBJ}
${CC} ${CFLAGS} ${INCLUDES} -o $@ ${OBJS} ${LIBS}
.cpp.o:
${CC} ${CFLAGS} ${INCLUDES} -c $<
Often it is useful to add more text to the value of a variable already defined. You do this with a line containing `+=', as shown β
objects += another.o
It takes the value of the variable objects, and adds the text `another.o' to it, preceded by a single space as shown below.
objects = main.o hello.o factorial.o
objects += another.o
The above code sets objects to `main.o hello.o factorial.o another.o'.
Using `+=' is similar to:
objects = main.o hello.o factorial.o
objects := $(objects) another.o
If you do not like too big lines in your Makefile, then you can break your line using a back-slash "\" as shown below β
OBJ = main.o factorial.o \
hello.o
is equivalent to
OBJ = main.o factorial.o hello.o
If you have prepared the Makefile with name "Makefile", then simply write make at command prompt and it will run the Makefile file. But if you have given any other name to the Makefile, then use the following command β
make -f your-makefile-name
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1856,
"s": 1784,
"text": "In this chapter, we shall look into various other features of Makefile."
},
{
"code": null,
"e": 2252,
"s": 1856,
"text": "Recursive use of make means using make as a command in a makefile. This technique is useful when you want separate makefiles for various subsystems that compose a larger system. For example, suppose you have a subdirectory named `subdir' which has its own makefile, and you would like the containing directory's makefile to run make on the subdirectory. You can do it by writing the below code β"
},
{
"code": null,
"e": 2341,
"s": 2252,
"text": "subsystem:\n cd subdir && $(MAKE)\n\nor, equivalently:\n \t\nsubsystem:\n $(MAKE) -C subdir"
},
{
"code": null,
"e": 2516,
"s": 2341,
"text": "You can write recursive make commands just by copying this example. However, you need to know about how they work and why, and how the sub-make relates to the top-level make."
},
{
"code": null,
"e": 2802,
"s": 2516,
"text": "Variable values of the top-level make can be passed to the sub-make through the environment by explicit request. These variables are defined in the sub-make as defaults. You cannot override what is specified in the makefile used by the sub-make makefile unless you use the `-e' switch."
},
{
"code": null,
"e": 3009,
"s": 2802,
"text": "To pass down, or export, a variable, make adds the variable and its value to the environment for running each command. The sub-make, in turn, uses the environment to initialize its table of variable values."
},
{
"code": null,
"e": 3148,
"s": 3009,
"text": "The special variables SHELL and MAKEFLAGS are always exported (unless you unexport them). MAKEFILES is exported if you set it to anything."
},
{
"code": null,
"e": 3247,
"s": 3148,
"text": "If you want to export specific variables to a sub-make, use the export directive, as shown below β"
},
{
"code": null,
"e": 3268,
"s": 3247,
"text": "export variable ...\n"
},
{
"code": null,
"e": 3368,
"s": 3268,
"text": "If you want to prevent a variable from being exported, use the unexport directive, as shown below β"
},
{
"code": null,
"e": 3391,
"s": 3368,
"text": "unexport variable ...\n"
},
{
"code": null,
"e": 3660,
"s": 3391,
"text": "If the environment variable MAKEFILES is defined, make considers its value as a list of names (separated by white space) of additional makefiles to be read before the others. This works much like the include directive: various directories are searched for those files."
},
{
"code": null,
"e": 3749,
"s": 3660,
"text": "The main use of MAKEFILES is in communication between recursive invocations of the make."
},
{
"code": null,
"e": 4164,
"s": 3749,
"text": "If you have put the header files in different directories and you are running make in a different directory, then it is required to provide the path of header files. This can be done using -I option in makefile. Assuming that functions.h file is available in /home/tutorialspoint/header folder and rest of the files are available in /home/tutorialspoint/src/ folder, then the makefile would be written as follows β"
},
{
"code": null,
"e": 4394,
"s": 4164,
"text": "INCLUDES = -I \"/home/tutorialspoint/header\"\nCC = gcc\nLIBS = -lm\nCFLAGS = -g -Wall\nOBJ = main.o factorial.o hello.o\n\nhello: ${OBJ}\n ${CC} ${CFLAGS} ${INCLUDES} -o $@ ${OBJS} ${LIBS}\n.cpp.o:\n ${CC} ${CFLAGS} ${INCLUDES} -c $<"
},
{
"code": null,
"e": 4526,
"s": 4394,
"text": "Often it is useful to add more text to the value of a variable already defined. You do this with a line containing `+=', as shown β"
},
{
"code": null,
"e": 4548,
"s": 4526,
"text": "objects += another.o\n"
},
{
"code": null,
"e": 4672,
"s": 4548,
"text": "It takes the value of the variable objects, and adds the text `another.o' to it, preceded by a single space as shown below."
},
{
"code": null,
"e": 4730,
"s": 4672,
"text": "objects = main.o hello.o factorial.o\nobjects += another.o"
},
{
"code": null,
"e": 4801,
"s": 4730,
"text": "The above code sets objects to `main.o hello.o factorial.o another.o'."
},
{
"code": null,
"e": 4827,
"s": 4801,
"text": "Using `+=' is similar to:"
},
{
"code": null,
"e": 4896,
"s": 4827,
"text": "objects = main.o hello.o factorial.o\nobjects := $(objects) another.o"
},
{
"code": null,
"e": 5016,
"s": 4896,
"text": "If you do not like too big lines in your Makefile, then you can break your line using a back-slash \"\\\" as shown below β"
},
{
"code": null,
"e": 5108,
"s": 5016,
"text": "OBJ = main.o factorial.o \\\n hello.o\n\nis equivalent to\n\nOBJ = main.o factorial.o hello.o"
},
{
"code": null,
"e": 5327,
"s": 5108,
"text": "If you have prepared the Makefile with name \"Makefile\", then simply write make at command prompt and it will run the Makefile file. But if you have given any other name to the Makefile, then use the following command β"
},
{
"code": null,
"e": 5355,
"s": 5327,
"text": "make -f your-makefile-name\n"
},
{
"code": null,
"e": 5362,
"s": 5355,
"text": " Print"
},
{
"code": null,
"e": 5373,
"s": 5362,
"text": " Add Notes"
}
] |
VB.Net - Basic Syntax
|
VB.Net is an object-oriented programming language. In Object-Oriented Programming methodology, a program consists of various objects that interact with each other by means of actions. The actions that an object may take are called methods. Objects of the same kind are said to have the same type or, more often, are said to be in the same class.
When we consider a VB.Net program, it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what do class, object, methods and instance variables mean.
Object β Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors - wagging, barking, eating, etc. An object is an instance of a class.
Object β Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors - wagging, barking, eating, etc. An object is an instance of a class.
Class β A class can be defined as a template/blueprint that describes the behaviors/states that objects of its type support.
Class β A class can be defined as a template/blueprint that describes the behaviors/states that objects of its type support.
Methods β A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
Methods β A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
Instance Variables β Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.
Instance Variables β Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.
For example, let us consider a Rectangle object. It has attributes like length and width. Depending upon the design, it may need ways for accepting the values of these attributes, calculating area and displaying details.
Let us look at an implementation of a Rectangle class and discuss VB.Net basic syntax on the basis of our observations in it β
Imports System
Public Class Rectangle
Private length As Double
Private width As Double
'Public methods
Public Sub AcceptDetails()
length = 4.5
width = 3.5
End Sub
Public Function GetArea() As Double
GetArea = length * width
End Function
Public Sub Display()
Console.WriteLine("Length: {0}", length)
Console.WriteLine("Width: {0}", width)
Console.WriteLine("Area: {0}", GetArea())
End Sub
Shared Sub Main()
Dim r As New Rectangle()
r.Acceptdetails()
r.Display()
Console.ReadLine()
End Sub
End Class
When the above code is compiled and executed, it produces the following result β
Length: 4.5
Width: 3.5
Area: 15.75
In previous chapter, we created a Visual Basic module that held the code. Sub Main indicates the entry point of VB.Net program. Here, we are using Class that contains both code and data. You use classes to create objects. For example, in the code, r is a Rectangle object.
An object is an instance of a class β
Dim r As New Rectangle()
A class may have members that can be accessible from outside class, if so specified. Data members are called fields and procedure members are called methods.
Shared methods or static methods can be invoked without creating an object of the class. Instance methods are invoked through an object of the class β
Shared Sub Main()
Dim r As New Rectangle()
r.Acceptdetails()
r.Display()
Console.ReadLine()
End Sub
An identifier is a name used to identify a class, variable, function, or any other user-defined item. The basic rules for naming classes in VB.Net are as follows β
A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit.
A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit.
It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used.
It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used.
It should not be a reserved keyword.
It should not be a reserved keyword.
The following table lists the VB.Net reserved keywords β
63 Lectures
4 hours
Frahaan Hussain
103 Lectures
12 hours
Arnold Higuit
60 Lectures
9.5 hours
Arnold Higuit
97 Lectures
9 hours
Arnold Higuit
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2646,
"s": 2300,
"text": "VB.Net is an object-oriented programming language. In Object-Oriented Programming methodology, a program consists of various objects that interact with each other by means of actions. The actions that an object may take are called methods. Objects of the same kind are said to have the same type or, more often, are said to be in the same class."
},
{
"code": null,
"e": 2868,
"s": 2646,
"text": "When we consider a VB.Net program, it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what do class, object, methods and instance variables mean."
},
{
"code": null,
"e": 3050,
"s": 2868,
"text": "Object β Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors - wagging, barking, eating, etc. An object is an instance of a class."
},
{
"code": null,
"e": 3232,
"s": 3050,
"text": "Object β Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors - wagging, barking, eating, etc. An object is an instance of a class."
},
{
"code": null,
"e": 3357,
"s": 3232,
"text": "Class β A class can be defined as a template/blueprint that describes the behaviors/states that objects of its type support."
},
{
"code": null,
"e": 3482,
"s": 3357,
"text": "Class β A class can be defined as a template/blueprint that describes the behaviors/states that objects of its type support."
},
{
"code": null,
"e": 3661,
"s": 3482,
"text": "Methods β A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed."
},
{
"code": null,
"e": 3840,
"s": 3661,
"text": "Methods β A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed."
},
{
"code": null,
"e": 3996,
"s": 3840,
"text": "Instance Variables β Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables."
},
{
"code": null,
"e": 4152,
"s": 3996,
"text": "Instance Variables β Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables."
},
{
"code": null,
"e": 4373,
"s": 4152,
"text": "For example, let us consider a Rectangle object. It has attributes like length and width. Depending upon the design, it may need ways for accepting the values of these attributes, calculating area and displaying details."
},
{
"code": null,
"e": 4500,
"s": 4373,
"text": "Let us look at an implementation of a Rectangle class and discuss VB.Net basic syntax on the basis of our observations in it β"
},
{
"code": null,
"e": 5095,
"s": 4500,
"text": "Imports System\nPublic Class Rectangle\n Private length As Double\n Private width As Double\n\n 'Public methods\n Public Sub AcceptDetails()\n length = 4.5\n width = 3.5\n End Sub\n\n Public Function GetArea() As Double\n GetArea = length * width\n End Function\n Public Sub Display()\n Console.WriteLine(\"Length: {0}\", length)\n Console.WriteLine(\"Width: {0}\", width)\n Console.WriteLine(\"Area: {0}\", GetArea())\n\n End Sub\n\n Shared Sub Main()\n Dim r As New Rectangle()\n r.Acceptdetails()\n r.Display()\n Console.ReadLine()\n End Sub\nEnd Class"
},
{
"code": null,
"e": 5176,
"s": 5095,
"text": "When the above code is compiled and executed, it produces the following result β"
},
{
"code": null,
"e": 5212,
"s": 5176,
"text": "Length: 4.5\nWidth: 3.5\nArea: 15.75\n"
},
{
"code": null,
"e": 5485,
"s": 5212,
"text": "In previous chapter, we created a Visual Basic module that held the code. Sub Main indicates the entry point of VB.Net program. Here, we are using Class that contains both code and data. You use classes to create objects. For example, in the code, r is a Rectangle object."
},
{
"code": null,
"e": 5523,
"s": 5485,
"text": "An object is an instance of a class β"
},
{
"code": null,
"e": 5549,
"s": 5523,
"text": "Dim r As New Rectangle()\n"
},
{
"code": null,
"e": 5707,
"s": 5549,
"text": "A class may have members that can be accessible from outside class, if so specified. Data members are called fields and procedure members are called methods."
},
{
"code": null,
"e": 5858,
"s": 5707,
"text": "Shared methods or static methods can be invoked without creating an object of the class. Instance methods are invoked through an object of the class β"
},
{
"code": null,
"e": 5970,
"s": 5858,
"text": "Shared Sub Main()\n Dim r As New Rectangle()\n r.Acceptdetails()\n r.Display()\n Console.ReadLine()\nEnd Sub"
},
{
"code": null,
"e": 6134,
"s": 5970,
"text": "An identifier is a name used to identify a class, variable, function, or any other user-defined item. The basic rules for naming classes in VB.Net are as follows β"
},
{
"code": null,
"e": 6301,
"s": 6134,
"text": "A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit."
},
{
"code": null,
"e": 6468,
"s": 6301,
"text": "A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit."
},
{
"code": null,
"e": 6614,
"s": 6468,
"text": "It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ] { } . ; : \" ' / and \\. However, an underscore ( _ ) can be used."
},
{
"code": null,
"e": 6760,
"s": 6614,
"text": "It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ] { } . ; : \" ' / and \\. However, an underscore ( _ ) can be used."
},
{
"code": null,
"e": 6797,
"s": 6760,
"text": "It should not be a reserved keyword."
},
{
"code": null,
"e": 6834,
"s": 6797,
"text": "It should not be a reserved keyword."
},
{
"code": null,
"e": 6891,
"s": 6834,
"text": "The following table lists the VB.Net reserved keywords β"
},
{
"code": null,
"e": 6924,
"s": 6891,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6941,
"s": 6924,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6976,
"s": 6941,
"text": "\n 103 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 6991,
"s": 6976,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 7026,
"s": 6991,
"text": "\n 60 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 7041,
"s": 7026,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 7074,
"s": 7041,
"text": "\n 97 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 7089,
"s": 7074,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 7096,
"s": 7089,
"text": " Print"
},
{
"code": null,
"e": 7107,
"s": 7096,
"text": " Add Notes"
}
] |
pipe() - Unix, Linux System Call
|
Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright Β© 2014 by tutorialspoint
int pipe(int filedes[2]);
#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int
main(int argc, char *argv[])
{
int pfd[2];
pid_t cpid;
char buf;
assert(argc == 2);
if (pipe(pfd) == -1) { perror("pipe"); exit(EXIT_FAILURE); }
cpid = fork();
if (cpid == -1) { perror("fork"); exit(EXIT_FAILURE); }
if (cpid == 0) { /* Child reads from pipe */
close(pfd[1]); /* Close unused write end */
while (read(pfd[0], &buf, 1) > 0)
write(STDOUT_FILENO, &buf, 1);
write(STDOUT_FILENO, "\n", 1);
close(pfd[0]);
_exit(EXIT_SUCCESS);
} else { /* Parent writes argv[1] to pipe */
close(pfd[0]); /* Close unused read end */
write(pfd[1], argv[1], strlen(argv[1]));
close(pfd[1]); /* Reader will see EOF */
wait(NULL); /* Wait for child */
exit(EXIT_SUCCESS);
}
}
#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int
main(int argc, char *argv[])
{
int pfd[2];
pid_t cpid;
char buf;
assert(argc == 2);
if (pipe(pfd) == -1) { perror("pipe"); exit(EXIT_FAILURE); }
cpid = fork();
if (cpid == -1) { perror("fork"); exit(EXIT_FAILURE); }
if (cpid == 0) { /* Child reads from pipe */
close(pfd[1]); /* Close unused write end */
while (read(pfd[0], &buf, 1) > 0)
write(STDOUT_FILENO, &buf, 1);
write(STDOUT_FILENO, "\n", 1);
close(pfd[0]);
_exit(EXIT_SUCCESS);
} else { /* Parent writes argv[1] to pipe */
close(pfd[0]); /* Close unused read end */
write(pfd[1], argv[1], strlen(argv[1]));
close(pfd[1]); /* Reader will see EOF */
wait(NULL); /* Wait for child */
exit(EXIT_SUCCESS);
}
}
fork (2)
fork (2)
read (2)
read (2)
socketpair (2)
socketpair (2)
write (2)
write (2)
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1466,
"s": 1454,
"text": "Unix - Home"
},
{
"code": null,
"e": 1489,
"s": 1466,
"text": "Unix - Getting Started"
},
{
"code": null,
"e": 1512,
"s": 1489,
"text": "Unix - File Management"
},
{
"code": null,
"e": 1531,
"s": 1512,
"text": "Unix - Directories"
},
{
"code": null,
"e": 1554,
"s": 1531,
"text": "Unix - File Permission"
},
{
"code": null,
"e": 1573,
"s": 1554,
"text": "Unix - Environment"
},
{
"code": null,
"e": 1596,
"s": 1573,
"text": "Unix - Basic Utilities"
},
{
"code": null,
"e": 1619,
"s": 1596,
"text": "Unix - Pipes & Filters"
},
{
"code": null,
"e": 1636,
"s": 1619,
"text": "Unix - Processes"
},
{
"code": null,
"e": 1657,
"s": 1636,
"text": "Unix - Communication"
},
{
"code": null,
"e": 1678,
"s": 1657,
"text": "Unix - The vi Editor"
},
{
"code": null,
"e": 1700,
"s": 1678,
"text": "Unix - What is Shell?"
},
{
"code": null,
"e": 1723,
"s": 1700,
"text": "Unix - Using Variables"
},
{
"code": null,
"e": 1748,
"s": 1723,
"text": "Unix - Special Variables"
},
{
"code": null,
"e": 1768,
"s": 1748,
"text": "Unix - Using Arrays"
},
{
"code": null,
"e": 1791,
"s": 1768,
"text": "Unix - Basic Operators"
},
{
"code": null,
"e": 1814,
"s": 1791,
"text": "Unix - Decision Making"
},
{
"code": null,
"e": 1833,
"s": 1814,
"text": "Unix - Shell Loops"
},
{
"code": null,
"e": 1853,
"s": 1833,
"text": "Unix - Loop Control"
},
{
"code": null,
"e": 1880,
"s": 1853,
"text": "Unix - Shell Substitutions"
},
{
"code": null,
"e": 1906,
"s": 1880,
"text": "Unix - Quoting Mechanisms"
},
{
"code": null,
"e": 1929,
"s": 1906,
"text": "Unix - IO Redirections"
},
{
"code": null,
"e": 1952,
"s": 1929,
"text": "Unix - Shell Functions"
},
{
"code": null,
"e": 1972,
"s": 1952,
"text": "Unix - Manpage Help"
},
{
"code": null,
"e": 1999,
"s": 1972,
"text": "Unix - Regular Expressions"
},
{
"code": null,
"e": 2025,
"s": 1999,
"text": "Unix - File System Basics"
},
{
"code": null,
"e": 2052,
"s": 2025,
"text": "Unix - User Administration"
},
{
"code": null,
"e": 2078,
"s": 2052,
"text": "Unix - System Performance"
},
{
"code": null,
"e": 2100,
"s": 2078,
"text": "Unix - System Logging"
},
{
"code": null,
"e": 2125,
"s": 2100,
"text": "Unix - Signals and Traps"
},
{
"code": null,
"e": 2148,
"s": 2125,
"text": "Unix - Useful Commands"
},
{
"code": null,
"e": 2167,
"s": 2148,
"text": "Unix - Quick Guide"
},
{
"code": null,
"e": 2192,
"s": 2167,
"text": "Unix - Builtin Functions"
},
{
"code": null,
"e": 2212,
"s": 2192,
"text": "Unix - System Calls"
},
{
"code": null,
"e": 2233,
"s": 2212,
"text": "Unix - Commands List"
},
{
"code": null,
"e": 2255,
"s": 2233,
"text": "Unix Useful Resources"
},
{
"code": null,
"e": 2273,
"s": 2255,
"text": "Computer Glossary"
},
{
"code": null,
"e": 2284,
"s": 2273,
"text": "Who is Who"
},
{
"code": null,
"e": 2319,
"s": 2284,
"text": "Copyright Β© 2014 by tutorialspoint"
},
{
"code": null,
"e": 2347,
"s": 2319,
"text": "\nint pipe(int filedes[2]); "
},
{
"code": null,
"e": 3332,
"s": 2347,
"text": "\n#include <sys/wait.h>\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string.h>\n\nint\nmain(int argc, char *argv[])\n{\n int pfd[2];\n pid_t cpid;\n char buf;\n\n assert(argc == 2);\n\n if (pipe(pfd) == -1) { perror(\"pipe\"); exit(EXIT_FAILURE); }\n\n cpid = fork();\n if (cpid == -1) { perror(\"fork\"); exit(EXIT_FAILURE); }\n\n if (cpid == 0) { /* Child reads from pipe */\n close(pfd[1]); /* Close unused write end */\n\n while (read(pfd[0], &buf, 1) > 0)\n write(STDOUT_FILENO, &buf, 1);\n\n write(STDOUT_FILENO, \"\\n\", 1);\n close(pfd[0]);\n _exit(EXIT_SUCCESS);\n\n } else { /* Parent writes argv[1] to pipe */\n close(pfd[0]); /* Close unused read end */\n write(pfd[1], argv[1], strlen(argv[1]));\n close(pfd[1]); /* Reader will see EOF */\n wait(NULL); /* Wait for child */\n exit(EXIT_SUCCESS);\n }\n}\n\n"
},
{
"code": null,
"e": 3455,
"s": 3332,
"text": "\n#include <sys/wait.h>\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string.h>\n"
},
{
"code": null,
"e": 3538,
"s": 3455,
"text": "\nint\nmain(int argc, char *argv[])\n{\n int pfd[2];\n pid_t cpid;\n char buf;\n"
},
{
"code": null,
"e": 3563,
"s": 3538,
"text": "\n assert(argc == 2);\n"
},
{
"code": null,
"e": 3630,
"s": 3563,
"text": "\n if (pipe(pfd) == -1) { perror(\"pipe\"); exit(EXIT_FAILURE); }\n"
},
{
"code": null,
"e": 3711,
"s": 3630,
"text": "\n cpid = fork();\n if (cpid == -1) { perror(\"fork\"); exit(EXIT_FAILURE); }\n"
},
{
"code": null,
"e": 3826,
"s": 3711,
"text": "\n if (cpid == 0) { /* Child reads from pipe */\n close(pfd[1]); /* Close unused write end */\n"
},
{
"code": null,
"e": 3913,
"s": 3826,
"text": "\n while (read(pfd[0], &buf, 1) > 0)\n write(STDOUT_FILENO, &buf, 1);\n"
},
{
"code": null,
"e": 4006,
"s": 3913,
"text": "\n write(STDOUT_FILENO, \"\\n\", 1);\n close(pfd[0]);\n _exit(EXIT_SUCCESS);\n"
},
{
"code": null,
"e": 4324,
"s": 4006,
"text": "\n } else { /* Parent writes argv[1] to pipe */\n close(pfd[0]); /* Close unused read end */\n write(pfd[1], argv[1], strlen(argv[1]));\n close(pfd[1]); /* Reader will see EOF */\n wait(NULL); /* Wait for child */\n exit(EXIT_SUCCESS);\n }\n}\n"
},
{
"code": null,
"e": 4335,
"s": 4326,
"text": "fork (2)"
},
{
"code": null,
"e": 4344,
"s": 4335,
"text": "fork (2)"
},
{
"code": null,
"e": 4353,
"s": 4344,
"text": "read (2)"
},
{
"code": null,
"e": 4362,
"s": 4353,
"text": "read (2)"
},
{
"code": null,
"e": 4377,
"s": 4362,
"text": "socketpair (2)"
},
{
"code": null,
"e": 4392,
"s": 4377,
"text": "socketpair (2)"
},
{
"code": null,
"e": 4402,
"s": 4392,
"text": "write (2)"
},
{
"code": null,
"e": 4412,
"s": 4402,
"text": "write (2)"
},
{
"code": null,
"e": 4429,
"s": 4412,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 4464,
"s": 4429,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 4492,
"s": 4464,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4526,
"s": 4492,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4543,
"s": 4526,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4576,
"s": 4543,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4587,
"s": 4576,
"text": " Pradeep D"
},
{
"code": null,
"e": 4622,
"s": 4587,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4638,
"s": 4622,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 4671,
"s": 4638,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4683,
"s": 4671,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 4715,
"s": 4683,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4723,
"s": 4715,
"text": " Uplatz"
},
{
"code": null,
"e": 4730,
"s": 4723,
"text": " Print"
},
{
"code": null,
"e": 4741,
"s": 4730,
"text": " Add Notes"
}
] |
Python - tensorflow.math.reduce_variance() - GeeksforGeeks
|
31 Aug, 2021
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks.
reduce_variance() is used to find variance of elements across dimensions of a tensor.
Syntax: tensorflow.math.reduce_variance( input_tensor, axis, keepdims, name)
Parameters:
input_tensor: It is numeric tensor to reduce.
axis(optional): It represent the dimensions to reduce. Itβs value should be in range [-rank(input_tensor), rank(input_tensor)). If no value is given for this all dimensions are reduced.
keepdims(optional): Itβs default value is False. If itβs set to True it will retain the reduced dimension with length 1.
name(optional): It defines the name for the operation.
Returns: It returns a tensor.
Example 1:
Python3
# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([1, 2, 3, 4], dtype = tf.float64) # Printing the input tensorprint('Input: ', a) # Calculating resultres = tf.math.reduce_variance(a) # Printing the resultprint('Result: ', res)
Output:
Input: tf.Tensor([1. 2. 3. 4.], shape=(4, ), dtype=float64)
Result: tf.Tensor(1.25, shape=(), dtype=float64)
Example 2:
Python3
# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([[1, 2], [3, 4]], dtype = tf.float64) # Printing the input tensorprint('Input: ', a) # Calculating resultres = tf.math.reduce_variance(a, axis = 1, keepdims = True) # Printing the resultprint('Result: ', res)
Output:
Input: tf.Tensor(
[[1. 2.]
[3. 4.]], shape=(2, 2), dtype=float64)
Result: tf.Tensor(
[[0.25]
[0.25]], shape=(2, 1), dtype=float64)
sooda367
Python Tensorflow-math-functions
Python-Tensorflow
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 24032,
"s": 23901,
"text": "TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks."
},
{
"code": null,
"e": 24118,
"s": 24032,
"text": "reduce_variance() is used to find variance of elements across dimensions of a tensor."
},
{
"code": null,
"e": 24195,
"s": 24118,
"text": "Syntax: tensorflow.math.reduce_variance( input_tensor, axis, keepdims, name)"
},
{
"code": null,
"e": 24207,
"s": 24195,
"text": "Parameters:"
},
{
"code": null,
"e": 24253,
"s": 24207,
"text": "input_tensor: It is numeric tensor to reduce."
},
{
"code": null,
"e": 24440,
"s": 24253,
"text": "axis(optional): It represent the dimensions to reduce. Itβs value should be in range [-rank(input_tensor), rank(input_tensor)). If no value is given for this all dimensions are reduced."
},
{
"code": null,
"e": 24561,
"s": 24440,
"text": "keepdims(optional): Itβs default value is False. If itβs set to True it will retain the reduced dimension with length 1."
},
{
"code": null,
"e": 24616,
"s": 24561,
"text": "name(optional): It defines the name for the operation."
},
{
"code": null,
"e": 24646,
"s": 24616,
"text": "Returns: It returns a tensor."
},
{
"code": null,
"e": 24657,
"s": 24646,
"text": "Example 1:"
},
{
"code": null,
"e": 24665,
"s": 24657,
"text": "Python3"
},
{
"code": "# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([1, 2, 3, 4], dtype = tf.float64) # Printing the input tensorprint('Input: ', a) # Calculating resultres = tf.math.reduce_variance(a) # Printing the resultprint('Result: ', res)",
"e": 24937,
"s": 24665,
"text": null
},
{
"code": null,
"e": 24945,
"s": 24937,
"text": "Output:"
},
{
"code": null,
"e": 25056,
"s": 24945,
"text": "Input: tf.Tensor([1. 2. 3. 4.], shape=(4, ), dtype=float64)\nResult: tf.Tensor(1.25, shape=(), dtype=float64)"
},
{
"code": null,
"e": 25067,
"s": 25056,
"text": "Example 2:"
},
{
"code": null,
"e": 25075,
"s": 25067,
"text": "Python3"
},
{
"code": "# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([[1, 2], [3, 4]], dtype = tf.float64) # Printing the input tensorprint('Input: ', a) # Calculating resultres = tf.math.reduce_variance(a, axis = 1, keepdims = True) # Printing the resultprint('Result: ', res)",
"e": 25378,
"s": 25075,
"text": null
},
{
"code": null,
"e": 25386,
"s": 25378,
"text": "Output:"
},
{
"code": null,
"e": 25521,
"s": 25386,
"text": "Input: tf.Tensor(\n[[1. 2.]\n [3. 4.]], shape=(2, 2), dtype=float64)\nResult: tf.Tensor(\n[[0.25]\n [0.25]], shape=(2, 1), dtype=float64)"
},
{
"code": null,
"e": 25530,
"s": 25521,
"text": "sooda367"
},
{
"code": null,
"e": 25563,
"s": 25530,
"text": "Python Tensorflow-math-functions"
},
{
"code": null,
"e": 25581,
"s": 25563,
"text": "Python-Tensorflow"
},
{
"code": null,
"e": 25588,
"s": 25581,
"text": "Python"
},
{
"code": null,
"e": 25686,
"s": 25588,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25695,
"s": 25686,
"text": "Comments"
},
{
"code": null,
"e": 25708,
"s": 25695,
"text": "Old Comments"
},
{
"code": null,
"e": 25740,
"s": 25708,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25796,
"s": 25740,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25838,
"s": 25796,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25880,
"s": 25838,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25916,
"s": 25880,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 25938,
"s": 25916,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25977,
"s": 25938,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26004,
"s": 25977,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26035,
"s": 26004,
"text": "Python | os.path.join() method"
}
] |
Donβt Miss Out on Rolling Window Functions in Pandas | by Byron Dolon | Towards Data Science
|
Window calculations can add a lot of depth to your data analysis.
The Pandas library lets you perform many different built-in aggregate calculations, define your functions and apply them across a DataFrame, and even work with multiple columns in a DataFrame simultaneously. A feature in Pandas you might not have heard of before is the built-in Window functions.
Window functions are useful because you can perform many different kinds of operations on subsets of your data. Rolling window functions specifically let you calculate new values over each row in a DataFrame. This might sound a bit abstract, so letβs just dive into the explanations and examples.
Examples in this piece will use some old Tesla stock price data from Yahoo Finance. Feel free to run the code below if you want to follow along. For more information on pd.read_html and df.sort_values, check out the links at the end of this piece.
import pandas as pddf = pd.read_html("https://finance.yahoo.com/quote/TSLA/history?period1=1546300800&period2=1550275200&interval=1d&filter=history&frequency=1d")[0]df = df.head(11).sort_values(by='Date')df = df.astype({"Open":'float', "High":'float', "Low":'float', "Close*":'float', "Adj Close**":'float', "Volume":'float'})df['Gain'] = df['Close*'] - df['Open']
So what is a rolling window calculation?
Youβll typically use rolling calculations when you work with time-series data. Again, a window is a subset of rows that you perform a window calculation on. After youβve defined a window, you can perform operations like calculating running totals, moving averages, ranks, and much more!
Letβs clear this up with some examples.
The moving average calculation creates an updated average value for each row based on the window we specify. The calculation is also called a βrolling meanβ because itβs calculating an average of values within a specified range for each row as you go along the DataFrame.
That sounds a bit abstract, so letβs calculate the rolling mean for the βCloseβ column price over time. To do so, weβll run the following code:
df['Rolling Close Average'] = df['Close*'].rolling(2).mean()
Weβre creating a new column βRolling Close Averageβ which takes the moving average of the close price within a window. To do this, we simply write .rolling(2).mean(), where we specify a window of β2β and calculate the mean for every window along the DataFrame. Each row gets a βRolling Close Averageβ equal to its βClose*β value plus the previous rowβs βClose*β divided by 2 (the window). In essence, itβs Moving Avg = ([t] + [t-1]) / 2.
In practice, this means the first calculated value (62.44 + 62.58) / 2 = 62.51, which is the βRolling Close Averageβ value for February 4. There is no rolling mean for the first row in the DataFrame, because there is no available [t-1] or prior period βClose*β value to use in the calculation, which is why Pandas fills it with a NaN value.
To further see the difference between a regular calculation and a rolling calculation, letβs check out the rolling standard deviation of the βOpenβ price. To do so, weβll run the following code:
df['Open Standard Deviation'] = df['Open'].std()df['Rolling Open Standard Deviation'] = df['Open'].rolling(2).std()
I also included a new column βOpen Standard Deviationβ for the standard deviation that simply calculates the standard deviation for the whole βOpenβ column. Beside it, youβll see the βRolling Open Standard Deviationβ column, in which Iβve defined a window of 2 and calculated the standard deviation for each row.
Just as with the previous example, the first non-null value is at the second row of the DataFrame, because thatβs the first row that has both [t] and [t-1]. You can see how the moving standard deviation varies as you move down the table, which can be useful to track volatility over time.
Pandas uses N-1 degrees of freedom when calculating the standard deviation. You can pass an optional argument to ddof, which in the std function is set to β1β by default.
As a final example, letβs calculate the rolling sum for the βVolumeβ column. To do so, we run the following code:
df['Rolling Volume Sum'] = df['Volume'].rolling(3).sum()
Weβve defined a window of β3β, so the first calculated value appears on the third row. The sum calculation then βrollsβ over every row, so that you can track the sum of the current row and the two prior rowβs values over time.
Itβs important to emphasize here that these rolling (moving) calculations should not be confused with running calculations. Rolling calculations, as you can see int he diagram above, have a moving window. So with our moving sum, the calculated value for February 6 (the fourth row) does not include the value for February 1 (the first row), because the specified window (3) does not go that far back. In contrast, a running calculation would take continually add each row value to a running total value across the whole DataFrame. You can check out the cumsum function for that.
I hope you found this very basic introduction to logical comparisons in Pandas using the wrappers useful. Remember to only compare data that can be compared (i.e. donβt try to compare a string to a float) and manually double-check the results to make sure your calculations are producing the intended results.
Go forth and compare!
More by me:* 2 Easy Ways to Get Tables From a Website* 4 Different Ways to Efficiently Sort a Pandas DataFrame- Top 4 Repositories on GitHub to Learn Pandas- How to Quickly Create and Unpack Lists with Pandas- Learning to Forecast With Tableau in 5 Minutes Or Less
|
[
{
"code": null,
"e": 238,
"s": 172,
"text": "Window calculations can add a lot of depth to your data analysis."
},
{
"code": null,
"e": 535,
"s": 238,
"text": "The Pandas library lets you perform many different built-in aggregate calculations, define your functions and apply them across a DataFrame, and even work with multiple columns in a DataFrame simultaneously. A feature in Pandas you might not have heard of before is the built-in Window functions."
},
{
"code": null,
"e": 832,
"s": 535,
"text": "Window functions are useful because you can perform many different kinds of operations on subsets of your data. Rolling window functions specifically let you calculate new values over each row in a DataFrame. This might sound a bit abstract, so letβs just dive into the explanations and examples."
},
{
"code": null,
"e": 1080,
"s": 832,
"text": "Examples in this piece will use some old Tesla stock price data from Yahoo Finance. Feel free to run the code below if you want to follow along. For more information on pd.read_html and df.sort_values, check out the links at the end of this piece."
},
{
"code": null,
"e": 1520,
"s": 1080,
"text": "import pandas as pddf = pd.read_html(\"https://finance.yahoo.com/quote/TSLA/history?period1=1546300800&period2=1550275200&interval=1d&filter=history&frequency=1d\")[0]df = df.head(11).sort_values(by='Date')df = df.astype({\"Open\":'float', \"High\":'float', \"Low\":'float', \"Close*\":'float', \"Adj Close**\":'float', \"Volume\":'float'})df['Gain'] = df['Close*'] - df['Open']"
},
{
"code": null,
"e": 1561,
"s": 1520,
"text": "So what is a rolling window calculation?"
},
{
"code": null,
"e": 1848,
"s": 1561,
"text": "Youβll typically use rolling calculations when you work with time-series data. Again, a window is a subset of rows that you perform a window calculation on. After youβve defined a window, you can perform operations like calculating running totals, moving averages, ranks, and much more!"
},
{
"code": null,
"e": 1888,
"s": 1848,
"text": "Letβs clear this up with some examples."
},
{
"code": null,
"e": 2160,
"s": 1888,
"text": "The moving average calculation creates an updated average value for each row based on the window we specify. The calculation is also called a βrolling meanβ because itβs calculating an average of values within a specified range for each row as you go along the DataFrame."
},
{
"code": null,
"e": 2304,
"s": 2160,
"text": "That sounds a bit abstract, so letβs calculate the rolling mean for the βCloseβ column price over time. To do so, weβll run the following code:"
},
{
"code": null,
"e": 2365,
"s": 2304,
"text": "df['Rolling Close Average'] = df['Close*'].rolling(2).mean()"
},
{
"code": null,
"e": 2803,
"s": 2365,
"text": "Weβre creating a new column βRolling Close Averageβ which takes the moving average of the close price within a window. To do this, we simply write .rolling(2).mean(), where we specify a window of β2β and calculate the mean for every window along the DataFrame. Each row gets a βRolling Close Averageβ equal to its βClose*β value plus the previous rowβs βClose*β divided by 2 (the window). In essence, itβs Moving Avg = ([t] + [t-1]) / 2."
},
{
"code": null,
"e": 3144,
"s": 2803,
"text": "In practice, this means the first calculated value (62.44 + 62.58) / 2 = 62.51, which is the βRolling Close Averageβ value for February 4. There is no rolling mean for the first row in the DataFrame, because there is no available [t-1] or prior period βClose*β value to use in the calculation, which is why Pandas fills it with a NaN value."
},
{
"code": null,
"e": 3339,
"s": 3144,
"text": "To further see the difference between a regular calculation and a rolling calculation, letβs check out the rolling standard deviation of the βOpenβ price. To do so, weβll run the following code:"
},
{
"code": null,
"e": 3455,
"s": 3339,
"text": "df['Open Standard Deviation'] = df['Open'].std()df['Rolling Open Standard Deviation'] = df['Open'].rolling(2).std()"
},
{
"code": null,
"e": 3768,
"s": 3455,
"text": "I also included a new column βOpen Standard Deviationβ for the standard deviation that simply calculates the standard deviation for the whole βOpenβ column. Beside it, youβll see the βRolling Open Standard Deviationβ column, in which Iβve defined a window of 2 and calculated the standard deviation for each row."
},
{
"code": null,
"e": 4057,
"s": 3768,
"text": "Just as with the previous example, the first non-null value is at the second row of the DataFrame, because thatβs the first row that has both [t] and [t-1]. You can see how the moving standard deviation varies as you move down the table, which can be useful to track volatility over time."
},
{
"code": null,
"e": 4228,
"s": 4057,
"text": "Pandas uses N-1 degrees of freedom when calculating the standard deviation. You can pass an optional argument to ddof, which in the std function is set to β1β by default."
},
{
"code": null,
"e": 4342,
"s": 4228,
"text": "As a final example, letβs calculate the rolling sum for the βVolumeβ column. To do so, we run the following code:"
},
{
"code": null,
"e": 4399,
"s": 4342,
"text": "df['Rolling Volume Sum'] = df['Volume'].rolling(3).sum()"
},
{
"code": null,
"e": 4626,
"s": 4399,
"text": "Weβve defined a window of β3β, so the first calculated value appears on the third row. The sum calculation then βrollsβ over every row, so that you can track the sum of the current row and the two prior rowβs values over time."
},
{
"code": null,
"e": 5205,
"s": 4626,
"text": "Itβs important to emphasize here that these rolling (moving) calculations should not be confused with running calculations. Rolling calculations, as you can see int he diagram above, have a moving window. So with our moving sum, the calculated value for February 6 (the fourth row) does not include the value for February 1 (the first row), because the specified window (3) does not go that far back. In contrast, a running calculation would take continually add each row value to a running total value across the whole DataFrame. You can check out the cumsum function for that."
},
{
"code": null,
"e": 5515,
"s": 5205,
"text": "I hope you found this very basic introduction to logical comparisons in Pandas using the wrappers useful. Remember to only compare data that can be compared (i.e. donβt try to compare a string to a float) and manually double-check the results to make sure your calculations are producing the intended results."
},
{
"code": null,
"e": 5537,
"s": 5515,
"text": "Go forth and compare!"
}
] |
How to disable GridView scrolling in Android using Kotlin?
|
This example demonstrates how to disable GridView scrolling in Android using Kotlin.
Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project.
Step 2 β Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
tools:context=".MainActivity">
<GridView
android:id="@+id/gridLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Step 3 β Add the following code to src/MainActivity.kt
import android.content.Context
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private lateinit var gridView: GridView
var imageIDs = arrayOf(
R.drawable.ronaldo,
R.drawable.andre,
R.drawable.bernado,
R.drawable.carvalho,
R.drawable.bruno,
R.drawable.patricio,
R.drawable.pepe,
R.drawable.felix,
R.drawable.semedo,
R.drawable.ronaldo
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
gridView = findViewById(R.id.gridLayout)
gridView.numColumns = 3
gridView.adapter = ImageAdapterGridView(this)
gridView.setOnTouchListener { _, event ->
Toast.makeText(this@MainActivity, "Scrolling is Disabled", Toast.LENGTH_SHORT).show()
event.action === MotionEvent.ACTION_MOVE
}
}
inner class ImageAdapterGridView internal constructor(c: Context) : BaseAdapter() {
private val context: Context = c
override fun getCount(): Int {
return imageIDs.size
}
override fun getItem(position: Int): Any? {
return null
}
override fun getItemId(position: Int): Long {
return 0
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val imageView: ImageView
if (convertView == null) {
imageView = ImageView(context)
imageView.layoutParams = AbsListView.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
imageView.scaleType = ImageView.ScaleType.CENTER_CROP
imageView.setPadding(30, 30, 30, 30)
}
else {
imageView = convertView as ImageView
}
imageView.setImageResource(imageIDs[position])
return imageView
}
}
}
Step 4 β Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
Click here to download the project code.
|
[
{
"code": null,
"e": 1147,
"s": 1062,
"text": "This example demonstrates how to disable GridView scrolling in Android using Kotlin."
},
{
"code": null,
"e": 1276,
"s": 1147,
"text": "Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1341,
"s": 1276,
"text": "Step 2 β Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1798,
"s": 1341,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"8dp\"\n tools:context=\".MainActivity\">\n <GridView\n android:id=\"@+id/gridLayout\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n</RelativeLayout>\n"
},
{
"code": null,
"e": 1853,
"s": 1798,
"text": "Step 3 β Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 4040,
"s": 1853,
"text": "import android.content.Context\nimport android.os.Bundle\nimport android.view.MotionEvent\nimport android.view.View\nimport android.view.ViewGroup\nimport android.widget.*\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n private lateinit var gridView: GridView\n var imageIDs = arrayOf(\n R.drawable.ronaldo,\n R.drawable.andre,\n R.drawable.bernado,\n R.drawable.carvalho,\n R.drawable.bruno,\n R.drawable.patricio,\n R.drawable.pepe,\n R.drawable.felix,\n R.drawable.semedo,\n R.drawable.ronaldo\n )\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n gridView = findViewById(R.id.gridLayout)\n gridView.numColumns = 3\n gridView.adapter = ImageAdapterGridView(this)\n gridView.setOnTouchListener { _, event ->\n Toast.makeText(this@MainActivity, \"Scrolling is Disabled\", Toast.LENGTH_SHORT).show()\n event.action === MotionEvent.ACTION_MOVE\n }\n }\n inner class ImageAdapterGridView internal constructor(c: Context) : BaseAdapter() {\n private val context: Context = c\n override fun getCount(): Int {\n return imageIDs.size\n }\n override fun getItem(position: Int): Any? {\n return null\n }\n override fun getItemId(position: Int): Long {\n return 0\n }\n override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {\n val imageView: ImageView\n if (convertView == null) {\n imageView = ImageView(context)\n imageView.layoutParams = AbsListView.LayoutParams(\n ViewGroup.LayoutParams.WRAP_CONTENT,\n ViewGroup.LayoutParams.WRAP_CONTENT\n )\n imageView.scaleType = ImageView.ScaleType.CENTER_CROP\n imageView.setPadding(30, 30, 30, 30)\n }\n else {\n imageView = convertView as ImageView\n }\n imageView.setImageResource(imageIDs[position])\n return imageView\n }\n }\n}"
},
{
"code": null,
"e": 4095,
"s": 4040,
"text": "Step 4 β Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4769,
"s": 4095,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5118,
"s": 4769,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen."
},
{
"code": null,
"e": 5159,
"s": 5118,
"text": "Click here to download the project code."
}
] |
Spring Boot - Google OAuth2 Sign-In
|
In this chapter, we are going to see how to add the Google OAuth2 Sign-In by using Spring Boot application with Gradle build.
First, add the Spring Boot OAuth2 security dependency in your build configuration file and your build configuration file is given below.
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.tutorialspoint.projects'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter')
testCompile('org.springframework.boot:spring-boot-starter-test')
compile('org.springframework.security.oauth:spring-security-oauth2')
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Now, add the HTTP Endpoint to read the User Principal from the Google after authenticating via Spring Boot in main Spring Boot application class file as given below β
package com.tutorialspoint.projects.googleservice;
import java.security.Principal;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class GoogleserviceApplication {
public static void main(String[] args) {
SpringApplication.run(GoogleserviceApplication.class, args);
}
@RequestMapping(value = "/user")
public Principal user(Principal principal) {
return principal;
}
}
Now, write a Configuration file to enable the OAuth2SSO for web security and remove the authentication for index.html file as shown β
package com.tutorialspoint.projects.googleservice;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableOAuth2Sso
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.antMatcher("/**")
.authorizeRequests()
.antMatchers("/", "/index.html")
.permitAll()
.anyRequest()
.authenticated();
}
}
Next, add the index.html file under static resources and add the link to redirect into user HTTP Endpoint to read the Google user Principal as shown below β
<!DOCTYPE html>
<html>
<head>
<meta charset = "ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href = "user">Click here to Google Login</a>
</body>
</html>
Note β In Google Cloud console - Enable the Gmail Services, Analytics Services and Google+ service API(s).
Then, go the Credentials section and create a credentials and choose OAuth Client ID.
Next, provide a Product Name in OAuth2 consent screen.
Next, choose the Application Type as βWeb applicationβ, provide the Authorized JavaScript origins and Authorized redirect URIs.
Now, your OAuth2 Client Id and Client Secret is created.
Next, add the Client Id and Client Secret in your application properties file.
security.oauth2.client.clientId = <CLIENT_ID>
security.oauth2.client.clientSecret = <CLIENT_SECRET>
security.oauth2.client.accessTokenUri = https://www.googleapis.com/oauth2/v3/token
security.oauth2.client.userAuthorizationUri = https://accounts.google.com/o/oauth2/auth
security.oauth2.client.tokenName = oauth_token
security.oauth2.client.authenticationScheme = query
security.oauth2.client.clientAuthenticationScheme = form
security.oauth2.client.scope = profile email
security.oauth2.resource.userInfoUri = https://www.googleapis.com/userinfo/v2/me
security.oauth2.resource.preferTokenInfo = false
Now, you can create an executable JAR file, and run the Spring Boot application by using the following Gradle command.
For Gradle, you can use the command as shown β
gradle clean build
After βBUILD SUCCESSFULβ, you can find the JAR file under the build/libs directory.
Run the JAR file by using the command java βjar <JARFILE> and application is started on the Tomcat port 8080.
Now hit the URL http://localhost:8080/ and click the Google Login link.
It will redirect to the Google login screen and provide a Gmail login details.
If login success, we will receive the Principal object of the Gmail user.
102 Lectures
8 hours
Karthikeya T
39 Lectures
5 hours
Chaand Sheikh
73 Lectures
5.5 hours
Senol Atac
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
69 Lectures
5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3151,
"s": 3025,
"text": "In this chapter, we are going to see how to add the Google OAuth2 Sign-In by using Spring Boot application with Gradle build."
},
{
"code": null,
"e": 3288,
"s": 3151,
"text": "First, add the Spring Boot OAuth2 security dependency in your build configuration file and your build configuration file is given below."
},
{
"code": null,
"e": 4082,
"s": 3288,
"text": "buildscript {\n ext {\n springBootVersion = '1.5.8.RELEASE'\n }\n repositories {\n mavenCentral()\n }\n dependencies {\n classpath(\"org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}\")\n }\n}\n\napply plugin: 'java'\napply plugin: 'eclipse'\napply plugin: 'org.springframework.boot'\n\ngroup = 'com.tutorialspoint.projects'\nversion = '0.0.1-SNAPSHOT'\nsourceCompatibility = 1.8\n\nrepositories {\n mavenCentral()\n}\ndependencies {\n compile('org.springframework.boot:spring-boot-starter')\n testCompile('org.springframework.boot:spring-boot-starter-test')\n compile('org.springframework.security.oauth:spring-security-oauth2')\n compile('org.springframework.boot:spring-boot-starter-web')\n testCompile('org.springframework.boot:spring-boot-starter-test')\n} "
},
{
"code": null,
"e": 4249,
"s": 4082,
"text": "Now, add the HTTP Endpoint to read the User Principal from the Google after authenticating via Spring Boot in main Spring Boot application class file as given below β"
},
{
"code": null,
"e": 4891,
"s": 4249,
"text": "package com.tutorialspoint.projects.googleservice;\n\nimport java.security.Principal;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@SpringBootApplication\n@RestController\npublic class GoogleserviceApplication {\n public static void main(String[] args) {\n SpringApplication.run(GoogleserviceApplication.class, args);\n }\n @RequestMapping(value = \"/user\")\n public Principal user(Principal principal) {\n return principal;\n }\n}"
},
{
"code": null,
"e": 5025,
"s": 4891,
"text": "Now, write a Configuration file to enable the OAuth2SSO for web security and remove the authentication for index.html file as shown β"
},
{
"code": null,
"e": 5823,
"s": 5025,
"text": "package com.tutorialspoint.projects.googleservice;\n\nimport org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;\n\n@Configuration\n@EnableOAuth2Sso\npublic class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {\n @Override\n protected void configure(HttpSecurity http) throws Exception {\n http\n .csrf()\n .disable()\n .antMatcher(\"/**\")\n .authorizeRequests()\n .antMatchers(\"/\", \"/index.html\")\n .permitAll()\n .anyRequest()\n .authenticated();\n }\n}"
},
{
"code": null,
"e": 5980,
"s": 5823,
"text": "Next, add the index.html file under static resources and add the link to redirect into user HTTP Endpoint to read the Google user Principal as shown below β"
},
{
"code": null,
"e": 6183,
"s": 5980,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"ISO-8859-1\">\n <title>Insert title here</title>\n </head>\n <body>\n <a href = \"user\">Click here to Google Login</a>\n </body>\n</html> "
},
{
"code": null,
"e": 6290,
"s": 6183,
"text": "Note β In Google Cloud console - Enable the Gmail Services, Analytics Services and Google+ service API(s)."
},
{
"code": null,
"e": 6376,
"s": 6290,
"text": "Then, go the Credentials section and create a credentials and choose OAuth Client ID."
},
{
"code": null,
"e": 6431,
"s": 6376,
"text": "Next, provide a Product Name in OAuth2 consent screen."
},
{
"code": null,
"e": 6559,
"s": 6431,
"text": "Next, choose the Application Type as βWeb applicationβ, provide the Authorized JavaScript origins and Authorized redirect URIs."
},
{
"code": null,
"e": 6616,
"s": 6559,
"text": "Now, your OAuth2 Client Id and Client Secret is created."
},
{
"code": null,
"e": 6695,
"s": 6616,
"text": "Next, add the Client Id and Client Secret in your application properties file."
},
{
"code": null,
"e": 7304,
"s": 6695,
"text": "security.oauth2.client.clientId = <CLIENT_ID>\nsecurity.oauth2.client.clientSecret = <CLIENT_SECRET>\nsecurity.oauth2.client.accessTokenUri = https://www.googleapis.com/oauth2/v3/token\nsecurity.oauth2.client.userAuthorizationUri = https://accounts.google.com/o/oauth2/auth\nsecurity.oauth2.client.tokenName = oauth_token\nsecurity.oauth2.client.authenticationScheme = query\nsecurity.oauth2.client.clientAuthenticationScheme = form\nsecurity.oauth2.client.scope = profile email\n\nsecurity.oauth2.resource.userInfoUri = https://www.googleapis.com/userinfo/v2/me\nsecurity.oauth2.resource.preferTokenInfo = false"
},
{
"code": null,
"e": 7423,
"s": 7304,
"text": "Now, you can create an executable JAR file, and run the Spring Boot application by using the following Gradle command."
},
{
"code": null,
"e": 7470,
"s": 7423,
"text": "For Gradle, you can use the command as shown β"
},
{
"code": null,
"e": 7490,
"s": 7470,
"text": "gradle clean build\n"
},
{
"code": null,
"e": 7574,
"s": 7490,
"text": "After βBUILD SUCCESSFULβ, you can find the JAR file under the build/libs directory."
},
{
"code": null,
"e": 7684,
"s": 7574,
"text": "Run the JAR file by using the command java βjar <JARFILE> and application is started on the Tomcat port 8080."
},
{
"code": null,
"e": 7756,
"s": 7684,
"text": "Now hit the URL http://localhost:8080/ and click the Google Login link."
},
{
"code": null,
"e": 7835,
"s": 7756,
"text": "It will redirect to the Google login screen and provide a Gmail login details."
},
{
"code": null,
"e": 7909,
"s": 7835,
"text": "If login success, we will receive the Principal object of the Gmail user."
},
{
"code": null,
"e": 7943,
"s": 7909,
"text": "\n 102 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 7957,
"s": 7943,
"text": " Karthikeya T"
},
{
"code": null,
"e": 7990,
"s": 7957,
"text": "\n 39 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 8005,
"s": 7990,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 8040,
"s": 8005,
"text": "\n 73 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 8052,
"s": 8040,
"text": " Senol Atac"
},
{
"code": null,
"e": 8087,
"s": 8052,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8099,
"s": 8087,
"text": " Senol Atac"
},
{
"code": null,
"e": 8134,
"s": 8099,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8146,
"s": 8134,
"text": " Senol Atac"
},
{
"code": null,
"e": 8179,
"s": 8146,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 8191,
"s": 8179,
"text": " Senol Atac"
},
{
"code": null,
"e": 8198,
"s": 8191,
"text": " Print"
},
{
"code": null,
"e": 8209,
"s": 8198,
"text": " Add Notes"
}
] |
CSS Opacity / Transparency
|
For CSS Opacity/ Transparency, the opacity property is used. For example,
opacity: 0.3;
Following is the code showing Opacity/ Transparency using CSS β
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
div {
width: 200px;
height: 200px;
background-color: rgb(0, 0, 255);
color: white;
display: inline-block;
}
.transparent {
background-color: rgba(0, 0, 255, 0.582);
}
img{
width: 200px;
height: 200px;
}
.transparent-img{
opacity: 0.3;
}
</style>
</head>
<body>
<h1>Tansparency/Opacity Example</h1>
<div class="transparent">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Hic, accusantium.
</div>
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Eum, nisi!
</div>
<hr>
<img src="https://i.picsum.photos/id/487/300/300.jpg">
<img class="transparent-img" src="https://i.picsum.photos/id/487/300/300.jpg">
</body>
</html>
The above code will produce the following output β
|
[
{
"code": null,
"e": 1136,
"s": 1062,
"text": "For CSS Opacity/ Transparency, the opacity property is used. For example,"
},
{
"code": null,
"e": 1150,
"s": 1136,
"text": "opacity: 0.3;"
},
{
"code": null,
"e": 1214,
"s": 1150,
"text": "Following is the code showing Opacity/ Transparency using CSS β"
},
{
"code": null,
"e": 1225,
"s": 1214,
"text": " Live Demo"
},
{
"code": null,
"e": 2006,
"s": 1225,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nbody {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n}\ndiv {\n width: 200px;\n height: 200px;\n background-color: rgb(0, 0, 255);\n color: white;\n display: inline-block;\n}\n.transparent {\n background-color: rgba(0, 0, 255, 0.582);\n}\nimg{\n width: 200px;\n height: 200px;\n}\n.transparent-img{\n opacity: 0.3;\n}\n</style>\n</head>\n<body>\n<h1>Tansparency/Opacity Example</h1>\n<div class=\"transparent\">\nLorem ipsum dolor sit amet consectetur adipisicing elit. Hic, accusantium.\n</div>\n<div>\nLorem ipsum dolor sit amet consectetur adipisicing elit. Eum, nisi!\n</div>\n<hr>\n<img src=\"https://i.picsum.photos/id/487/300/300.jpg\">\n<img class=\"transparent-img\" src=\"https://i.picsum.photos/id/487/300/300.jpg\">\n</body>\n</html>"
},
{
"code": null,
"e": 2057,
"s": 2006,
"text": "The above code will produce the following output β"
}
] |
Seeing is Believing: Converting Audio Data into Images | by Tony Chen | Towards Data Science
|
Created together with Dmytro Karabash, Maxim Korotkov, and Hyeongchan Kim.
Close your eyes and listen to the sound around you. Whether you are in a crowded office, cozy home, or open space of nature, you can distinguish the environment with the sound around you. One of the five major senses of humans is hearing, so audio plays a significant role in our life. Therefore, organizing and exploiting values in audio data with deep learning is a crucial process for AI to understand our world. An important task in sound processing is enabling computers to distinguish one sound from another. This capability enables computers to do things ranging from detecting metal wearing in power plants to monitoring and optimizing carsβ fuel efficiency. In this post, we will use bird sound identification as an example. We will detect locations of bird calls in recordings produced in natural settings and classify species. By converting audio data to image data and applying computer vision models, we acquired a silver medal (top 2%) in Kaggle Cornell Birdcall Identification challenge.
When a doctor diagnoses heart problems, he can either directly listen to the patientβs heartbeat or look at the ECG - a diagram that describes the heartbeat - of the patient. The former usually takes longer β it takes time for the doctor to listen β and harder β memorizing what you heard can be hard. In contrast, visual perceptions of ECG allows a doctor to absorb spatial information instantly and accelerates the tasks.
The same rationales apply to our sound detection tasks. Here are spectrograms of four bird species. You can listen to the original audio clips here. Even human eyes can see the differences between species instantly based on color and shapes.
Going over the audio waves through time takes more computational resources, and we can acquire more information from the 2-dimensional data of images than 1-dimensional waves. In addition, the recent rapid development of computer visions, especially with the help of Convolutional Neural Network (CNNs), can significantly benefit our approach if treating audios as images as we (along with pretty much everyone) did in the competition.
The specific image representation that we use is called a spectrogram: a visual representation of the spectrum of frequencies of a signal as it varies with time.
Sounds can be represented in the form of waves, and waves have two important properties: frequency and amplitude as illustrated in the picture below. The frequency determines how the audio sounds like, and amplitude determines how loud the sound is.
In a spectrogram of an audio clip, the horizontal direction represents time, and the vertical direction represents different frequencies. Finally, the amplitude of sounds of a particular frequency exists at a particular point of time is represented by the pointβs color, resulting from the corresponding x-y coordinates.
To more intuitively see how frequencies are embodied in spectrograms, hereβs a 3D visualization, which demonstrates the amplitude with an extra dimension. Again, the x-axis is time, and y-axis is the value of frequencies. The z-axis is the amplitude of sounds of the frequency of y-coordinate at the moment of the x-coordinate. As the z-value increases, the color changes from blue to red, which results in the color we saw in the previous example of a 2D spectrogram.
Spectrograms are helpful because they extract exactly the information we need: frequencies, the features that shape the form of sound we hear. Different bird species, or actually all objects that produce sound, have their own unique frequency range so that their sounds appear to be different for our ears. Our model will simply need to master distinguishing between frequencies to achieve ideal classification results.
However, human ears do not perceive differences in all frequency ranges equally. As frequencies increase, it is more difficult for us to distinguish between different frequencies. In order to better emulate human ear behaviors with deep learning models, we measure frequencies in mel scale. In the mel scale, any equal distance between frequencies sound equally different for human ears. mel scale converts frequency from in Hertz (f) to in mel (m) with the following equation:
m = 2595 * log(1+f/700)
A mel scale spectrogram is simply a spectrogram with frequencies measured in mel.
To create a mel spectrogram from audio waves, we will employ librosa library.
import librosay, sr = librosa.load('img-tony/amered.wav', sr=32000, mono=True)melspec = librosa.feature.melspectrogram(y, sr=sr, n_mels = 128)melspec = librosa.power_to_db(melspec).astype(np.float32)
Where y denotes the raw wave data, sr denotes sample rate of the audio sample, and n_mels decides the number of mel bands in the generated spectrogram. When using melspectrogram method, you can also set f_min and f_max method You can also set Then, we can convert mel spectrogram that express amplitude in amplitude squared scale to decibel scale with the power_to_db method.
To visualize the generated spectrogram, run
import librosa.displaylibrosa.display.specshow(melspec, x_axis='time', y_axis='mel', sr=sr, fmax=16000)
Alternatively, if you are using GPU, you can accelerate the mel spectrogram generation process with torchlibrosa library.
from torchlibrosa.stft import Spectrogram, LogmelFilterBankspectrogram_extractor = Spectrogram()logmel_extractor = LogmelFilterBank()y = spectrogram_extractor(y)y = self.logmel_extractor(y)
In conclusion, we can take advantages from recent developments in computer vision in audio-related tasks by converting audio clips into image data. We achieve so with spectrograms that exhibit frequency, amplitude, and time information of audio data in an image. Using mel scale and mel scale spectrogram helps computers to emulate human hearing behaviors to distinguish sounds of different frequencies. To generate spectrograms, we could employ librosa library, or torchlibrosa for GPU acceleration, in Python. By treating audio-related tasks in such a way, we are able to establish efficient deep learning models to identify and classify sounds, like how doctors diagnose heart-related diseases with ECG.
Originally published at YourDataBlog.
|
[
{
"code": null,
"e": 247,
"s": 172,
"text": "Created together with Dmytro Karabash, Maxim Korotkov, and Hyeongchan Kim."
},
{
"code": null,
"e": 1250,
"s": 247,
"text": "Close your eyes and listen to the sound around you. Whether you are in a crowded office, cozy home, or open space of nature, you can distinguish the environment with the sound around you. One of the five major senses of humans is hearing, so audio plays a significant role in our life. Therefore, organizing and exploiting values in audio data with deep learning is a crucial process for AI to understand our world. An important task in sound processing is enabling computers to distinguish one sound from another. This capability enables computers to do things ranging from detecting metal wearing in power plants to monitoring and optimizing carsβ fuel efficiency. In this post, we will use bird sound identification as an example. We will detect locations of bird calls in recordings produced in natural settings and classify species. By converting audio data to image data and applying computer vision models, we acquired a silver medal (top 2%) in Kaggle Cornell Birdcall Identification challenge."
},
{
"code": null,
"e": 1674,
"s": 1250,
"text": "When a doctor diagnoses heart problems, he can either directly listen to the patientβs heartbeat or look at the ECG - a diagram that describes the heartbeat - of the patient. The former usually takes longer β it takes time for the doctor to listen β and harder β memorizing what you heard can be hard. In contrast, visual perceptions of ECG allows a doctor to absorb spatial information instantly and accelerates the tasks."
},
{
"code": null,
"e": 1916,
"s": 1674,
"text": "The same rationales apply to our sound detection tasks. Here are spectrograms of four bird species. You can listen to the original audio clips here. Even human eyes can see the differences between species instantly based on color and shapes."
},
{
"code": null,
"e": 2352,
"s": 1916,
"text": "Going over the audio waves through time takes more computational resources, and we can acquire more information from the 2-dimensional data of images than 1-dimensional waves. In addition, the recent rapid development of computer visions, especially with the help of Convolutional Neural Network (CNNs), can significantly benefit our approach if treating audios as images as we (along with pretty much everyone) did in the competition."
},
{
"code": null,
"e": 2514,
"s": 2352,
"text": "The specific image representation that we use is called a spectrogram: a visual representation of the spectrum of frequencies of a signal as it varies with time."
},
{
"code": null,
"e": 2764,
"s": 2514,
"text": "Sounds can be represented in the form of waves, and waves have two important properties: frequency and amplitude as illustrated in the picture below. The frequency determines how the audio sounds like, and amplitude determines how loud the sound is."
},
{
"code": null,
"e": 3085,
"s": 2764,
"text": "In a spectrogram of an audio clip, the horizontal direction represents time, and the vertical direction represents different frequencies. Finally, the amplitude of sounds of a particular frequency exists at a particular point of time is represented by the pointβs color, resulting from the corresponding x-y coordinates."
},
{
"code": null,
"e": 3554,
"s": 3085,
"text": "To more intuitively see how frequencies are embodied in spectrograms, hereβs a 3D visualization, which demonstrates the amplitude with an extra dimension. Again, the x-axis is time, and y-axis is the value of frequencies. The z-axis is the amplitude of sounds of the frequency of y-coordinate at the moment of the x-coordinate. As the z-value increases, the color changes from blue to red, which results in the color we saw in the previous example of a 2D spectrogram."
},
{
"code": null,
"e": 3974,
"s": 3554,
"text": "Spectrograms are helpful because they extract exactly the information we need: frequencies, the features that shape the form of sound we hear. Different bird species, or actually all objects that produce sound, have their own unique frequency range so that their sounds appear to be different for our ears. Our model will simply need to master distinguishing between frequencies to achieve ideal classification results."
},
{
"code": null,
"e": 4452,
"s": 3974,
"text": "However, human ears do not perceive differences in all frequency ranges equally. As frequencies increase, it is more difficult for us to distinguish between different frequencies. In order to better emulate human ear behaviors with deep learning models, we measure frequencies in mel scale. In the mel scale, any equal distance between frequencies sound equally different for human ears. mel scale converts frequency from in Hertz (f) to in mel (m) with the following equation:"
},
{
"code": null,
"e": 4476,
"s": 4452,
"text": "m = 2595 * log(1+f/700)"
},
{
"code": null,
"e": 4558,
"s": 4476,
"text": "A mel scale spectrogram is simply a spectrogram with frequencies measured in mel."
},
{
"code": null,
"e": 4636,
"s": 4558,
"text": "To create a mel spectrogram from audio waves, we will employ librosa library."
},
{
"code": null,
"e": 4836,
"s": 4636,
"text": "import librosay, sr = librosa.load('img-tony/amered.wav', sr=32000, mono=True)melspec = librosa.feature.melspectrogram(y, sr=sr, n_mels = 128)melspec = librosa.power_to_db(melspec).astype(np.float32)"
},
{
"code": null,
"e": 5212,
"s": 4836,
"text": "Where y denotes the raw wave data, sr denotes sample rate of the audio sample, and n_mels decides the number of mel bands in the generated spectrogram. When using melspectrogram method, you can also set f_min and f_max method You can also set Then, we can convert mel spectrogram that express amplitude in amplitude squared scale to decibel scale with the power_to_db method."
},
{
"code": null,
"e": 5256,
"s": 5212,
"text": "To visualize the generated spectrogram, run"
},
{
"code": null,
"e": 5361,
"s": 5256,
"text": "import librosa.displaylibrosa.display.specshow(melspec, x_axis='time', y_axis='mel', sr=sr, fmax=16000)"
},
{
"code": null,
"e": 5483,
"s": 5361,
"text": "Alternatively, if you are using GPU, you can accelerate the mel spectrogram generation process with torchlibrosa library."
},
{
"code": null,
"e": 5673,
"s": 5483,
"text": "from torchlibrosa.stft import Spectrogram, LogmelFilterBankspectrogram_extractor = Spectrogram()logmel_extractor = LogmelFilterBank()y = spectrogram_extractor(y)y = self.logmel_extractor(y)"
},
{
"code": null,
"e": 6380,
"s": 5673,
"text": "In conclusion, we can take advantages from recent developments in computer vision in audio-related tasks by converting audio clips into image data. We achieve so with spectrograms that exhibit frequency, amplitude, and time information of audio data in an image. Using mel scale and mel scale spectrogram helps computers to emulate human hearing behaviors to distinguish sounds of different frequencies. To generate spectrograms, we could employ librosa library, or torchlibrosa for GPU acceleration, in Python. By treating audio-related tasks in such a way, we are able to establish efficient deep learning models to identify and classify sounds, like how doctors diagnose heart-related diseases with ECG."
}
] |
Build a Voice Recorder GUI using Python - GeeksforGeeks
|
01 Oct, 2020
Prerequisites: Python GUI β tkinter, Create a Voice Recorder using Python
Python provides various tools and can be used for various purposes. One such purpose is recording voice. It can be done using the sounddevice module. This recorded file can be saved using the soundfile module
Sounddevice: The sounddevice module provides bindings for the PortAudio library and a few convenience functions to play and record NumPy arrays containing audio signals. To install this type the below command in the terminal.
pip install sounddevice
SoundFile: SoundFile can read and write sound files. To install this type the below command in the terminal.
pip install SoundFile
Approach:
Import the required module.
Set frequency and duration.
Record voice data in NumPy array, you can use rec().
Store into the file using soundfile.write().
Implementation:
Step 1: Import modules
import sounddevice as sd
import soundfile as sf
Step 2: Set frequency and duration and record voice data in NumPy array, you can use rec()
fs = 48000
duration = 5
myrecording = sd.rec(int(duration * fs), samplerate=fs,
channels=2)
Note: fs is the sample rate of the recording (usually 44100 or 44800 Hz)
Step 3: Now store these array into audio files.
# Save as FLAC file at correct sampling rate
sf.write('My_Audio_file.flac', myrecording, fs)
Letβs create a GUI application for the same. Weβll be using Tkinter for doing the same.
Python3
import sounddevice as sdimport soundfile as sffrom tkinter import * def Voice_rec(): fs = 48000 # seconds duration = 5 myrecording = sd.rec(int(duration * fs), samplerate=fs, channels=2) sd.wait() # Save as FLAC file at correct sampling rate return sf.write('my_Audio_file.flac', myrecording, fs) master = Tk() Label(master, text=" Voice Recoder : " ).grid(row=0, sticky=W, rowspan=5) b = Button(master, text="Start", command=Voice_rec)b.grid(row=0, column=2, columnspan=2, rowspan=2, padx=5, pady=5) mainloop()
Output:
Python-projects
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
|
[
{
"code": null,
"e": 24307,
"s": 24279,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 24381,
"s": 24307,
"text": "Prerequisites: Python GUI β tkinter, Create a Voice Recorder using Python"
},
{
"code": null,
"e": 24590,
"s": 24381,
"text": "Python provides various tools and can be used for various purposes. One such purpose is recording voice. It can be done using the sounddevice module. This recorded file can be saved using the soundfile module"
},
{
"code": null,
"e": 24816,
"s": 24590,
"text": "Sounddevice: The sounddevice module provides bindings for the PortAudio library and a few convenience functions to play and record NumPy arrays containing audio signals. To install this type the below command in the terminal."
},
{
"code": null,
"e": 24841,
"s": 24816,
"text": "pip install sounddevice\n"
},
{
"code": null,
"e": 24951,
"s": 24841,
"text": "SoundFile: SoundFile can read and write sound files. To install this type the below command in the terminal."
},
{
"code": null,
"e": 24974,
"s": 24951,
"text": "pip install SoundFile\n"
},
{
"code": null,
"e": 24984,
"s": 24974,
"text": "Approach:"
},
{
"code": null,
"e": 25012,
"s": 24984,
"text": "Import the required module."
},
{
"code": null,
"e": 25040,
"s": 25012,
"text": "Set frequency and duration."
},
{
"code": null,
"e": 25093,
"s": 25040,
"text": "Record voice data in NumPy array, you can use rec()."
},
{
"code": null,
"e": 25138,
"s": 25093,
"text": "Store into the file using soundfile.write()."
},
{
"code": null,
"e": 25154,
"s": 25138,
"text": "Implementation:"
},
{
"code": null,
"e": 25177,
"s": 25154,
"text": "Step 1: Import modules"
},
{
"code": null,
"e": 25225,
"s": 25177,
"text": "import sounddevice as sd\nimport soundfile as sf"
},
{
"code": null,
"e": 25316,
"s": 25225,
"text": "Step 2: Set frequency and duration and record voice data in NumPy array, you can use rec()"
},
{
"code": null,
"e": 25430,
"s": 25316,
"text": "fs = 48000\nduration = 5 \nmyrecording = sd.rec(int(duration * fs), samplerate=fs,\n channels=2)"
},
{
"code": null,
"e": 25503,
"s": 25430,
"text": "Note: fs is the sample rate of the recording (usually 44100 or 44800 Hz)"
},
{
"code": null,
"e": 25551,
"s": 25503,
"text": "Step 3: Now store these array into audio files."
},
{
"code": null,
"e": 25644,
"s": 25551,
"text": "# Save as FLAC file at correct sampling rate\nsf.write('My_Audio_file.flac', myrecording, fs)"
},
{
"code": null,
"e": 25732,
"s": 25644,
"text": "Letβs create a GUI application for the same. Weβll be using Tkinter for doing the same."
},
{
"code": null,
"e": 25740,
"s": 25732,
"text": "Python3"
},
{
"code": "import sounddevice as sdimport soundfile as sffrom tkinter import * def Voice_rec(): fs = 48000 # seconds duration = 5 myrecording = sd.rec(int(duration * fs), samplerate=fs, channels=2) sd.wait() # Save as FLAC file at correct sampling rate return sf.write('my_Audio_file.flac', myrecording, fs) master = Tk() Label(master, text=\" Voice Recoder : \" ).grid(row=0, sticky=W, rowspan=5) b = Button(master, text=\"Start\", command=Voice_rec)b.grid(row=0, column=2, columnspan=2, rowspan=2, padx=5, pady=5) mainloop()",
"e": 26331,
"s": 25740,
"text": null
},
{
"code": null,
"e": 26339,
"s": 26331,
"text": "Output:"
},
{
"code": null,
"e": 26355,
"s": 26339,
"text": "Python-projects"
},
{
"code": null,
"e": 26370,
"s": 26355,
"text": "python-utility"
},
{
"code": null,
"e": 26377,
"s": 26370,
"text": "Python"
},
{
"code": null,
"e": 26475,
"s": 26377,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26484,
"s": 26475,
"text": "Comments"
},
{
"code": null,
"e": 26497,
"s": 26484,
"text": "Old Comments"
},
{
"code": null,
"e": 26515,
"s": 26497,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26550,
"s": 26515,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26572,
"s": 26550,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26604,
"s": 26572,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26634,
"s": 26604,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26676,
"s": 26634,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26702,
"s": 26676,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26745,
"s": 26702,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26789,
"s": 26745,
"text": "Reading and Writing to text files in Python"
}
] |
What is strcat() Function in C language?
|
The C library function char *strcat(char *dest, const char *src) appends the string pointed to by src to the end of the string pointed to by dest.
An array of characters is called a string.
Following is the declaration for an array β
char stringname [size];
For example β char string[50]; string of length 50 characters
Using single character constant β
char string[10] = { βHβ, βeβ, βlβ, βlβ, βoβ ,β\0β}
Using string constants β
char string[10] = "Hello":;
Accessing β There is a control string "%s" used for accessing the string till it encounters β\0β.
This is used for combining or concatenating two strings.
This is used for combining or concatenating two strings.
The length of the destination string must be greater than the source string.
The length of the destination string must be greater than the source string.
The result concatenated string is the source string.
The result concatenated string is the source string.
The syntax is as follows β
strcat (Destination String, Source string);
The following program shows the usage of strcat() function.
Live Demo
#include <string.h>
main(){
char a[50] = "Hello \n";
char b[20] = "Good Morning \n";
strcat (a,b);
printf("concatenated string = %s", a);
}
When the above program is executed, it produces the following result β
Concatenated string = Hello Good Morning
Letβs see another example.
Following is the C program to concatenate source string to destination string using strcat library function β
#include<stdio.h>
#include<string.h>
void main(){
//Declaring source and destination strings//
char source[45],destination[50];
//Reading source string and destination string from user//
printf("Enter the source string : \n");
gets(source);
printf("Enter the destination string : \n");
gets(destination);
//Concatenate all the above results//
strcat(source,destination);
//Printing destination string//
printf("The modified destination string :");
puts(source);
}
When the above program is executed, it produces the following result β
Enter the source string :Tutorials Point
Enter the destination string :C programming
The modified destination string :Tutorials Point C programming
|
[
{
"code": null,
"e": 1209,
"s": 1062,
"text": "The C library function char *strcat(char *dest, const char *src) appends the string pointed to by src to the end of the string pointed to by dest."
},
{
"code": null,
"e": 1252,
"s": 1209,
"text": "An array of characters is called a string."
},
{
"code": null,
"e": 1296,
"s": 1252,
"text": "Following is the declaration for an array β"
},
{
"code": null,
"e": 1320,
"s": 1296,
"text": "char stringname [size];"
},
{
"code": null,
"e": 1382,
"s": 1320,
"text": "For example β char string[50]; string of length 50 characters"
},
{
"code": null,
"e": 1416,
"s": 1382,
"text": "Using single character constant β"
},
{
"code": null,
"e": 1467,
"s": 1416,
"text": "char string[10] = { βHβ, βeβ, βlβ, βlβ, βoβ ,β\\0β}"
},
{
"code": null,
"e": 1492,
"s": 1467,
"text": "Using string constants β"
},
{
"code": null,
"e": 1520,
"s": 1492,
"text": "char string[10] = \"Hello\":;"
},
{
"code": null,
"e": 1618,
"s": 1520,
"text": "Accessing β There is a control string \"%s\" used for accessing the string till it encounters β\\0β."
},
{
"code": null,
"e": 1675,
"s": 1618,
"text": "This is used for combining or concatenating two strings."
},
{
"code": null,
"e": 1732,
"s": 1675,
"text": "This is used for combining or concatenating two strings."
},
{
"code": null,
"e": 1809,
"s": 1732,
"text": "The length of the destination string must be greater than the source string."
},
{
"code": null,
"e": 1886,
"s": 1809,
"text": "The length of the destination string must be greater than the source string."
},
{
"code": null,
"e": 1939,
"s": 1886,
"text": "The result concatenated string is the source string."
},
{
"code": null,
"e": 1992,
"s": 1939,
"text": "The result concatenated string is the source string."
},
{
"code": null,
"e": 2019,
"s": 1992,
"text": "The syntax is as follows β"
},
{
"code": null,
"e": 2063,
"s": 2019,
"text": "strcat (Destination String, Source string);"
},
{
"code": null,
"e": 2123,
"s": 2063,
"text": "The following program shows the usage of strcat() function."
},
{
"code": null,
"e": 2134,
"s": 2123,
"text": " Live Demo"
},
{
"code": null,
"e": 2286,
"s": 2134,
"text": "#include <string.h>\nmain(){\n char a[50] = \"Hello \\n\";\n char b[20] = \"Good Morning \\n\";\n strcat (a,b);\n printf(\"concatenated string = %s\", a);\n}"
},
{
"code": null,
"e": 2357,
"s": 2286,
"text": "When the above program is executed, it produces the following result β"
},
{
"code": null,
"e": 2398,
"s": 2357,
"text": "Concatenated string = Hello Good Morning"
},
{
"code": null,
"e": 2425,
"s": 2398,
"text": "Letβs see another example."
},
{
"code": null,
"e": 2535,
"s": 2425,
"text": "Following is the C program to concatenate source string to destination string using strcat library function β"
},
{
"code": null,
"e": 3035,
"s": 2535,
"text": "#include<stdio.h>\n#include<string.h>\nvoid main(){\n //Declaring source and destination strings//\n char source[45],destination[50];\n //Reading source string and destination string from user//\n printf(\"Enter the source string : \\n\");\n gets(source);\n printf(\"Enter the destination string : \\n\");\n gets(destination);\n //Concatenate all the above results//\n strcat(source,destination);\n //Printing destination string//\n printf(\"The modified destination string :\");\n puts(source);\n}"
},
{
"code": null,
"e": 3106,
"s": 3035,
"text": "When the above program is executed, it produces the following result β"
},
{
"code": null,
"e": 3254,
"s": 3106,
"text": "Enter the source string :Tutorials Point\nEnter the destination string :C programming\nThe modified destination string :Tutorials Point C programming"
}
] |
Laravel - Errors and Logging
|
This chapter deals with errors and logging in Laravel projects and how to work on them.
A project while underway, is borne to have a few errors. Errors and exception handling is already configured for you when you start a new Laravel project. Normally, in a local environment we need to see errors for debugging purposes. We need to hide these errors from users in production environment. This can be achieved with the variable APP_DEBUG set in the environment file .env stored at the root of the application.
For local environment the value of APP_DEBUG should be true but for production it needs to be set to false to hide errors.
Note β After changing the APP_DEBUG variable, you should restart the Laravel server.
Logging is an important mechanism by which system can log errors that are generated. It is useful to improve the reliability of the system. Laravel supports different logging modes like single, daily, syslog, and errorlog modes. You can set these modes in config/app.php file.
'log' => 'daily'
You can see the generated log entries in storage/logs/laravel.log file.
13 Lectures
3 hours
Sebastian Sulinski
35 Lectures
3.5 hours
Antonio Papa
7 Lectures
1.5 hours
Sebastian Sulinski
42 Lectures
1 hours
Skillbakerystudios
165 Lectures
13 hours
Paul Carlo Tordecilla
116 Lectures
13 hours
Hafizullah Masoudi
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2560,
"s": 2472,
"text": "This chapter deals with errors and logging in Laravel projects and how to work on them."
},
{
"code": null,
"e": 2982,
"s": 2560,
"text": "A project while underway, is borne to have a few errors. Errors and exception handling is already configured for you when you start a new Laravel project. Normally, in a local environment we need to see errors for debugging purposes. We need to hide these errors from users in production environment. This can be achieved with the variable APP_DEBUG set in the environment file .env stored at the root of the application."
},
{
"code": null,
"e": 3105,
"s": 2982,
"text": "For local environment the value of APP_DEBUG should be true but for production it needs to be set to false to hide errors."
},
{
"code": null,
"e": 3190,
"s": 3105,
"text": "Note β After changing the APP_DEBUG variable, you should restart the Laravel server."
},
{
"code": null,
"e": 3467,
"s": 3190,
"text": "Logging is an important mechanism by which system can log errors that are generated. It is useful to improve the reliability of the system. Laravel supports different logging modes like single, daily, syslog, and errorlog modes. You can set these modes in config/app.php file."
},
{
"code": null,
"e": 3485,
"s": 3467,
"text": "'log' => 'daily'\n"
},
{
"code": null,
"e": 3557,
"s": 3485,
"text": "You can see the generated log entries in storage/logs/laravel.log file."
},
{
"code": null,
"e": 3590,
"s": 3557,
"text": "\n 13 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3610,
"s": 3590,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 3645,
"s": 3610,
"text": "\n 35 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3659,
"s": 3645,
"text": " Antonio Papa"
},
{
"code": null,
"e": 3693,
"s": 3659,
"text": "\n 7 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3713,
"s": 3693,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 3746,
"s": 3713,
"text": "\n 42 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3766,
"s": 3746,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 3801,
"s": 3766,
"text": "\n 165 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3824,
"s": 3801,
"text": " Paul Carlo Tordecilla"
},
{
"code": null,
"e": 3859,
"s": 3824,
"text": "\n 116 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3879,
"s": 3859,
"text": " Hafizullah Masoudi"
},
{
"code": null,
"e": 3886,
"s": 3879,
"text": " Print"
},
{
"code": null,
"e": 3897,
"s": 3886,
"text": " Add Notes"
}
] |
What are the types of variables a class can have in Java?
|
There are three different types of variables a class can have in Java are local variables, instance variables, and class/static variables.
A local variable in Java can be declared locally in methods, code blocks, and constructors. When the program control enters the methods, code blocks, and constructors then the local variables are created and when the program control leaves the methods, code blocks, and constructors then the local variables are destroyed. A local variable must be initialized with some value.
public class LocalVariableTest {
public void show() {
int num = 100; // local variable
System.out.println("The number is : " + num);
}
public static void main(String args[]) {
LocalVariableTest test = new LocalVariableTest();
test.show();
}
}
The number is : 100
An instance variable in Java can be declared outside a block, method or constructor but inside a class. These variables are created when the class object is created and destroyed when the class object is destroyed.
public class InstanceVariableTest {
int num; // instance variable
InstanceVariableTest(int n) {
num = n;
}
public void show() {
System.out.println("The number is: " + num);
}
public static void main(String args[]) {
InstanceVariableTest test = new InstanceVariableTest(75);
test.show();
}
}
The number is : 75
A static/class variable can be defined using the static keyword. These variables are declared inside a class but outside a method and code block. A class/static variable can be created at the start of the program and destroyed at the end of the program.
public class StaticVaribleTest {
int num;
static int count; // static variable
StaticVaribleTest(int n) {
num = n;
count ++;
}
public void show() {
System.out.println("The number is: " + num);
}
public static void main(String args[]) {
StaticVaribleTest test1 = new StaticVaribleTest(75);
test1.show();
StaticVaribleTest test2 = new StaticVaribleTest(90);
test2.show();
System.out.println("The total objects of a class created are: " + count);
}
}
The number is: 75
The number is: 90
The total objects of a class created are: 2
|
[
{
"code": null,
"e": 1201,
"s": 1062,
"text": "There are three different types of variables a class can have in Java are local variables, instance variables, and class/static variables."
},
{
"code": null,
"e": 1578,
"s": 1201,
"text": "A local variable in Java can be declared locally in methods, code blocks, and constructors. When the program control enters the methods, code blocks, and constructors then the local variables are created and when the program control leaves the methods, code blocks, and constructors then the local variables are destroyed. A local variable must be initialized with some value."
},
{
"code": null,
"e": 1857,
"s": 1578,
"text": "public class LocalVariableTest {\n public void show() {\n int num = 100; // local variable\n System.out.println(\"The number is : \" + num);\n }\n public static void main(String args[]) {\n LocalVariableTest test = new LocalVariableTest();\n test.show();\n }\n}"
},
{
"code": null,
"e": 1878,
"s": 1857,
"text": "The number is : 100\n"
},
{
"code": null,
"e": 2093,
"s": 1878,
"text": "An instance variable in Java can be declared outside a block, method or constructor but inside a class. These variables are created when the class object is created and destroyed when the class object is destroyed."
},
{
"code": null,
"e": 2429,
"s": 2093,
"text": "public class InstanceVariableTest {\n int num; // instance variable\n InstanceVariableTest(int n) {\n num = n;\n }\n public void show() {\n System.out.println(\"The number is: \" + num);\n }\n public static void main(String args[]) {\n InstanceVariableTest test = new InstanceVariableTest(75);\n test.show();\n }\n}"
},
{
"code": null,
"e": 2449,
"s": 2429,
"text": "The number is : 75\n"
},
{
"code": null,
"e": 2703,
"s": 2449,
"text": "A static/class variable can be defined using the static keyword. These variables are declared inside a class but outside a method and code block. A class/static variable can be created at the start of the program and destroyed at the end of the program."
},
{
"code": null,
"e": 3223,
"s": 2703,
"text": "public class StaticVaribleTest {\n int num;\n static int count; // static variable\n StaticVaribleTest(int n) {\n num = n;\n count ++;\n }\n public void show() {\n System.out.println(\"The number is: \" + num);\n }\n public static void main(String args[]) {\n StaticVaribleTest test1 = new StaticVaribleTest(75);\n test1.show();\n StaticVaribleTest test2 = new StaticVaribleTest(90);\n test2.show();\n System.out.println(\"The total objects of a class created are: \" + count);\n }\n}"
},
{
"code": null,
"e": 3303,
"s": 3223,
"text": "The number is: 75\nThe number is: 90\nThe total objects of a class created are: 2"
}
] |
Introduction to Stream Processing | by Ivan Mushketyk | Towards Data Science
|
Together with machine learning and serverless stream processing seems to be one of the hottest topics nowadays. Companies are onboarding modern stream processing tools, service providers are releasing better and more powerful stream processing products, and specialists are in high demand.
This article introduces the basics of stream processing. It starts with a rationale for why we need stream processing and how it works under the hood. Then it goes into how to write simple, scalable distributed stream processing applications. All in fewer than 40 lines of code!
Since stream processing is a vast topic, this article is focused mostly on the data management part while sophisticated processing is left for another article. To make the article more practical, it discusses AWS Kinesis, a stream processing solution from Amazon, but it also refers to other popular Open Source technologies to present a broader picture.
This article has originally been written for Codementor website.
To understand why stream processing came into existence, letβs look into how data processing was done before. With the previous approach, called batch processing, all data was stored in a database or a distributed filesystem, and different applications would perform computation using this data. Since batch processing tools were built to process datasets of finite size, to continuously process new data, an application would periodically crunch data from the last period like one hour or one day.
While this architecture worked for many years and still has many applications, it has fundamental drawbacks. Since new data is not processed as soon as it arrives, this causes several issues:
High latency β new results are computed only after a significant delay, but since the value of data decreases with time, this is undesirable
Session data β since a batch processing system splits data into time intervals, it is hard to analyze events that started during the one-time interval but ended during another time interval
Non-uniform load β a batch processing system should wait until enough data is accumulated before it can process the next block of data
Stream processing, data processing on its head, is all about processing a flow of events. A typical stream application consists of a number of producers that generate new events and a set of consumers that process these events. Events in the system can be any number of things, such as financial transactions, user activity on a website, or application metrics. Consumers can aggregate incoming data, send automatic alerts in real-time, or produce new streams of data that can be processed by other consumers.
This architecture has a number of advantages:
Low-latency β a system can process new events and react to them in real-time
A natural fit for many applications β stream processing system is a natural fit for applications that work with a never-ending stream of events
Uniform processing β instead of waiting for data to accumulate before processing the next batch, stream processing system performs computation as soon as new data arrives
Unsurprisingly, stream processing was first adopted by financial companies that need to process new information, like trades or prices, in real-time, but is now used in many areas like fraud detection, online recommendations, monitoring, and many others.
This architecture, however, poses a question: how should producers and consumers be connected? Should a producer open a TCP session to every consumer and send events directly? While this may be an option, it presents a significant issue if a producer is writing data that a consumer can process. Also, if we have a significant number of consumer and producers, the web of connections can turn into an unruly mess.
This is exactly the problem that LinkedIn faced in 2008, when they ended up with a number of multiple point-to-point pipelines among multiple systems. To organize it, they started working on an internal project that eventually became Apache Kafka. In a nutshell, Kafka is a buffer that allows producers to store new streaming events and consumers to read them, in real-time, at their own pace.
Apache Kafka quickly became a backbone of modern stream processing applications by providing a data integration layer for decoupled event-driven applications. It allows for the easy addition of new consumers and producers and the building of more complex applications. Apache Kafka became so successful that other companies have built services with a similar design, like Azure Event Hubs and AWS Kinesis. The latter will be discussed in more detail in this article.
At first sight, Kafka and Kinesis do not seem like big deals, since alternatives like RabbitMQ have been around for many years. However, if we look under the hood of these systems, we will see that itβs designed differently and allows for the implementation of new use cases.
The foundation of modern stream processing software is a data structure called an append-only log. A log is just a sequence of binary records. Kinesis puts no restrictions on the content of those records β they can be in any format, like: JSON, Avro, Protobuf, etc.
An append-only log only allows for the addition of new elements to the end of the log. We canβt insert new elements at arbitrary positions of the log, and we canβt remove elements at will. Every element in a log has a sequence number, and newer elements have a higher sequence number than older elements.
When a record is read by a consumer, it is not removed and can be read by other consumers as well. Kinesis does not keep track of what records are yet to be read by different consumers. Instead, this responsibility lies with a consumer. This is different from systems, like RabbitMQ. That behave like a queue and keeps track of the state of every consumer.
This architecture allows systems like Kinesis and Kafka to process an insane amount of transactions, with low-latency, far beyond what traditional messaging systems are capable of. It also allows consumers to process data that was written to the buffer before they started.
Keep in mind that Kinesis and Kafka do not make RabbitMQ obsolete and there are still many use-cases where RabbitMQ would be a better fit.
At this point, you may be wondering, βIs data ever removed from a stream?β If we canβt remove records from a stream sooner or later, we wonβt have enough space to store all of the new records.
In both AWS Kinesis and Apache Kafka, records have a retention period and are automatically removed when this period ends. In Kinesis, a record is automatically removed after 24 hours, but the retention period can be increased to up to seven days.
An extended retention period is especially beneficial if, for some reason, your system canβt handle incoming data correctly, and you need to re-process it again. The longer the retention period, the more time you have to fix your production system and reprocess the log. The downside is that you have to pay more for additional storage.
Kafka allows specifying either maximum retention period or maximum retention size of all records. The default retention period is seven days, but it can even be infinite if the log compaction feature is enabled.
Systems like Apache Kafka and AWS Kinesis were built to handle petabytes of data. Since a single machine can never handle this load, they need to scale horizontally. To handle an immense load, both systems apply two well-known tricks to allow to handle more reads and writes: sharding and replication.
In the case of stream processing, sharding means that we have more than one log. A single stream is split into multiple logs, each one being small enough so a single machine can handle it.
To determine what shard to use, we need to provide a key with each record. For each incoming record, Kinesis calculates a hash code of a key and the value of the hash code is used to determine what shard will process it. Each shard is responsible for a portion of the hash code values range, and if a hash code of a key falls within a shardβs range, this shard will store a record associated with it.
How do we come up with a key for a record though? We can select a random key, and then our records will be uniformly distributed among our streamβs shards. We can also use a key from our problemβs domain, such as a hostname, if we process metrics, or payer ID if we process financial transactions. This will allow achieving order among records with the same key, since they will be directed to the same shard.
An important thing to notice is that because a log is split into multiple shards, global order of elements is not preserved. However, an order of elements that end up on the same shard is preserved.
But how many shards should we have? That depends on how many records we need to be able to write and read per second. The more data we need to process, the more shards we need to handle a flow of data. Because of this, we need to have the ability to increase and decrease the number of shards in our stream.
Kinesis allows splitting a single shard into two shards to process more records. If the number of records we need to process has decreased, we can merge two shards with adjacent hash key ranges and combine them in the single shard. This, in turn, will decrease both the throughput and our monthly bill.
bit.ly
As in the databases, world replication means that we maintain several copies of data, and consumers can read from any copy. In the case of Kinesis, every record has three copies in three different data centers.
This has two benefits. First, it makes a stream processing system more resilient to failure, since we can lose two copies of our data. Second, it allows transferring more data to consumers. This is reflected in Kinesis limits that allow to write only up to 1MB of data into a single shard and read up to 2MB of data from a shard.
At this stage, you should have an understanding of how stream processing systems works and how it can process almost an infinite amount of incoming data. Now it is time to go through some actual code examples.
Source: https://bit.ly/2IQCFjM
In this section, we will see how we can use the low-level API to read and write stream data. We will implement a producer that will write metrics data into a stream and a producer that will read and process this stream. Our applications should do the following:
Create a stream
A producer who sends a new record to a stream when we have new data
A consumer who reads and process new records in an infinite loop
Just as with many other AWS services, when we use Kinesis, we do not need to provision hosts or install software. All we need to do is to perform several API calls, and the rest will be done for us. This is what makes Kinesis different from Kafka. Kafka requires a complex set up that is hard to get right.
To perform any operations with Kinesis, we create a Kinesis client first:
// Create an AWS Kinesis client// You may want to set parameters such as AWS region, credentials, etc.AmazonKinesis kinesis = AmazonKinesisClientBuilder .standard() .build();
First, letβs create a stream that we will use to connect our producer and consumer. All we need to do is to provide the name of our stream, an initial number of shards, and call the createStream method.
CreateStreamRequest createStreamRequest = new CreateStreamRequest();// Set the name of a new streamcreateStreamRequest.setStreamName("metrics-stream");// Set initial number of shardscreateStreamRequest.setShardCount(4);client.createStream(createStreamRequest);
After weβve called the createStream method, we need to wait until a new stream is activated. I've omitted this logic for brevity, but you can read a full code example in the AWS documentation.
Now, when we have a stream, we can write some data into it! Writing new data is not much harder. First, for every new record, we need to create a PutRecordRequestinstance, set a stream name, a key, and data that we want to store in the stream. Then we need to call the putRecord method and pass our new record to it:
// A metric data that we need to sendMetric metric = ...;PutRecordRequest putRecordRequest = new PutRecordRequest();// Set a stream name. The same as we created in the previous exampleputRecordRequest.setStreamName("metrics-stream");// Set metric name as a key of the new recordputRecordRequest.setPartitionKey(metric.getMetricName());// Finally we specify data that we want to storeputRecordRequest.setData(metric.toBytes());try { kinesis.putRecord(putRecordRequest);} catch (AmazonClientException ex) { // Don't forget to process an exception!}
This code snippet sends a single record to a stream called metrics-stream.
Keep in mind that neither Kinesis nor Kafka guarantees 100% uptime! Both are complicated systems, and many things can go wrong, from network failure to an execution of an invalid command on a production system. On top of that, AWS Kinesis can even throttle your requests if you attempt to write too much data in a short period of time. Hence, you need to be prepared β implement retry logic and buffer new records locally for a short period of time in case a stream processing system is unavailable.
This is all for writing data. Reading data from a stream is a bit more complicated. In the case of AWS Kinesis, the process looks like this:
Get an iterator to read data from a particular shard
Send a read request and provide an iterator received during the previous step
A read request returns records from a stream and a new iterator that we can use to send another read request to read the next batch of records
Here is how we can get an iterator to read records from a shard named shard-0001, from the beginning, for a stream:
// Create a request to get an iteratorGetShardIteratorRequest getShardIteratorRequest = new GetShardIteratorRequest();// Specify a name of the stream to read records fromgetShardIteratorRequest.setStreamName("metrics-stream");// Specify what shard to read fromgetShardIteratorRequest.setShardId("shard-0001");// Start reading from the oldest recordgetShardIteratorRequest.setShardIteratorType("TRIM_HORIZON");// Get an iterator to read data from a stream from a specific shardGetShardIteratorResult getShardIteratorResult = client.getShardIterator(getShardIteratorRequest);// Iterator that we can use to read records from the specified shardString shardIterator = getShardIteratorResult.getShardIterator();
In this example, we start reading from the oldest record in the stream, but Kinesis supports other iterator types:
AT_SEQUENCE_NUMBER β start reading from a record with the specified sequence number
AFTER_SEQUENCE_NUMBER β start reading after a record with the specified sequence number
AT_TIMESTAMP β start reading records from a specified timestamp
LATEST β start reading after the most recent record in the stream
Notice that we can only get an iterator to read data from a single shard. But how can we get an ID of a shard to read from? We can get a list of shards for a specific stream by using the ListShards method from AWS Kinesis that returns information about shards, including their identifiers:
ListShardsRequest listShardsRequest = new ListShardsRequest();listShardsRequest.setStreamName("metrics-stream");ListShardsResult result = kinesis.listShards(listShardsRequest);for (Shard shard : result.getShards()) { // Get hash key range a shard is responsible for HashKeyRange hashKeyRange = shard.getHashKeyRange(); // Returns first a range of records' sequence numbers in a stream SequenceNumberRange sequenceNumberRange = shard.getSequenceNumberRange(); // Get a shard id that we can use to read data from it String shardId = shard.getShardId(); // Get parent's shard id String parentShardId = shard.getParentShardId();}
Now when we have an iterator, we can read data from a single shard. Since we donβt expect that a stream of records will never end, we read records in an infinite loop. Every time we read a new batch of records from a stream, we get an iterator that we can use to perform the next read.
String shardIterator = ...;while (true) { GetRecordsRequest getRecordsRequest = new GetRecordsRequest(); getRecordsRequest.setShardIterator(shardIterator); getRecordsRequest.setLimit(20); GetRecordsResult result = client.getRecords(getRecordsRequest); // Put the result into record list. The result can be empty. List<Record> records = result.getRecords(); for (Record record: records) { // Process each record } Thread.sleep(200); shardIterator = result.getNextShardIterator();}
Why do we need to sleep for 200 milliseconds? This because each shard in Kinesis allows up to five read transactions per second so that we can read new records at most every 200 ms. The more consumers we have read from a shard, the more each consumer should wait.
Since we used a metric name as a key in the previous example, all metrics with the same name will end up on the same shard. This allows a reader of a shard to process all data for the same metric. In a way, this is similar to MapReduce, when a single reduce execution is processing records with the same key.
So far weβve figured out how to read data from a single shard, but usually, we want to process all records in a stream. Sure, we can start a thread per shard in a stream, but this, however, poses several problems:
What should we do if new shards are created in a stream?
How do we distribute the work of reading records from a stream among multiple machines?
If one of our machines reading from the stream failed, how do we ensure that we continue processing records correctly?
There are multiple stream processing systems that can process records from Kinesis or Kafka streams, such as Apache Spark, Apache Flink, Google Cloud Dataflow, etc., but these are sophisticated tools that are beyond the scope of this article. Here, we will look at how we can use a simpler framework called Kinesis Client Library (KCL).
To use it, we need to do two things:
Implement a processor that will process records from a single shard
Run KCL workers on one or more machines
This is it. KCL will ensure that all records from all shards are processed and that the work is evenly distributed among multiple machines.
Before we start, however, letβs briefly talk about how KCL distributes the work. KCL distributes shards among multiple workers, and every worker controls several processors, with each one processing a shingle shard. There is no βmasterβ node in this system, and every KCL worker is independent of other workers. The state of the system is stored in a DynamoDB table and is constantly updated by each worker. Every record in the DynamoDB table specifies a shard ID from a Kinesis stream, what processor is processing it, and what is the sequence number is of the last processed record in this shard.
Periodically, every KCL worker gets a list of shards from a KCL stream and checks if there are any shards without an assigned processor. If it finds any unassigned shards, a worker creates a record in the DynamoDB table to βacquireβ a shard and creates an instance of a processor to process it. If we scale down a stream and some of the shards are closed, KCL will detect this as well and decrease the number of processors to maintain a 1:1 relationship between processors and shards in a stream.
To implement a processor in KCL, we need to implement the following interface:
// Called once before processor starts processing incoming records public void initialize(InitializationInput initializationInput) {}// Called to process a batch of records read from a Kinesis stream public void processRecords(ProcessRecordsInput processRecordsInput) {}// Called once before the processor is terminated public void shutdown(ShutdownInput shutdownInput) {}}
Letβs implement these methods one by one.
The main method that we need to implement is processRecords. It is called every time the KCL library has read a group of records, and it sends them to a processor. In this method, we need to iterate through a list of records, process every record (here we just print its content to console), and checkpoint our progress.
@Overridepublic void processRecords(ProcessRecordsInput processRecordsInput) { // Iterate through a list of new records to process for (Record record : processRecordsInput.getRecords()) { // First we need to deserialize a metric object Metric metric = parseMetric(record); // Now we can process a single record. Here we just print // record to a console, but we could also send a notification // to a third-party system, write data to a database, calculate // statistics, etc. System.out.println(metric); // At last, we need to signal that this record is processed // Once a record is processed it won't be sent to our processor again checkpoint(processRecordsInput.getCheckpointer(), record); }}private Metric parseMetric(Record record) { ByteBuffer data = record.getData(); // Parse binary data that was recorded to a stream}private void checkpoint(IRecordProcessorCheckpointer checkpointer, Record record) { try { checkpointer.checkpoint(record); } catch (InvalidStateException e) { // DynamoDB Table does not exists // We need recreate the table } catch (ShutdownException e) { // Two processors are processing the same shard // We need stop processing records in this processor }}
There are multiple ways to checkpoint progress, and we should not necessarily do this after weβve processed all records. Depending on our application, it can do this every N records or after weβve processed a batch of records.
Notice that the checkpoint method can throw an exception in case DynamoDB table does not exist or if we have two KCL records processing the same shard.
The last method that we need to implement is the shutdown. This method is the last chance for our processor to checkpoint its progress, and this is exactly what we do here:
public void shutdown(ShutdownInput shutdownInput) { ShutdownReason reason = shutdownInput.getShutdownReason(); switch (reason) { // Re-sharding, no more records in current shard case TERMINATE: // Application shutdown case REQUESTED: checkpoint(shutdownInput.getCheckpointer(), lastProcessedRecord); break; // Processing will be moved to a different record processor case ZOMBIE: // No need to checkpoint break; }}
The majority of work is done, but we also need to provide a factory object for KCL to create an instance of our processor:
public class MetricsProcessorFactory implements IRecordProcessorFactory {public IRecordProcessor createProcessor() { return new MetricRecordsProcessor(); }}
Now, when we have all the parts in place, all we need to do is to start a KCL worker. We will launch this code on as many machines as we need to process our Kinesis stream.
// Configuration for a worker instancefinal KinesisClientLibConfiguration config = new KinesisClientLibConfiguration( // Name of our application "metrics-processor", // Name of stream to process "metrics-stream", new DefaultAWSCredentialsProviderChain(), // Name of this KCL worker instance. Should be different for different processes/machines "worker-1");// Create a factory that knows how to create an instance of our records processorfinal IRecordProcessorFactory recordProcessorFactory = new MetricsProcessorFactory();// Create a KCL worker. We only need one per machinefinal Worker worker = new Worker.Builder() .config(config) .recordProcessorFactory(recordProcessorFactory) .build();// Start KCL workerworker.run();
That is all we need to do to implement a distributed stream processing. KCL will launch a processor per Kinesis shard and will distribute load among multiple machines automatically.
Notice that KCL can launch additional threads. However, if you need more machines to process incoming records you need to take care of this yourself. If you use AWS, you can use auto-scaling groups to automatically add more machines if CPU utilization gets too high.
To make these concepts more practical, Iβve implemented a small GitHub project that shows how to use AWS Kinesis. You can look through the code and run working examples. It consists of several small applications that create AWS resources, produces streaming data, and read data from the stream.
That was a brief introduction to the field of stream processing. Modern stream processing systems are based on the append-only log data structure that allows building a data ingestion infrastructure. Stream processing systems allow producers to write new records to a log, and multiple consumers can read records from a log in parallel. Weβve also covered how to create a simple stream processing applications using AWS Kinesis
This article just scratched the surface of the topic. It didnβt cover such interesting topics windows in stream, stream processing frameworks, a concept of time in streaming data, streaming SQL (sounds like an oxymoron, I know!), etc., and I hope to cover these and many other topics in upcoming articles.
Hi! My name is Ivan Mushketyk, I am an avid software engineer, Open Source contributor, blogger, and a course author for Pluralsight, Udacity, and Coursera.
If you liked this article, you can watch my deep dive Pluralsight course Developing Stream Processing Applications with AWS Kinesis, which covers the ins and out of AWS Kinesis.
|
[
{
"code": null,
"e": 461,
"s": 171,
"text": "Together with machine learning and serverless stream processing seems to be one of the hottest topics nowadays. Companies are onboarding modern stream processing tools, service providers are releasing better and more powerful stream processing products, and specialists are in high demand."
},
{
"code": null,
"e": 740,
"s": 461,
"text": "This article introduces the basics of stream processing. It starts with a rationale for why we need stream processing and how it works under the hood. Then it goes into how to write simple, scalable distributed stream processing applications. All in fewer than 40 lines of code!"
},
{
"code": null,
"e": 1095,
"s": 740,
"text": "Since stream processing is a vast topic, this article is focused mostly on the data management part while sophisticated processing is left for another article. To make the article more practical, it discusses AWS Kinesis, a stream processing solution from Amazon, but it also refers to other popular Open Source technologies to present a broader picture."
},
{
"code": null,
"e": 1160,
"s": 1095,
"text": "This article has originally been written for Codementor website."
},
{
"code": null,
"e": 1659,
"s": 1160,
"text": "To understand why stream processing came into existence, letβs look into how data processing was done before. With the previous approach, called batch processing, all data was stored in a database or a distributed filesystem, and different applications would perform computation using this data. Since batch processing tools were built to process datasets of finite size, to continuously process new data, an application would periodically crunch data from the last period like one hour or one day."
},
{
"code": null,
"e": 1851,
"s": 1659,
"text": "While this architecture worked for many years and still has many applications, it has fundamental drawbacks. Since new data is not processed as soon as it arrives, this causes several issues:"
},
{
"code": null,
"e": 1992,
"s": 1851,
"text": "High latency β new results are computed only after a significant delay, but since the value of data decreases with time, this is undesirable"
},
{
"code": null,
"e": 2182,
"s": 1992,
"text": "Session data β since a batch processing system splits data into time intervals, it is hard to analyze events that started during the one-time interval but ended during another time interval"
},
{
"code": null,
"e": 2317,
"s": 2182,
"text": "Non-uniform load β a batch processing system should wait until enough data is accumulated before it can process the next block of data"
},
{
"code": null,
"e": 2827,
"s": 2317,
"text": "Stream processing, data processing on its head, is all about processing a flow of events. A typical stream application consists of a number of producers that generate new events and a set of consumers that process these events. Events in the system can be any number of things, such as financial transactions, user activity on a website, or application metrics. Consumers can aggregate incoming data, send automatic alerts in real-time, or produce new streams of data that can be processed by other consumers."
},
{
"code": null,
"e": 2873,
"s": 2827,
"text": "This architecture has a number of advantages:"
},
{
"code": null,
"e": 2950,
"s": 2873,
"text": "Low-latency β a system can process new events and react to them in real-time"
},
{
"code": null,
"e": 3094,
"s": 2950,
"text": "A natural fit for many applications β stream processing system is a natural fit for applications that work with a never-ending stream of events"
},
{
"code": null,
"e": 3265,
"s": 3094,
"text": "Uniform processing β instead of waiting for data to accumulate before processing the next batch, stream processing system performs computation as soon as new data arrives"
},
{
"code": null,
"e": 3520,
"s": 3265,
"text": "Unsurprisingly, stream processing was first adopted by financial companies that need to process new information, like trades or prices, in real-time, but is now used in many areas like fraud detection, online recommendations, monitoring, and many others."
},
{
"code": null,
"e": 3934,
"s": 3520,
"text": "This architecture, however, poses a question: how should producers and consumers be connected? Should a producer open a TCP session to every consumer and send events directly? While this may be an option, it presents a significant issue if a producer is writing data that a consumer can process. Also, if we have a significant number of consumer and producers, the web of connections can turn into an unruly mess."
},
{
"code": null,
"e": 4328,
"s": 3934,
"text": "This is exactly the problem that LinkedIn faced in 2008, when they ended up with a number of multiple point-to-point pipelines among multiple systems. To organize it, they started working on an internal project that eventually became Apache Kafka. In a nutshell, Kafka is a buffer that allows producers to store new streaming events and consumers to read them, in real-time, at their own pace."
},
{
"code": null,
"e": 4795,
"s": 4328,
"text": "Apache Kafka quickly became a backbone of modern stream processing applications by providing a data integration layer for decoupled event-driven applications. It allows for the easy addition of new consumers and producers and the building of more complex applications. Apache Kafka became so successful that other companies have built services with a similar design, like Azure Event Hubs and AWS Kinesis. The latter will be discussed in more detail in this article."
},
{
"code": null,
"e": 5071,
"s": 4795,
"text": "At first sight, Kafka and Kinesis do not seem like big deals, since alternatives like RabbitMQ have been around for many years. However, if we look under the hood of these systems, we will see that itβs designed differently and allows for the implementation of new use cases."
},
{
"code": null,
"e": 5337,
"s": 5071,
"text": "The foundation of modern stream processing software is a data structure called an append-only log. A log is just a sequence of binary records. Kinesis puts no restrictions on the content of those records β they can be in any format, like: JSON, Avro, Protobuf, etc."
},
{
"code": null,
"e": 5642,
"s": 5337,
"text": "An append-only log only allows for the addition of new elements to the end of the log. We canβt insert new elements at arbitrary positions of the log, and we canβt remove elements at will. Every element in a log has a sequence number, and newer elements have a higher sequence number than older elements."
},
{
"code": null,
"e": 5999,
"s": 5642,
"text": "When a record is read by a consumer, it is not removed and can be read by other consumers as well. Kinesis does not keep track of what records are yet to be read by different consumers. Instead, this responsibility lies with a consumer. This is different from systems, like RabbitMQ. That behave like a queue and keeps track of the state of every consumer."
},
{
"code": null,
"e": 6273,
"s": 5999,
"text": "This architecture allows systems like Kinesis and Kafka to process an insane amount of transactions, with low-latency, far beyond what traditional messaging systems are capable of. It also allows consumers to process data that was written to the buffer before they started."
},
{
"code": null,
"e": 6412,
"s": 6273,
"text": "Keep in mind that Kinesis and Kafka do not make RabbitMQ obsolete and there are still many use-cases where RabbitMQ would be a better fit."
},
{
"code": null,
"e": 6605,
"s": 6412,
"text": "At this point, you may be wondering, βIs data ever removed from a stream?β If we canβt remove records from a stream sooner or later, we wonβt have enough space to store all of the new records."
},
{
"code": null,
"e": 6853,
"s": 6605,
"text": "In both AWS Kinesis and Apache Kafka, records have a retention period and are automatically removed when this period ends. In Kinesis, a record is automatically removed after 24 hours, but the retention period can be increased to up to seven days."
},
{
"code": null,
"e": 7190,
"s": 6853,
"text": "An extended retention period is especially beneficial if, for some reason, your system canβt handle incoming data correctly, and you need to re-process it again. The longer the retention period, the more time you have to fix your production system and reprocess the log. The downside is that you have to pay more for additional storage."
},
{
"code": null,
"e": 7402,
"s": 7190,
"text": "Kafka allows specifying either maximum retention period or maximum retention size of all records. The default retention period is seven days, but it can even be infinite if the log compaction feature is enabled."
},
{
"code": null,
"e": 7704,
"s": 7402,
"text": "Systems like Apache Kafka and AWS Kinesis were built to handle petabytes of data. Since a single machine can never handle this load, they need to scale horizontally. To handle an immense load, both systems apply two well-known tricks to allow to handle more reads and writes: sharding and replication."
},
{
"code": null,
"e": 7893,
"s": 7704,
"text": "In the case of stream processing, sharding means that we have more than one log. A single stream is split into multiple logs, each one being small enough so a single machine can handle it."
},
{
"code": null,
"e": 8294,
"s": 7893,
"text": "To determine what shard to use, we need to provide a key with each record. For each incoming record, Kinesis calculates a hash code of a key and the value of the hash code is used to determine what shard will process it. Each shard is responsible for a portion of the hash code values range, and if a hash code of a key falls within a shardβs range, this shard will store a record associated with it."
},
{
"code": null,
"e": 8704,
"s": 8294,
"text": "How do we come up with a key for a record though? We can select a random key, and then our records will be uniformly distributed among our streamβs shards. We can also use a key from our problemβs domain, such as a hostname, if we process metrics, or payer ID if we process financial transactions. This will allow achieving order among records with the same key, since they will be directed to the same shard."
},
{
"code": null,
"e": 8903,
"s": 8704,
"text": "An important thing to notice is that because a log is split into multiple shards, global order of elements is not preserved. However, an order of elements that end up on the same shard is preserved."
},
{
"code": null,
"e": 9211,
"s": 8903,
"text": "But how many shards should we have? That depends on how many records we need to be able to write and read per second. The more data we need to process, the more shards we need to handle a flow of data. Because of this, we need to have the ability to increase and decrease the number of shards in our stream."
},
{
"code": null,
"e": 9514,
"s": 9211,
"text": "Kinesis allows splitting a single shard into two shards to process more records. If the number of records we need to process has decreased, we can merge two shards with adjacent hash key ranges and combine them in the single shard. This, in turn, will decrease both the throughput and our monthly bill."
},
{
"code": null,
"e": 9521,
"s": 9514,
"text": "bit.ly"
},
{
"code": null,
"e": 9732,
"s": 9521,
"text": "As in the databases, world replication means that we maintain several copies of data, and consumers can read from any copy. In the case of Kinesis, every record has three copies in three different data centers."
},
{
"code": null,
"e": 10062,
"s": 9732,
"text": "This has two benefits. First, it makes a stream processing system more resilient to failure, since we can lose two copies of our data. Second, it allows transferring more data to consumers. This is reflected in Kinesis limits that allow to write only up to 1MB of data into a single shard and read up to 2MB of data from a shard."
},
{
"code": null,
"e": 10272,
"s": 10062,
"text": "At this stage, you should have an understanding of how stream processing systems works and how it can process almost an infinite amount of incoming data. Now it is time to go through some actual code examples."
},
{
"code": null,
"e": 10303,
"s": 10272,
"text": "Source: https://bit.ly/2IQCFjM"
},
{
"code": null,
"e": 10565,
"s": 10303,
"text": "In this section, we will see how we can use the low-level API to read and write stream data. We will implement a producer that will write metrics data into a stream and a producer that will read and process this stream. Our applications should do the following:"
},
{
"code": null,
"e": 10581,
"s": 10565,
"text": "Create a stream"
},
{
"code": null,
"e": 10649,
"s": 10581,
"text": "A producer who sends a new record to a stream when we have new data"
},
{
"code": null,
"e": 10714,
"s": 10649,
"text": "A consumer who reads and process new records in an infinite loop"
},
{
"code": null,
"e": 11021,
"s": 10714,
"text": "Just as with many other AWS services, when we use Kinesis, we do not need to provision hosts or install software. All we need to do is to perform several API calls, and the rest will be done for us. This is what makes Kinesis different from Kafka. Kafka requires a complex set up that is hard to get right."
},
{
"code": null,
"e": 11095,
"s": 11021,
"text": "To perform any operations with Kinesis, we create a Kinesis client first:"
},
{
"code": null,
"e": 11276,
"s": 11095,
"text": "// Create an AWS Kinesis client// You may want to set parameters such as AWS region, credentials, etc.AmazonKinesis kinesis = AmazonKinesisClientBuilder .standard() .build();"
},
{
"code": null,
"e": 11479,
"s": 11276,
"text": "First, letβs create a stream that we will use to connect our producer and consumer. All we need to do is to provide the name of our stream, an initial number of shards, and call the createStream method."
},
{
"code": null,
"e": 11740,
"s": 11479,
"text": "CreateStreamRequest createStreamRequest = new CreateStreamRequest();// Set the name of a new streamcreateStreamRequest.setStreamName(\"metrics-stream\");// Set initial number of shardscreateStreamRequest.setShardCount(4);client.createStream(createStreamRequest);"
},
{
"code": null,
"e": 11933,
"s": 11740,
"text": "After weβve called the createStream method, we need to wait until a new stream is activated. I've omitted this logic for brevity, but you can read a full code example in the AWS documentation."
},
{
"code": null,
"e": 12250,
"s": 11933,
"text": "Now, when we have a stream, we can write some data into it! Writing new data is not much harder. First, for every new record, we need to create a PutRecordRequestinstance, set a stream name, a key, and data that we want to store in the stream. Then we need to call the putRecord method and pass our new record to it:"
},
{
"code": null,
"e": 12803,
"s": 12250,
"text": "// A metric data that we need to sendMetric metric = ...;PutRecordRequest putRecordRequest = new PutRecordRequest();// Set a stream name. The same as we created in the previous exampleputRecordRequest.setStreamName(\"metrics-stream\");// Set metric name as a key of the new recordputRecordRequest.setPartitionKey(metric.getMetricName());// Finally we specify data that we want to storeputRecordRequest.setData(metric.toBytes());try { kinesis.putRecord(putRecordRequest);} catch (AmazonClientException ex) { // Don't forget to process an exception!}"
},
{
"code": null,
"e": 12878,
"s": 12803,
"text": "This code snippet sends a single record to a stream called metrics-stream."
},
{
"code": null,
"e": 13378,
"s": 12878,
"text": "Keep in mind that neither Kinesis nor Kafka guarantees 100% uptime! Both are complicated systems, and many things can go wrong, from network failure to an execution of an invalid command on a production system. On top of that, AWS Kinesis can even throttle your requests if you attempt to write too much data in a short period of time. Hence, you need to be prepared β implement retry logic and buffer new records locally for a short period of time in case a stream processing system is unavailable."
},
{
"code": null,
"e": 13519,
"s": 13378,
"text": "This is all for writing data. Reading data from a stream is a bit more complicated. In the case of AWS Kinesis, the process looks like this:"
},
{
"code": null,
"e": 13572,
"s": 13519,
"text": "Get an iterator to read data from a particular shard"
},
{
"code": null,
"e": 13650,
"s": 13572,
"text": "Send a read request and provide an iterator received during the previous step"
},
{
"code": null,
"e": 13793,
"s": 13650,
"text": "A read request returns records from a stream and a new iterator that we can use to send another read request to read the next batch of records"
},
{
"code": null,
"e": 13909,
"s": 13793,
"text": "Here is how we can get an iterator to read records from a shard named shard-0001, from the beginning, for a stream:"
},
{
"code": null,
"e": 14616,
"s": 13909,
"text": "// Create a request to get an iteratorGetShardIteratorRequest getShardIteratorRequest = new GetShardIteratorRequest();// Specify a name of the stream to read records fromgetShardIteratorRequest.setStreamName(\"metrics-stream\");// Specify what shard to read fromgetShardIteratorRequest.setShardId(\"shard-0001\");// Start reading from the oldest recordgetShardIteratorRequest.setShardIteratorType(\"TRIM_HORIZON\");// Get an iterator to read data from a stream from a specific shardGetShardIteratorResult getShardIteratorResult = client.getShardIterator(getShardIteratorRequest);// Iterator that we can use to read records from the specified shardString shardIterator = getShardIteratorResult.getShardIterator();"
},
{
"code": null,
"e": 14731,
"s": 14616,
"text": "In this example, we start reading from the oldest record in the stream, but Kinesis supports other iterator types:"
},
{
"code": null,
"e": 14815,
"s": 14731,
"text": "AT_SEQUENCE_NUMBER β start reading from a record with the specified sequence number"
},
{
"code": null,
"e": 14903,
"s": 14815,
"text": "AFTER_SEQUENCE_NUMBER β start reading after a record with the specified sequence number"
},
{
"code": null,
"e": 14967,
"s": 14903,
"text": "AT_TIMESTAMP β start reading records from a specified timestamp"
},
{
"code": null,
"e": 15033,
"s": 14967,
"text": "LATEST β start reading after the most recent record in the stream"
},
{
"code": null,
"e": 15323,
"s": 15033,
"text": "Notice that we can only get an iterator to read data from a single shard. But how can we get an ID of a shard to read from? We can get a list of shards for a specific stream by using the ListShards method from AWS Kinesis that returns information about shards, including their identifiers:"
},
{
"code": null,
"e": 15973,
"s": 15323,
"text": "ListShardsRequest listShardsRequest = new ListShardsRequest();listShardsRequest.setStreamName(\"metrics-stream\");ListShardsResult result = kinesis.listShards(listShardsRequest);for (Shard shard : result.getShards()) { // Get hash key range a shard is responsible for HashKeyRange hashKeyRange = shard.getHashKeyRange(); // Returns first a range of records' sequence numbers in a stream SequenceNumberRange sequenceNumberRange = shard.getSequenceNumberRange(); // Get a shard id that we can use to read data from it String shardId = shard.getShardId(); // Get parent's shard id String parentShardId = shard.getParentShardId();}"
},
{
"code": null,
"e": 16259,
"s": 15973,
"text": "Now when we have an iterator, we can read data from a single shard. Since we donβt expect that a stream of records will never end, we read records in an infinite loop. Every time we read a new batch of records from a stream, we get an iterator that we can use to perform the next read."
},
{
"code": null,
"e": 16801,
"s": 16259,
"text": "String shardIterator = ...;while (true) { GetRecordsRequest getRecordsRequest = new GetRecordsRequest(); getRecordsRequest.setShardIterator(shardIterator); getRecordsRequest.setLimit(20); GetRecordsResult result = client.getRecords(getRecordsRequest); // Put the result into record list. The result can be empty. List<Record> records = result.getRecords(); for (Record record: records) { // Process each record } Thread.sleep(200); shardIterator = result.getNextShardIterator();}"
},
{
"code": null,
"e": 17065,
"s": 16801,
"text": "Why do we need to sleep for 200 milliseconds? This because each shard in Kinesis allows up to five read transactions per second so that we can read new records at most every 200 ms. The more consumers we have read from a shard, the more each consumer should wait."
},
{
"code": null,
"e": 17374,
"s": 17065,
"text": "Since we used a metric name as a key in the previous example, all metrics with the same name will end up on the same shard. This allows a reader of a shard to process all data for the same metric. In a way, this is similar to MapReduce, when a single reduce execution is processing records with the same key."
},
{
"code": null,
"e": 17588,
"s": 17374,
"text": "So far weβve figured out how to read data from a single shard, but usually, we want to process all records in a stream. Sure, we can start a thread per shard in a stream, but this, however, poses several problems:"
},
{
"code": null,
"e": 17645,
"s": 17588,
"text": "What should we do if new shards are created in a stream?"
},
{
"code": null,
"e": 17733,
"s": 17645,
"text": "How do we distribute the work of reading records from a stream among multiple machines?"
},
{
"code": null,
"e": 17852,
"s": 17733,
"text": "If one of our machines reading from the stream failed, how do we ensure that we continue processing records correctly?"
},
{
"code": null,
"e": 18189,
"s": 17852,
"text": "There are multiple stream processing systems that can process records from Kinesis or Kafka streams, such as Apache Spark, Apache Flink, Google Cloud Dataflow, etc., but these are sophisticated tools that are beyond the scope of this article. Here, we will look at how we can use a simpler framework called Kinesis Client Library (KCL)."
},
{
"code": null,
"e": 18226,
"s": 18189,
"text": "To use it, we need to do two things:"
},
{
"code": null,
"e": 18294,
"s": 18226,
"text": "Implement a processor that will process records from a single shard"
},
{
"code": null,
"e": 18334,
"s": 18294,
"text": "Run KCL workers on one or more machines"
},
{
"code": null,
"e": 18474,
"s": 18334,
"text": "This is it. KCL will ensure that all records from all shards are processed and that the work is evenly distributed among multiple machines."
},
{
"code": null,
"e": 19073,
"s": 18474,
"text": "Before we start, however, letβs briefly talk about how KCL distributes the work. KCL distributes shards among multiple workers, and every worker controls several processors, with each one processing a shingle shard. There is no βmasterβ node in this system, and every KCL worker is independent of other workers. The state of the system is stored in a DynamoDB table and is constantly updated by each worker. Every record in the DynamoDB table specifies a shard ID from a Kinesis stream, what processor is processing it, and what is the sequence number is of the last processed record in this shard."
},
{
"code": null,
"e": 19570,
"s": 19073,
"text": "Periodically, every KCL worker gets a list of shards from a KCL stream and checks if there are any shards without an assigned processor. If it finds any unassigned shards, a worker creates a record in the DynamoDB table to βacquireβ a shard and creates an instance of a processor to process it. If we scale down a stream and some of the shards are closed, KCL will detect this as well and decrease the number of processors to maintain a 1:1 relationship between processors and shards in a stream."
},
{
"code": null,
"e": 19649,
"s": 19570,
"text": "To implement a processor in KCL, we need to implement the following interface:"
},
{
"code": null,
"e": 20032,
"s": 19649,
"text": "// Called once before processor starts processing incoming records public void initialize(InitializationInput initializationInput) {}// Called to process a batch of records read from a Kinesis stream public void processRecords(ProcessRecordsInput processRecordsInput) {}// Called once before the processor is terminated public void shutdown(ShutdownInput shutdownInput) {}}"
},
{
"code": null,
"e": 20074,
"s": 20032,
"text": "Letβs implement these methods one by one."
},
{
"code": null,
"e": 20395,
"s": 20074,
"text": "The main method that we need to implement is processRecords. It is called every time the KCL library has read a group of records, and it sends them to a processor. In this method, we need to iterate through a list of records, process every record (here we just print its content to console), and checkpoint our progress."
},
{
"code": null,
"e": 21730,
"s": 20395,
"text": "@Overridepublic void processRecords(ProcessRecordsInput processRecordsInput) { // Iterate through a list of new records to process for (Record record : processRecordsInput.getRecords()) { // First we need to deserialize a metric object Metric metric = parseMetric(record); // Now we can process a single record. Here we just print // record to a console, but we could also send a notification // to a third-party system, write data to a database, calculate // statistics, etc. System.out.println(metric); // At last, we need to signal that this record is processed // Once a record is processed it won't be sent to our processor again checkpoint(processRecordsInput.getCheckpointer(), record); }}private Metric parseMetric(Record record) { ByteBuffer data = record.getData(); // Parse binary data that was recorded to a stream}private void checkpoint(IRecordProcessorCheckpointer checkpointer, Record record) { try { checkpointer.checkpoint(record); } catch (InvalidStateException e) { // DynamoDB Table does not exists // We need recreate the table } catch (ShutdownException e) { // Two processors are processing the same shard // We need stop processing records in this processor }}"
},
{
"code": null,
"e": 21957,
"s": 21730,
"text": "There are multiple ways to checkpoint progress, and we should not necessarily do this after weβve processed all records. Depending on our application, it can do this every N records or after weβve processed a batch of records."
},
{
"code": null,
"e": 22109,
"s": 21957,
"text": "Notice that the checkpoint method can throw an exception in case DynamoDB table does not exist or if we have two KCL records processing the same shard."
},
{
"code": null,
"e": 22282,
"s": 22109,
"text": "The last method that we need to implement is the shutdown. This method is the last chance for our processor to checkpoint its progress, and this is exactly what we do here:"
},
{
"code": null,
"e": 22805,
"s": 22282,
"text": "public void shutdown(ShutdownInput shutdownInput) { ShutdownReason reason = shutdownInput.getShutdownReason(); switch (reason) { // Re-sharding, no more records in current shard case TERMINATE: // Application shutdown case REQUESTED: checkpoint(shutdownInput.getCheckpointer(), lastProcessedRecord); break; // Processing will be moved to a different record processor case ZOMBIE: // No need to checkpoint break; }}"
},
{
"code": null,
"e": 22928,
"s": 22805,
"text": "The majority of work is done, but we also need to provide a factory object for KCL to create an instance of our processor:"
},
{
"code": null,
"e": 23093,
"s": 22928,
"text": "public class MetricsProcessorFactory implements IRecordProcessorFactory {public IRecordProcessor createProcessor() { return new MetricRecordsProcessor(); }}"
},
{
"code": null,
"e": 23266,
"s": 23093,
"text": "Now, when we have all the parts in place, all we need to do is to start a KCL worker. We will launch this code on as many machines as we need to process our Kinesis stream."
},
{
"code": null,
"e": 24020,
"s": 23266,
"text": "// Configuration for a worker instancefinal KinesisClientLibConfiguration config = new KinesisClientLibConfiguration( // Name of our application \"metrics-processor\", // Name of stream to process \"metrics-stream\", new DefaultAWSCredentialsProviderChain(), // Name of this KCL worker instance. Should be different for different processes/machines \"worker-1\");// Create a factory that knows how to create an instance of our records processorfinal IRecordProcessorFactory recordProcessorFactory = new MetricsProcessorFactory();// Create a KCL worker. We only need one per machinefinal Worker worker = new Worker.Builder() .config(config) .recordProcessorFactory(recordProcessorFactory) .build();// Start KCL workerworker.run();"
},
{
"code": null,
"e": 24202,
"s": 24020,
"text": "That is all we need to do to implement a distributed stream processing. KCL will launch a processor per Kinesis shard and will distribute load among multiple machines automatically."
},
{
"code": null,
"e": 24469,
"s": 24202,
"text": "Notice that KCL can launch additional threads. However, if you need more machines to process incoming records you need to take care of this yourself. If you use AWS, you can use auto-scaling groups to automatically add more machines if CPU utilization gets too high."
},
{
"code": null,
"e": 24764,
"s": 24469,
"text": "To make these concepts more practical, Iβve implemented a small GitHub project that shows how to use AWS Kinesis. You can look through the code and run working examples. It consists of several small applications that create AWS resources, produces streaming data, and read data from the stream."
},
{
"code": null,
"e": 25192,
"s": 24764,
"text": "That was a brief introduction to the field of stream processing. Modern stream processing systems are based on the append-only log data structure that allows building a data ingestion infrastructure. Stream processing systems allow producers to write new records to a log, and multiple consumers can read records from a log in parallel. Weβve also covered how to create a simple stream processing applications using AWS Kinesis"
},
{
"code": null,
"e": 25498,
"s": 25192,
"text": "This article just scratched the surface of the topic. It didnβt cover such interesting topics windows in stream, stream processing frameworks, a concept of time in streaming data, streaming SQL (sounds like an oxymoron, I know!), etc., and I hope to cover these and many other topics in upcoming articles."
},
{
"code": null,
"e": 25655,
"s": 25498,
"text": "Hi! My name is Ivan Mushketyk, I am an avid software engineer, Open Source contributor, blogger, and a course author for Pluralsight, Udacity, and Coursera."
}
] |
8085 program for Binary search - GeeksforGeeks
|
23 Aug, 2021
Prerequisite β Binary Search Problem β Write an assembly language program in the 8085 microprocessor to find a given number in the list of 10 numbers. If found store 1 in output, else store 2 in output. Also, store the number of iterations and the index of the element, if found.
Example: Let the list be as follows:
Test-1:
Input: 21H (at 3000H)
Output: 1 (success) in 3001H,
2 (index) in 3002H, and
3 (iteration number) in 3003H.
Test-2:
Input: 22H (at 3000H)
Output: 2 (failure) in 3001H,
X (don't care) in 3002H, and
4 (iteration before failure) in 3003H
Assumption β Assume data to compare it with is stored in 3000H, list of numbers is from 3010H to 3019H and results are stored as follows: number of iterations in 3003H, success/failure (1/2) in 3001H and index in 3002H
Algorithm β
Move 0 to Accumulator and store it in 3003H, to indicate number of iterations so far.Move 0 and 9 to L and H registers, respectively.Load the data to search for in Accumulator from 3000H and shift it to B register.Retrieve the number of iterations from 3003H, increase it by one and store back in 3003H.Move value of H register to Accumulator and compare with L register.If carry is generated, binary search is over so JUMP to step 20.Add value of L register to Accumulator and right rotate it.Store value of Accumulator in register C and force reset carry flag, if set.Load the start address of the array in D-E register pair.Add the value of accumulator to Register E and store the result in E.Move 0 to Accumulator and use the ADC command to add any possible carry generated due to previous addition and store it back in Register D.Load the value pointed to by D-E pair and compare with Register B. If carry is generated, JUMP to step 15 and if Zero flag is set, JUMP to step 17.Move value of Register C to Accumulator and decrement Accumulator.Move value of Accumulator to H and JUMP back to step 4.Move value of Register C to Accumulator and increment Accumulator.Move value of Accumulator to L and JUMP back to step 4.Move 1 to Accumulator ad store in 3001H to indicate success.Move value of Register C to Accumulator and store it in 3002H to save the index.JUMP to statement 21.Move 2 to Accumulator and store it in 3001H to indicate failure.End the program.
Move 0 to Accumulator and store it in 3003H, to indicate number of iterations so far.
Move 0 and 9 to L and H registers, respectively.
Load the data to search for in Accumulator from 3000H and shift it to B register.
Retrieve the number of iterations from 3003H, increase it by one and store back in 3003H.
Move value of H register to Accumulator and compare with L register.
If carry is generated, binary search is over so JUMP to step 20.
Add value of L register to Accumulator and right rotate it.
Store value of Accumulator in register C and force reset carry flag, if set.
Load the start address of the array in D-E register pair.
Add the value of accumulator to Register E and store the result in E.
Move 0 to Accumulator and use the ADC command to add any possible carry generated due to previous addition and store it back in Register D.
Load the value pointed to by D-E pair and compare with Register B. If carry is generated, JUMP to step 15 and if Zero flag is set, JUMP to step 17.
Move value of Register C to Accumulator and decrement Accumulator.
Move value of Accumulator to H and JUMP back to step 4.
Move value of Register C to Accumulator and increment Accumulator.
Move value of Accumulator to L and JUMP back to step 4.
Move 1 to Accumulator ad store in 3001H to indicate success.
Move value of Register C to Accumulator and store it in 3002H to save the index.
JUMP to statement 21.
Move 2 to Accumulator and store it in 3001H to indicate failure.
End the program.
Program β
Explanation β
We move value of higher and lower index (9 and 0 in this case) to H and L registers respectively in step 2Higher and lower indices are compared in step 5. On getting a carry, which indicates low>high, we jump to end of loop else go to step 6.In steps 7 and 8 we add value of H and L registers and right rotate it, which is equivalent to (high+low)/2 in order to find the index in say C languageIn step 10, we add the value of mid to start address of array so that it acts as an offset, similar to how *(arr+x) and arr[x] is identical in C.Step 11 ensures no overflow occurs.In step 12, we compare the value at mid index with the value to be searched. If itβs equal, we jump out of the loop and set the values appropriately.If they are not equal, step 12 branches appropriately to let us increment/decrement mid by 1 and move that value to L/H register, as necessary (just like high=mid-1 or low=mid+1 is done in C) and go back to start of loop, that is step 2.
We move value of higher and lower index (9 and 0 in this case) to H and L registers respectively in step 2
Higher and lower indices are compared in step 5. On getting a carry, which indicates low>high, we jump to end of loop else go to step 6.
In steps 7 and 8 we add value of H and L registers and right rotate it, which is equivalent to (high+low)/2 in order to find the index in say C language
In step 10, we add the value of mid to start address of array so that it acts as an offset, similar to how *(arr+x) and arr[x] is identical in C.
Step 11 ensures no overflow occurs.
In step 12, we compare the value at mid index with the value to be searched. If itβs equal, we jump out of the loop and set the values appropriately.
If they are not equal, step 12 branches appropriately to let us increment/decrement mid by 1 and move that value to L/H register, as necessary (just like high=mid-1 or low=mid+1 is done in C) and go back to start of loop, that is step 2.
Note β This approach will fail if the element to be searched is smaller than the smallest element in the array. In order to handle that, add an extra zero to the start of the loop and move values 10 and 1 to H-L pair in step 2, respectively.
kalrap615
microprocessor
system-programming
Technical Scripter 2018
Technical Scripter
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 24133,
"s": 24105,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 24414,
"s": 24133,
"text": "Prerequisite β Binary Search Problem β Write an assembly language program in the 8085 microprocessor to find a given number in the list of 10 numbers. If found store 1 in output, else store 2 in output. Also, store the number of iterations and the index of the element, if found. "
},
{
"code": null,
"e": 24452,
"s": 24414,
"text": "Example: Let the list be as follows: "
},
{
"code": null,
"e": 24698,
"s": 24452,
"text": "Test-1: \nInput: 21H (at 3000H)\nOutput: 1 (success) in 3001H,\n2 (index) in 3002H, and\n3 (iteration number) in 3003H.\n\nTest-2: \nInput: 22H (at 3000H)\nOutput: 2 (failure) in 3001H,\nX (don't care) in 3002H, and\n4 (iteration before failure) in 3003H "
},
{
"code": null,
"e": 24918,
"s": 24698,
"text": "Assumption β Assume data to compare it with is stored in 3000H, list of numbers is from 3010H to 3019H and results are stored as follows: number of iterations in 3003H, success/failure (1/2) in 3001H and index in 3002H "
},
{
"code": null,
"e": 24931,
"s": 24918,
"text": "Algorithm β "
},
{
"code": null,
"e": 26397,
"s": 24931,
"text": "Move 0 to Accumulator and store it in 3003H, to indicate number of iterations so far.Move 0 and 9 to L and H registers, respectively.Load the data to search for in Accumulator from 3000H and shift it to B register.Retrieve the number of iterations from 3003H, increase it by one and store back in 3003H.Move value of H register to Accumulator and compare with L register.If carry is generated, binary search is over so JUMP to step 20.Add value of L register to Accumulator and right rotate it.Store value of Accumulator in register C and force reset carry flag, if set.Load the start address of the array in D-E register pair.Add the value of accumulator to Register E and store the result in E.Move 0 to Accumulator and use the ADC command to add any possible carry generated due to previous addition and store it back in Register D.Load the value pointed to by D-E pair and compare with Register B. If carry is generated, JUMP to step 15 and if Zero flag is set, JUMP to step 17.Move value of Register C to Accumulator and decrement Accumulator.Move value of Accumulator to H and JUMP back to step 4.Move value of Register C to Accumulator and increment Accumulator.Move value of Accumulator to L and JUMP back to step 4.Move 1 to Accumulator ad store in 3001H to indicate success.Move value of Register C to Accumulator and store it in 3002H to save the index.JUMP to statement 21.Move 2 to Accumulator and store it in 3001H to indicate failure.End the program."
},
{
"code": null,
"e": 26483,
"s": 26397,
"text": "Move 0 to Accumulator and store it in 3003H, to indicate number of iterations so far."
},
{
"code": null,
"e": 26532,
"s": 26483,
"text": "Move 0 and 9 to L and H registers, respectively."
},
{
"code": null,
"e": 26614,
"s": 26532,
"text": "Load the data to search for in Accumulator from 3000H and shift it to B register."
},
{
"code": null,
"e": 26704,
"s": 26614,
"text": "Retrieve the number of iterations from 3003H, increase it by one and store back in 3003H."
},
{
"code": null,
"e": 26773,
"s": 26704,
"text": "Move value of H register to Accumulator and compare with L register."
},
{
"code": null,
"e": 26838,
"s": 26773,
"text": "If carry is generated, binary search is over so JUMP to step 20."
},
{
"code": null,
"e": 26898,
"s": 26838,
"text": "Add value of L register to Accumulator and right rotate it."
},
{
"code": null,
"e": 26975,
"s": 26898,
"text": "Store value of Accumulator in register C and force reset carry flag, if set."
},
{
"code": null,
"e": 27033,
"s": 26975,
"text": "Load the start address of the array in D-E register pair."
},
{
"code": null,
"e": 27103,
"s": 27033,
"text": "Add the value of accumulator to Register E and store the result in E."
},
{
"code": null,
"e": 27243,
"s": 27103,
"text": "Move 0 to Accumulator and use the ADC command to add any possible carry generated due to previous addition and store it back in Register D."
},
{
"code": null,
"e": 27391,
"s": 27243,
"text": "Load the value pointed to by D-E pair and compare with Register B. If carry is generated, JUMP to step 15 and if Zero flag is set, JUMP to step 17."
},
{
"code": null,
"e": 27458,
"s": 27391,
"text": "Move value of Register C to Accumulator and decrement Accumulator."
},
{
"code": null,
"e": 27514,
"s": 27458,
"text": "Move value of Accumulator to H and JUMP back to step 4."
},
{
"code": null,
"e": 27581,
"s": 27514,
"text": "Move value of Register C to Accumulator and increment Accumulator."
},
{
"code": null,
"e": 27637,
"s": 27581,
"text": "Move value of Accumulator to L and JUMP back to step 4."
},
{
"code": null,
"e": 27698,
"s": 27637,
"text": "Move 1 to Accumulator ad store in 3001H to indicate success."
},
{
"code": null,
"e": 27779,
"s": 27698,
"text": "Move value of Register C to Accumulator and store it in 3002H to save the index."
},
{
"code": null,
"e": 27801,
"s": 27779,
"text": "JUMP to statement 21."
},
{
"code": null,
"e": 27866,
"s": 27801,
"text": "Move 2 to Accumulator and store it in 3001H to indicate failure."
},
{
"code": null,
"e": 27883,
"s": 27866,
"text": "End the program."
},
{
"code": null,
"e": 27894,
"s": 27883,
"text": "Program β "
},
{
"code": null,
"e": 27910,
"s": 27894,
"text": "Explanation β "
},
{
"code": null,
"e": 28871,
"s": 27910,
"text": "We move value of higher and lower index (9 and 0 in this case) to H and L registers respectively in step 2Higher and lower indices are compared in step 5. On getting a carry, which indicates low>high, we jump to end of loop else go to step 6.In steps 7 and 8 we add value of H and L registers and right rotate it, which is equivalent to (high+low)/2 in order to find the index in say C languageIn step 10, we add the value of mid to start address of array so that it acts as an offset, similar to how *(arr+x) and arr[x] is identical in C.Step 11 ensures no overflow occurs.In step 12, we compare the value at mid index with the value to be searched. If itβs equal, we jump out of the loop and set the values appropriately.If they are not equal, step 12 branches appropriately to let us increment/decrement mid by 1 and move that value to L/H register, as necessary (just like high=mid-1 or low=mid+1 is done in C) and go back to start of loop, that is step 2."
},
{
"code": null,
"e": 28978,
"s": 28871,
"text": "We move value of higher and lower index (9 and 0 in this case) to H and L registers respectively in step 2"
},
{
"code": null,
"e": 29115,
"s": 28978,
"text": "Higher and lower indices are compared in step 5. On getting a carry, which indicates low>high, we jump to end of loop else go to step 6."
},
{
"code": null,
"e": 29268,
"s": 29115,
"text": "In steps 7 and 8 we add value of H and L registers and right rotate it, which is equivalent to (high+low)/2 in order to find the index in say C language"
},
{
"code": null,
"e": 29414,
"s": 29268,
"text": "In step 10, we add the value of mid to start address of array so that it acts as an offset, similar to how *(arr+x) and arr[x] is identical in C."
},
{
"code": null,
"e": 29450,
"s": 29414,
"text": "Step 11 ensures no overflow occurs."
},
{
"code": null,
"e": 29600,
"s": 29450,
"text": "In step 12, we compare the value at mid index with the value to be searched. If itβs equal, we jump out of the loop and set the values appropriately."
},
{
"code": null,
"e": 29838,
"s": 29600,
"text": "If they are not equal, step 12 branches appropriately to let us increment/decrement mid by 1 and move that value to L/H register, as necessary (just like high=mid-1 or low=mid+1 is done in C) and go back to start of loop, that is step 2."
},
{
"code": null,
"e": 30081,
"s": 29838,
"text": "Note β This approach will fail if the element to be searched is smaller than the smallest element in the array. In order to handle that, add an extra zero to the start of the loop and move values 10 and 1 to H-L pair in step 2, respectively. "
},
{
"code": null,
"e": 30091,
"s": 30081,
"text": "kalrap615"
},
{
"code": null,
"e": 30106,
"s": 30091,
"text": "microprocessor"
},
{
"code": null,
"e": 30125,
"s": 30106,
"text": "system-programming"
},
{
"code": null,
"e": 30149,
"s": 30125,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 30168,
"s": 30149,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30183,
"s": 30168,
"text": "microprocessor"
}
] |
ArrayList clear() Method in Java with Examples - GeeksforGeeks
|
23 Nov, 2021
The clear() method of ArrayList in Java is used to remove all the elements from a list. The list will be empty after this call returns so do whenever this operation has been performed all elements of the corresponding Arraylist will be deleted so it does it becomes an essential function for deleting elements in ArrayList from memory leading to optimization.
Syntax:
clear()
Return Type: It does not return any value as it removes all the elements in the list and makes it empty.
Tip: It does implement the following interfaces as follows: Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess
Example 1:
Java
// Java Program to Illustrate Working of clear() Method// of ArrayList class // Importing required classesimport java.util.ArrayList; // Main classpublic class GFG { // Main driiver method public static void main(String[] args) { // Creating an empty Integer ArrayList ArrayList<Integer> arr = new ArrayList<Integer>(4); // Adding elements to above ArrayList // using add() method arr.add(1); arr.add(2); arr.add(3); arr.add(4); // Printing the elements inside current ArrayList System.out.println("The list initially: " + arr); // Clearing off elements // using clear() method arr.clear(); // Displaying ArrayList elements // after using clear() method System.out.println( "The list after using clear() method: " + arr); }}
The list initially: [1, 2, 3, 4]
The list after using clear() method: []
Akanksha_Rai
solankimayank
Java - util package
Java-ArrayList
Java-Collections
Java-Functions
java-list
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
|
[
{
"code": null,
"e": 25033,
"s": 25005,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 25393,
"s": 25033,
"text": "The clear() method of ArrayList in Java is used to remove all the elements from a list. The list will be empty after this call returns so do whenever this operation has been performed all elements of the corresponding Arraylist will be deleted so it does it becomes an essential function for deleting elements in ArrayList from memory leading to optimization."
},
{
"code": null,
"e": 25402,
"s": 25393,
"text": "Syntax: "
},
{
"code": null,
"e": 25410,
"s": 25402,
"text": "clear()"
},
{
"code": null,
"e": 25516,
"s": 25410,
"text": "Return Type: It does not return any value as it removes all the elements in the list and makes it empty. "
},
{
"code": null,
"e": 25651,
"s": 25516,
"text": "Tip: It does implement the following interfaces as follows: Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess"
},
{
"code": null,
"e": 25662,
"s": 25651,
"text": "Example 1:"
},
{
"code": null,
"e": 25667,
"s": 25662,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Working of clear() Method// of ArrayList class // Importing required classesimport java.util.ArrayList; // Main classpublic class GFG { // Main driiver method public static void main(String[] args) { // Creating an empty Integer ArrayList ArrayList<Integer> arr = new ArrayList<Integer>(4); // Adding elements to above ArrayList // using add() method arr.add(1); arr.add(2); arr.add(3); arr.add(4); // Printing the elements inside current ArrayList System.out.println(\"The list initially: \" + arr); // Clearing off elements // using clear() method arr.clear(); // Displaying ArrayList elements // after using clear() method System.out.println( \"The list after using clear() method: \" + arr); }}",
"e": 26539,
"s": 25667,
"text": null
},
{
"code": null,
"e": 26612,
"s": 26539,
"text": "The list initially: [1, 2, 3, 4]\nThe list after using clear() method: []"
},
{
"code": null,
"e": 26627,
"s": 26614,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 26641,
"s": 26627,
"text": "solankimayank"
},
{
"code": null,
"e": 26661,
"s": 26641,
"text": "Java - util package"
},
{
"code": null,
"e": 26676,
"s": 26661,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 26693,
"s": 26676,
"text": "Java-Collections"
},
{
"code": null,
"e": 26708,
"s": 26693,
"text": "Java-Functions"
},
{
"code": null,
"e": 26718,
"s": 26708,
"text": "java-list"
},
{
"code": null,
"e": 26723,
"s": 26718,
"text": "Java"
},
{
"code": null,
"e": 26728,
"s": 26723,
"text": "Java"
},
{
"code": null,
"e": 26745,
"s": 26728,
"text": "Java-Collections"
},
{
"code": null,
"e": 26843,
"s": 26745,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26875,
"s": 26843,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26926,
"s": 26875,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26956,
"s": 26926,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26975,
"s": 26956,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26993,
"s": 26975,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27024,
"s": 26993,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27056,
"s": 27024,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27076,
"s": 27056,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27091,
"s": 27076,
"text": "Stream In Java"
}
] |
PHP - Hash hmac() Function
|
The hash_hmac() function is used to generate keyed hash value using HMAC method.
HMAC stands for keyed-hash message authentication code or hash-based message authentication code. It makes use of cryptographic hash function like md5, sha-256 and a secret key to return the message digest hash of the given data.
hash_hmac ( string $algo , string $data , string $key [, bool $raw_output = FALSE ] ) : string
algo
Name of the hashing algorithm. There is a big list of algorithm available with hash, some important ones are md5, sha256, etc.
To get the full list of algorithms supported check for hash_hmac_algos()
data
The data you want to hash.
key
Secret key to generate HMAC vaiant of the message digest.
raw_output
By default, the value is false and hence it returns lowercase hexits values. If the value is true, it will return raw binary data.
The hash_hmac() function returns a string containing calculated message digest that will be in the form of lowercase hexits if raw_output is false otherwise it will return raw binary data.
This function will work from PHP Version greater than 5.1.2.
Using hash_hmac() β
<?php
echo hash_hmac('md5', 'Welcome to Tutorialspoint', 'any_secretkey');
?>
This will produce the following result β
3e89ca31da24cb046c9d11706be688c1
Using hash_hmac() with ripemd128 algorithm β
<?php
echo hash_hmac('ripemd128', 'Welcome to Tutorialspoint', 'any_secretkey');
?>
This will produce the following result β
c9b5c68b72808f31b4524fbd46bf87d0
To generate hash_hmac with raw_output as true β
<?php
echo hash_hmac('ripemd128', 'Welcome to Tutorialspoint', 'any_secretkey', true);
?>
This will produce the following result β
Ι΅ΖrοΏ½οΏ½1οΏ½ROοΏ½FοΏ½οΏ½οΏ½
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2838,
"s": 2757,
"text": "The hash_hmac() function is used to generate keyed hash value using HMAC method."
},
{
"code": null,
"e": 3069,
"s": 2838,
"text": "HMAC stands for keyed-hash message authentication code or hash-based message authentication code. It makes use of cryptographic hash function like md5, sha-256 and a secret key to return the message digest hash of the given data."
},
{
"code": null,
"e": 3165,
"s": 3069,
"text": "hash_hmac ( string $algo , string $data , string $key [, bool $raw_output = FALSE ] ) : string\n"
},
{
"code": null,
"e": 3170,
"s": 3165,
"text": "algo"
},
{
"code": null,
"e": 3297,
"s": 3170,
"text": "Name of the hashing algorithm. There is a big list of algorithm available with hash, some important ones are md5, sha256, etc."
},
{
"code": null,
"e": 3370,
"s": 3297,
"text": "To get the full list of algorithms supported check for hash_hmac_algos()"
},
{
"code": null,
"e": 3375,
"s": 3370,
"text": "data"
},
{
"code": null,
"e": 3402,
"s": 3375,
"text": "The data you want to hash."
},
{
"code": null,
"e": 3406,
"s": 3402,
"text": "key"
},
{
"code": null,
"e": 3464,
"s": 3406,
"text": "Secret key to generate HMAC vaiant of the message digest."
},
{
"code": null,
"e": 3475,
"s": 3464,
"text": "raw_output"
},
{
"code": null,
"e": 3606,
"s": 3475,
"text": "By default, the value is false and hence it returns lowercase hexits values. If the value is true, it will return raw binary data."
},
{
"code": null,
"e": 3795,
"s": 3606,
"text": "The hash_hmac() function returns a string containing calculated message digest that will be in the form of lowercase hexits if raw_output is false otherwise it will return raw binary data."
},
{
"code": null,
"e": 3856,
"s": 3795,
"text": "This function will work from PHP Version greater than 5.1.2."
},
{
"code": null,
"e": 3876,
"s": 3856,
"text": "Using hash_hmac() β"
},
{
"code": null,
"e": 3957,
"s": 3876,
"text": "<?php\n echo hash_hmac('md5', 'Welcome to Tutorialspoint', 'any_secretkey');\n?>"
},
{
"code": null,
"e": 3998,
"s": 3957,
"text": "This will produce the following result β"
},
{
"code": null,
"e": 4032,
"s": 3998,
"text": "3e89ca31da24cb046c9d11706be688c1\n"
},
{
"code": null,
"e": 4077,
"s": 4032,
"text": "Using hash_hmac() with ripemd128 algorithm β"
},
{
"code": null,
"e": 4164,
"s": 4077,
"text": "<?php\n echo hash_hmac('ripemd128', 'Welcome to Tutorialspoint', 'any_secretkey');\n?>"
},
{
"code": null,
"e": 4205,
"s": 4164,
"text": "This will produce the following result β"
},
{
"code": null,
"e": 4239,
"s": 4205,
"text": "c9b5c68b72808f31b4524fbd46bf87d0\n"
},
{
"code": null,
"e": 4287,
"s": 4239,
"text": "To generate hash_hmac with raw_output as true β"
},
{
"code": null,
"e": 4380,
"s": 4287,
"text": "<?php\n echo hash_hmac('ripemd128', 'Welcome to Tutorialspoint', 'any_secretkey', true);\n?>"
},
{
"code": null,
"e": 4421,
"s": 4380,
"text": "This will produce the following result β"
},
{
"code": null,
"e": 4437,
"s": 4421,
"text": "Ι΅ΖrοΏ½οΏ½1οΏ½ROοΏ½FοΏ½οΏ½οΏ½\n"
},
{
"code": null,
"e": 4470,
"s": 4437,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 4486,
"s": 4470,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4519,
"s": 4486,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4530,
"s": 4519,
"text": " Syed Raza"
},
{
"code": null,
"e": 4565,
"s": 4530,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4582,
"s": 4565,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4615,
"s": 4582,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4630,
"s": 4615,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 4665,
"s": 4630,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 4677,
"s": 4665,
"text": " Azaz Patel"
},
{
"code": null,
"e": 4712,
"s": 4677,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4740,
"s": 4712,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 4747,
"s": 4740,
"text": " Print"
},
{
"code": null,
"e": 4758,
"s": 4747,
"text": " Add Notes"
}
] |
Setup MLflow in Production. MLflow is an open-source platform for... | by Sumeet Gyanchandani | Towards Data Science
|
This is the first article in my MLflow tutorial series:
Setup MLflow in Production (you are here!)MLflow: Basic logging functionsMLflow logging for TensorFlowMLflow ProjectsRetrieving the best model using Python API for MLflowServing a model using MLflow
Setup MLflow in Production (you are here!)
MLflow: Basic logging functions
MLflow logging for TensorFlow
MLflow Projects
Retrieving the best model using Python API for MLflow
Serving a model using MLflow
MLflow is an open-source platform for machine learning lifecycle management. Recently, I set up MLflow in production with a Postgres database as a Tracking Server and SFTP for the transfer of artifacts over the network. It took me about 2 weeks to get all the components right but this post would help you setup of MLflow in a production environment in about 10 minutes.
Anaconda
Tracking Server stores the metadata that you see in the MLflow UI. First, letβs create a new Conda environment:
conda create -n mlflow_envconda activate mlflow_env
Install the MLflow and PySFTP libraries:
conda install pythonpip install mlflowpip install pysftp
Our Tracking Server uses a Postgres database as a backend for storing the metadata. So letβs install PostgreSQL:
apt-get install postgresql postgresql-contrib postgresql-server-dev-all
Next, we will create the admin user and a database for the Tracking Server
sudo -u postgres psql
In the psql console:
CREATE DATABASE mlflow_db;CREATE USER mlflow_user WITH ENCRYPTED PASSWORD 'mlflow';GRANT ALL PRIVILEGES ON DATABASE mlflow_db TO mlflow_user;
As weβll need to interact with Postgres from Python, it is needed to install the psycopg2 library. However, to ensure a successful installation we need to install the GCC Linux package before:
sudo apt install gccpip install psycopg2-binary
If you would like to connect to the PostgreSQL Server remotely or would like to give its access to the users. You can
cd /var/lib/pgsql/data
Then add the following line at the end of the postgresql.conf file.
listen_addresses = '*'
You can then specify a remote IP from which you want to allow connection to the PostgreSQL Server, by adding the following line at the end of the pg_hba.conf file
host all all 10.10.10.187/32 trust
where 10.10.10.187/32 is the remote IP. To allow connection from any IP, use 0.0.0.0/0 instead. Then restart the PostgreSQL Server to apply the changes.
service postgresql restart
The next step is creating a directory for our Tracking Server to log the Machine Learning models and other artifacts. Remember that the Postgres database is only used for storing metadata regarding those models. This directory is called artifact URI.
mkdir ~/mlflow/mlruns
Create a logging directory.
mkdir ~/mlflow/mllogs
You can run the Tracking Server with the following command. But as soon as you do Ctrl-C or exit the terminal the server stops.
mlflow server --backend-store-uri postgresql://mlflow_user:mlflow@localhost/mlflow_db --default-artifact-root sftp://mlflow_user@<hostname_of_server>:~/mlflow/mlruns -h 0.0.0.0 -p 8000
If you want the Tracking server to be up and running after restarts and be resilient to failures, it is very useful to run it as a systemd service.
You need to go into the /etc/systemd/system directory and create a new file called mlflow-tracking.service with the following content:
[Unit]Description=MLflow Tracking ServerAfter=network.target[Service]Restart=on-failureRestartSec=30StandardOutput=file:/path_to_your_logging_folder/stdout.logStandardError=file:/path_to_your_logging_folder/stderr.logUser=rootExecStart=/bin/bash -c 'PATH=/path_to_your_conda_installation/envs/mlflow_env/bin/:$PATH exec mlflow server --backend-store-uri postgresql://mlflow_user:mlflow@localhost/mlflow_db --default-artifact-root sftp://mlflow_user@<hostname_of_server>:~/mlflow/mlruns -h 0.0.0.0 -p 8000'[Install]WantedBy=multi-user.target
Activate and enable the above service with the following commands:
sudo systemctl daemon-reloadsudo systemctl enable mlflow-trackingsudo systemctl start mlflow-tracking
Check that everything worked as expected with the following command:
sudo systemctl status mlflow-tracking
You should see an output similar to this:
Create user for the server named mlflow_user and make mlflow directory as the working directory for this user. Then create an ssh-key pair in the .ssh directory for the mlflow_user (/mlflow/.ssh in our case). Put the public key in the authorized_keys file and share the private key with the users.
Additionally, for the MLflow UI to be able to read the artifacts, copy the private key to /root/.ssh/ as well.
Next, we need to create the Host Key for the server manually using this command:
cd /root/.sshssh-keyscan -H <hostname_of_server> >> known_hosts
You can now restart the machine and the MLflow Tracking Server will be up and running after this restart.
In order to start tracking everything under the production Tracking Server, it is necessary to set the following environment variable in your .bashrc.
export MLFLOW_TRACKING_URI='http://<hostname_of_server>:8000'
Do not forget to source your .bashrc file!
. ~/.bashrc
Make sure you install pip packages for mlflow and pysftp in your environment (pysftp is required to facilitate the transfer of artifacts to the production server).
pip install mlflowpip install pysftp
To be able to authenticate the pysftp transfers, put the private key generated on the Production Server in the .ssh directory of your local machine . Then do
ssh <hostname_of_server>
When prompted to save <hostname_of_server> as a known host, answer yes.
You can access MLflow UI at http://<hostname_of_server>:8000
Run a sample machine learning model from the internet to check whether MLflow can track the runs.
mlflow run [email protected]:databricks/mlflow-example.git -P alpha=0.5
In the next post, Iβll speak about basic MLflow logging functions
[1] MLflow, Installing MLflow (2019), MLflow Documentation
|
[
{
"code": null,
"e": 227,
"s": 171,
"text": "This is the first article in my MLflow tutorial series:"
},
{
"code": null,
"e": 426,
"s": 227,
"text": "Setup MLflow in Production (you are here!)MLflow: Basic logging functionsMLflow logging for TensorFlowMLflow ProjectsRetrieving the best model using Python API for MLflowServing a model using MLflow"
},
{
"code": null,
"e": 469,
"s": 426,
"text": "Setup MLflow in Production (you are here!)"
},
{
"code": null,
"e": 501,
"s": 469,
"text": "MLflow: Basic logging functions"
},
{
"code": null,
"e": 531,
"s": 501,
"text": "MLflow logging for TensorFlow"
},
{
"code": null,
"e": 547,
"s": 531,
"text": "MLflow Projects"
},
{
"code": null,
"e": 601,
"s": 547,
"text": "Retrieving the best model using Python API for MLflow"
},
{
"code": null,
"e": 630,
"s": 601,
"text": "Serving a model using MLflow"
},
{
"code": null,
"e": 1001,
"s": 630,
"text": "MLflow is an open-source platform for machine learning lifecycle management. Recently, I set up MLflow in production with a Postgres database as a Tracking Server and SFTP for the transfer of artifacts over the network. It took me about 2 weeks to get all the components right but this post would help you setup of MLflow in a production environment in about 10 minutes."
},
{
"code": null,
"e": 1010,
"s": 1001,
"text": "Anaconda"
},
{
"code": null,
"e": 1122,
"s": 1010,
"text": "Tracking Server stores the metadata that you see in the MLflow UI. First, letβs create a new Conda environment:"
},
{
"code": null,
"e": 1174,
"s": 1122,
"text": "conda create -n mlflow_envconda activate mlflow_env"
},
{
"code": null,
"e": 1215,
"s": 1174,
"text": "Install the MLflow and PySFTP libraries:"
},
{
"code": null,
"e": 1272,
"s": 1215,
"text": "conda install pythonpip install mlflowpip install pysftp"
},
{
"code": null,
"e": 1385,
"s": 1272,
"text": "Our Tracking Server uses a Postgres database as a backend for storing the metadata. So letβs install PostgreSQL:"
},
{
"code": null,
"e": 1457,
"s": 1385,
"text": "apt-get install postgresql postgresql-contrib postgresql-server-dev-all"
},
{
"code": null,
"e": 1532,
"s": 1457,
"text": "Next, we will create the admin user and a database for the Tracking Server"
},
{
"code": null,
"e": 1554,
"s": 1532,
"text": "sudo -u postgres psql"
},
{
"code": null,
"e": 1575,
"s": 1554,
"text": "In the psql console:"
},
{
"code": null,
"e": 1717,
"s": 1575,
"text": "CREATE DATABASE mlflow_db;CREATE USER mlflow_user WITH ENCRYPTED PASSWORD 'mlflow';GRANT ALL PRIVILEGES ON DATABASE mlflow_db TO mlflow_user;"
},
{
"code": null,
"e": 1910,
"s": 1717,
"text": "As weβll need to interact with Postgres from Python, it is needed to install the psycopg2 library. However, to ensure a successful installation we need to install the GCC Linux package before:"
},
{
"code": null,
"e": 1958,
"s": 1910,
"text": "sudo apt install gccpip install psycopg2-binary"
},
{
"code": null,
"e": 2076,
"s": 1958,
"text": "If you would like to connect to the PostgreSQL Server remotely or would like to give its access to the users. You can"
},
{
"code": null,
"e": 2099,
"s": 2076,
"text": "cd /var/lib/pgsql/data"
},
{
"code": null,
"e": 2167,
"s": 2099,
"text": "Then add the following line at the end of the postgresql.conf file."
},
{
"code": null,
"e": 2190,
"s": 2167,
"text": "listen_addresses = '*'"
},
{
"code": null,
"e": 2353,
"s": 2190,
"text": "You can then specify a remote IP from which you want to allow connection to the PostgreSQL Server, by adding the following line at the end of the pg_hba.conf file"
},
{
"code": null,
"e": 2400,
"s": 2353,
"text": "host all all 10.10.10.187/32 trust"
},
{
"code": null,
"e": 2553,
"s": 2400,
"text": "where 10.10.10.187/32 is the remote IP. To allow connection from any IP, use 0.0.0.0/0 instead. Then restart the PostgreSQL Server to apply the changes."
},
{
"code": null,
"e": 2580,
"s": 2553,
"text": "service postgresql restart"
},
{
"code": null,
"e": 2831,
"s": 2580,
"text": "The next step is creating a directory for our Tracking Server to log the Machine Learning models and other artifacts. Remember that the Postgres database is only used for storing metadata regarding those models. This directory is called artifact URI."
},
{
"code": null,
"e": 2853,
"s": 2831,
"text": "mkdir ~/mlflow/mlruns"
},
{
"code": null,
"e": 2881,
"s": 2853,
"text": "Create a logging directory."
},
{
"code": null,
"e": 2903,
"s": 2881,
"text": "mkdir ~/mlflow/mllogs"
},
{
"code": null,
"e": 3031,
"s": 2903,
"text": "You can run the Tracking Server with the following command. But as soon as you do Ctrl-C or exit the terminal the server stops."
},
{
"code": null,
"e": 3216,
"s": 3031,
"text": "mlflow server --backend-store-uri postgresql://mlflow_user:mlflow@localhost/mlflow_db --default-artifact-root sftp://mlflow_user@<hostname_of_server>:~/mlflow/mlruns -h 0.0.0.0 -p 8000"
},
{
"code": null,
"e": 3364,
"s": 3216,
"text": "If you want the Tracking server to be up and running after restarts and be resilient to failures, it is very useful to run it as a systemd service."
},
{
"code": null,
"e": 3499,
"s": 3364,
"text": "You need to go into the /etc/systemd/system directory and create a new file called mlflow-tracking.service with the following content:"
},
{
"code": null,
"e": 4040,
"s": 3499,
"text": "[Unit]Description=MLflow Tracking ServerAfter=network.target[Service]Restart=on-failureRestartSec=30StandardOutput=file:/path_to_your_logging_folder/stdout.logStandardError=file:/path_to_your_logging_folder/stderr.logUser=rootExecStart=/bin/bash -c 'PATH=/path_to_your_conda_installation/envs/mlflow_env/bin/:$PATH exec mlflow server --backend-store-uri postgresql://mlflow_user:mlflow@localhost/mlflow_db --default-artifact-root sftp://mlflow_user@<hostname_of_server>:~/mlflow/mlruns -h 0.0.0.0 -p 8000'[Install]WantedBy=multi-user.target"
},
{
"code": null,
"e": 4107,
"s": 4040,
"text": "Activate and enable the above service with the following commands:"
},
{
"code": null,
"e": 4209,
"s": 4107,
"text": "sudo systemctl daemon-reloadsudo systemctl enable mlflow-trackingsudo systemctl start mlflow-tracking"
},
{
"code": null,
"e": 4278,
"s": 4209,
"text": "Check that everything worked as expected with the following command:"
},
{
"code": null,
"e": 4316,
"s": 4278,
"text": "sudo systemctl status mlflow-tracking"
},
{
"code": null,
"e": 4358,
"s": 4316,
"text": "You should see an output similar to this:"
},
{
"code": null,
"e": 4656,
"s": 4358,
"text": "Create user for the server named mlflow_user and make mlflow directory as the working directory for this user. Then create an ssh-key pair in the .ssh directory for the mlflow_user (/mlflow/.ssh in our case). Put the public key in the authorized_keys file and share the private key with the users."
},
{
"code": null,
"e": 4767,
"s": 4656,
"text": "Additionally, for the MLflow UI to be able to read the artifacts, copy the private key to /root/.ssh/ as well."
},
{
"code": null,
"e": 4848,
"s": 4767,
"text": "Next, we need to create the Host Key for the server manually using this command:"
},
{
"code": null,
"e": 4912,
"s": 4848,
"text": "cd /root/.sshssh-keyscan -H <hostname_of_server> >> known_hosts"
},
{
"code": null,
"e": 5018,
"s": 4912,
"text": "You can now restart the machine and the MLflow Tracking Server will be up and running after this restart."
},
{
"code": null,
"e": 5169,
"s": 5018,
"text": "In order to start tracking everything under the production Tracking Server, it is necessary to set the following environment variable in your .bashrc."
},
{
"code": null,
"e": 5231,
"s": 5169,
"text": "export MLFLOW_TRACKING_URI='http://<hostname_of_server>:8000'"
},
{
"code": null,
"e": 5274,
"s": 5231,
"text": "Do not forget to source your .bashrc file!"
},
{
"code": null,
"e": 5286,
"s": 5274,
"text": ". ~/.bashrc"
},
{
"code": null,
"e": 5450,
"s": 5286,
"text": "Make sure you install pip packages for mlflow and pysftp in your environment (pysftp is required to facilitate the transfer of artifacts to the production server)."
},
{
"code": null,
"e": 5487,
"s": 5450,
"text": "pip install mlflowpip install pysftp"
},
{
"code": null,
"e": 5645,
"s": 5487,
"text": "To be able to authenticate the pysftp transfers, put the private key generated on the Production Server in the .ssh directory of your local machine . Then do"
},
{
"code": null,
"e": 5670,
"s": 5645,
"text": "ssh <hostname_of_server>"
},
{
"code": null,
"e": 5742,
"s": 5670,
"text": "When prompted to save <hostname_of_server> as a known host, answer yes."
},
{
"code": null,
"e": 5803,
"s": 5742,
"text": "You can access MLflow UI at http://<hostname_of_server>:8000"
},
{
"code": null,
"e": 5901,
"s": 5803,
"text": "Run a sample machine learning model from the internet to check whether MLflow can track the runs."
},
{
"code": null,
"e": 5970,
"s": 5901,
"text": "mlflow run [email protected]:databricks/mlflow-example.git -P alpha=0.5"
},
{
"code": null,
"e": 6036,
"s": 5970,
"text": "In the next post, Iβll speak about basic MLflow logging functions"
}
] |
80 Python Interview Practice Questions | by Cornellius Yudha Wijaya | Towards Data Science
|
Many Data Aspirant started learning their Data Science journey with Python Programming Language. Why Python? because it was easy to follow and many companies use Python programming language these days. Moreover, Python is a multi-purpose language that not specific only for Data scientists; people also use Python for developer purposes.
When you applying for a position as a Data Scientist, many companies would need you to follow a job interview with the Python knowledge. In this case, I try to outline the Python Interview question I collected from many sources and my own. I try to select the question that most likely would be asked and what is important to know. Here they are.
1. What is Python?
Python is a programming language with objects, modules, threads, exceptions, and automatic memory management. Python is designed to be highly readable. It uses English keywords frequently whereas other languages use punctuation, and it has fewer syntactical constructions than other languages.
2. What are the benefits of using Python?
The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is open-source.
3. How is Python an interpreted language?
An interpreted language is any programming language that is not in machine-level code before runtime. Therefore, Python is an interpreted language.
4. How Python is interpreted?
Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.
5. How is memory managed in Python?
Memory in Python is managed by Python private heap space. All Python objects and data structures are located in a private heap. This private heap is taken care of by Python Interpreter itself, and a programmer doesnβt have access to this private heap.
Python memory manager takes care of the allocation of Python private heap space.
Memory for Python private heap space is made available by Pythonβs in-built garbage collector, which recycles and frees up all the unused memory.
6. What is pep 8?
PEP stands for Python Enhancement Proposal. It is a set of rules that specify how to format Python code for maximum readability.
7. How do you write comments in python?
Comments in Python start with a # character.
#Comment Example
8. How to comment on multiple lines in python?
Multi-line comments appear in more than one line. All the lines to be commented are to be prefixed by a #. You can also a very good shortcut method to comment on multiple lines. All you need to do is hold the ctrl key and left-click in every place wherever you want to include a # character and type a # just once. This will comment on all the lines where you introduced your cursor.
9. What are docstrings in Python?
Docstrings are not actually comments, but, they are documentation strings. These docstrings are within triple quotes. They are not assigned to any variable and therefore, at times, serve the purpose of comments as well.
""" This is Docstring exampleIt is useful for documentation purposes"""
10. Is indentation optional in Python?
Indentation in Python is compulsory and is part of its syntax.
All programming languages have some way of defining the scope and extent of the block of codes; in Python, it is indentation. Indentation provides better readability to the code, which is probably why Python has made it compulsory.
11. What is a function in Python?
A function is a block of code that is executed only when it is called. To define a Python function, the def keyword is used. If the function returning something, they need a return keyword.
def example(a): return a*2
12. What are local variables and global variables in Python?
Global Variables:
Variables declared outside a function or in global space are called global variables. These variables can be accessed by any function in the program.
Local Variables:
Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space.
#Example of Global Variablea = 1#Example of Local Variabledef sample(): #Local Variable a = 1
13. What is a lambda function?
An anonymous or unnamed function is known as a lambda function. This function can have any number of parameters but, can have just one statement. It is often used as a one-time function rather than a function that used repeatedly.
#Example of Lambda Functiontest = lambda x,y: x*yprint(test(2,4))
14. Why lambda forms in python does not have statements?
A lambda form in python does not have statements as it is used to make new function object and then return them at runtime.
15. What are the supported data types in Python?
Python has five standard data types β
Numbers (Integer and Float)
String
List
Tuple
Dictionary
16. What are indexes?
To access an element from ordered sequences, we simply use the index of the element, which is the position number of that particular element. The index usually starts from 0, i.e., the first element has index 0, the second has 1, and so on.
#Example usage of indexlist_ex = [1,2, 'Test']print(list_ex[0])
17. What are negative indexes and why are they used?
When we use the index to access elements from the end of a list, itβs called reverse indexing. In reverse indexing, the indexing of elements starts from the last element with the index number β1. The second last element has index ββ2β, and so on. These indexes used in reverse indexing are called negative indexes.
#Example usage of indexlist_ex = [1,2, 'Test']print(list_ex[-1])
18. What is a dictionary in Python?
Python dictionary is one of the supported data types in Python. It is an unordered collection of elements. The elements in dictionaries are stored as key-value pairs. Dictionaries are indexed by keys. The data type is presented by{} .
#Example of Dictionarydictionary = {'key' : 'value'}
19. How to access values in a dictionary?
You could access the values in a dictionary by indexing using the key. Indexing is presented by [] .
#Accessing Dictionarydictionary = {'key' : 'value'}print(dictionary['key'])
20. How do you get a list of all the keys in a dictionary?
In Dictionary, there is a keys() attribute we could use.
dictionary = {'key' : 'value', 'key1': : 'value1'}print(dictionary.keys())
21. What is the difference between list and tuple?
The difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed for e.g as a key for dictionaries. The list is defined using [] and tuple defined using () .
#Example of list and tuple#Listlist_ex = [1,2,'test']#List is mutablelist_ex[0] = 100#Tupletuple_ex = (1,2,'test)#Tuple is not mutabletuple_ex[0] = 100 #It would error
22. In Python what are iterators?
In Python, iterators are used to iterate a group of elements, containers like the list or string. By iteration, it means that it could be looped by using a statement.
23. What does [::-1} do?
[::-1] is used to reverse the order of any iterable object.
#Reverse examplestring = 'this is a string'print(string[::-1])
24. How can the ternary operators be used in python?
The Ternary operator is the operator that is used to show the conditional statements. This consists of true or false values with a statement that has to be evaluated for it.
#Ternary operators examplea = 1 #The true valuesif a < 1: print('Less')#If the previous condition haven't fulfilledelse: print('More')
25. How does break work?
The break statement allows loop termination when some condition is met and the control is transferred to the next statement.
#Break examplefor i in range(5): if i < 3: print(i) else: break
26. What is the purpose pass statement in python?
The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.
#Pass examplefor i in range(10): if i%2 == 0: print(i) else: pass
27. What is a map function in Python?
The map() function is a function that takes a function as an argument and then applies that function to all the elements of an iterable, passed to it as another argument. It would return a map object so we need to transform it to a list object.
#map function exampledef number_exponential(num): return num**2number_list = [2,3,4,5]print(list(map(number_exponential, number_list)))
28. What is a enumerate function in python?
The enumerate() method adds a counter to an iterable and returns it in a form of enumerate object. The object would consist of the counter and the iterable values.
#Enumerate exampleiter_example = ['test', 'test2', 'test3']for idx, val in enumerate(iter_example): print(idx) print(val)
29. What is Dict and List comprehensions are?
They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable. It is created by looping inside the Dictionary or List object.
#Dictionary comprehensiondict_comprehension = {key:val for key, val in emumerate('sample')}print(dict_comprehension)#List comprehensionlist_comprehension = [i for i in range(5)]print(list_comprehension)
30. What is slicing in Python?
Slicing is a mechanism to select a range of items from sequence types like list, tuple, strings, etc. This slicing is done by indexing method.
#Slicing examplelist_example = [1,2,3,4,'test','test2']print(list_example[1:4])
31. What are the purposes of not in the operator?Operators are special functions. They take one or more values and produce a corresponding result. not would return the inverse of the boolean value.
print(not 1 == 2)
32. What is the purpose of // in python?
It is a Floor Division operator, which is used for dividing two operands with the result showing only digits before the decimal point.
print(5//2)
33. How do you add a new value to a list object?
You can do it by using .append() attribute that list has. By passing any values to the .append() attribute, the new value would be placed at the end of the list sequence.
list_example = [1,2,3,4,5]list_example.append(6)print(list_example)
34. What is a shallow copy?
Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. It means when we copying an object to another variable, it would be connected.
#Example of shallow copylist_example = [1,2,3,4,5]another_list = list_exampleanother_list[0] = 100print(list_example)
35. What is a deep copy?
Deep copy is used to store the values that are already copied. The deep copy doesnβt copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. Contrast with a shallow copy, The changes made in the original copy wonβt affect any other copy that uses the object. It means they are not connected.
#Example of Deep copylist_example = [1,2,3,4,5]#Iniating Deep copy with .copy attributeanother_list = list_example.copy()another_list[0] = 100print(list_example)
36. How to create an empty class in Python?
An empty class is a class that does not have any code defined within its block. It can be created using the pass keyword. However, you can create objects of this class outside the class itself. In Python, the passcommand does nothing when its executed. itβs a null statement.
class sample: passtest=sample()test.name="test1"print(test.name)
37. What is self-keyword in Python?
Self-keyword is used as the first parameter of a function inside a class that represents the instance of the class. The object or the instance of the class is automatically passed to the method that it belongs to and is received in the βself-keyword.β Users can use another name for the first parameter of the function that catches the object of the class, but it is recommended to use βself-keywordβ as it is more of a Python convention.
38. Will the do-while loop work if you donβt end it with a semicolon?
This is a Trick question! Python does not support an intrinsic do-while loop. Secondly, to terminate do-while loops is a necessity for languages like C++.
39. How will you convert a list into a string?
In this case, we could use a .join() attribute from the string object. Here we passed the list object to the attribute.
list_example = ['apple', 'grape', 'orange']print(' '.join(list_example))
40. What is a membership operator?
It is an operator that can confirm if a value is a member in another object. The operators are βinβ and βnot inβ
#Example membership operatorsprint('me' in 'membership')print('mes' not in 'membership')
41. What is identity operators in Python?
Identity operators is an operator that tell us if two values have the same identity. The operators are βisβ and βis notβ.
#Example Identity operatorsprint(1 is '1')print(2 is not '2')
42. How do you take input in Python?
For taking input from the user, we could use the function input(). This function would take input from the user and return the input into a string object.
test = input('input a number: ')print(test)
43. What does the function zip() do?
It would return an iterator of tuples. It would form an n-pair of value from iterable passed on the function. The n is the number of iterable passed on the function.
#Zip function exampleprint(list(zip([1,2,3], ['apple', 'grape', 'orange'], ['x', 2, True])))for num, fruit, thing in zip([1,2,3], ['apple', 'grape', 'orange'], ['x', 2, True]): print(num) print(fruit) print(thing)
44. What is the difference if range() function takes one argument, two arguments, and three arguments?
When we pass only one argument, it takes it as the stop value. Here, the start value is 0, and the step value is +1. The iteration with a range would always stop 1 value before the stop value.
for i in range(5): print(i)
When we pass two arguments, the first one is the start value, and the second is the stop value.
for i in range(1,5): print(i)
Using three arguments, the first argument is the start value, the second is the stop value, and the third is the step value.
for i in range(1,10,2): print(i)
45. What is the best code you can write to swap two numbers?
You can perform the swab with a single line of code.
a = 1b = 2#Swab numbera, b = b, a
46. How can you declare multiple assignments in one line of code?
There are two ways to do this. First is by separately declare the variable in the same line.
a, b, c = 1,2,3
Another way is by declaring the variable in the same line with only one value.
a=b=c=1
47. How to break out of the Infinite loop?
You can do it by pressing Ctrl+C to interrupt the looping process.
48. What is the withstatement in Python?
The with statement in Python ensures that cleanup code is executed when working with unmanaged resources by encapsulating common preparation and cleanup tasks. It may be used to open a file, do something, and then automatically close the file at the end. It may be used to open a database connection, do some processing, then automatically close the connection to ensure resources are closed and available for others. with will cleanup the resources even if an exception is thrown.
#Example of with statementwith open('database.txt') as data: print(data)
49. In a try-except block, when is except block executed?
The try-except block is commonly used when we want something to execute when errors were raised. The except block is executed when the code in the try block has encountered an error.
a = (1,2,3)try: a[0] = 2except: print('There is an error')
50. Where will you use whilerather than for?
For simple repetitive looping and when we donβt need to iterate through a list of items- like database records and characters in a string.
51. What is a Python module?
Modules are independent Python scripts with the .py extension that can be reused in other Python codes or scripts using the import statement. A module can consist of functions, classes, and variables, or some runnable code. Modules not only help in keeping Python codes organized but also in making codes less complex and more efficient.
import #name of the module
52. What is PYTHONPATH?
It is an environment variable that is used when a module is imported. Whenever a module is imported, PYTHONPATH is also looked up to check for the existence of the imported modules in various directories. The interpreter uses it to determine which module to load.
53. Name the example of file-processing modes with Python?
We have the following modes:
Read-only mode(βrβ): Open a file for reading. It is the default mode.
Write-only mode(βwβ): Open a file for writing. If the file contains data, data would be lost. Another new file is created.
Read-Write mode(βrwβ): Open a file for reading, write mode. It means updating mode.
Append mode(βaβ): Open for writing, append to the end of the file, if the file exists.
54. What is pickling and unpickling?
Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using a dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.
import picklea = 1#Pickling processpickle.dump(a, open('file.sav', 'wb'))#Unpickling processfile = pickle.load(open('file.sav', 'rb'))
55. Is python NumPy array better than lists?
We use python NumPy array instead of a list because of the below three reasons:
Less MemoryFastConvenient
Less Memory
Fast
Convenient
56. How do you calculate percentiles with NumPy?
Percentiles is the position of the ordered number in a certain percentile. We can calculate the percentile with NumPy using the following code.
import numpy as npa = np.array([i for i in range(100)])p = np.percentile(a, 50) #Returns 50th percentile, e.g. medianprint(p)
57. How do you get the current working directory using Python?
Working with Python, you may need to read and write files from various directories. To find out which directory weβre presently working under, we can use the getcwd() method from the os module.
import osos.getcwd()
58. What do you see below? What would happen if we execute it?
a = '1'b = '2'c = '3's = a + β[β + b + β:β + c + β]βprint(s)
This is string concatenation. If even one of the variables isnβt a string, this would raise a TypeError. What would happen is that we get an output of the string concatenation.
59. How would you randomize the contents of a list in-place?
We can use the help of function shuffle() from the module random.
from random import shufflelist_example = [1,2,3,4,5,6,7,8]shuffle(list_example)
60. What is a cast in Python?
Casting is when we convert a variable value from one type to another. In Python, it could be done with functions such as list(),int(), float() or str() . An example is when you convert a string into an integer object.
a = '1'b = int(a)
61. Explain why are we getting an error here?
from numpy imprt stdevImportError Traceback (most recent call last)<ipython-input-26-685c12521ed4> in <module>----> 1 from numpy import stdevImportError: cannot import name 'stdev' from 'numpy'
In the above code, we try to import a non-exist function from the numpy module. That is why we getting an error.
62. How can you unsign or delete variables in Python?
We could use the del() function to remove or unsign a variable. This is considered a good practice to remove all the unnecessary variables when we are not using it.
a = 1del a
63. What is a pandas in Python?
pandas is a Python package providing fast, flexible, and expressive data structures designed to make working with βrelationalβ or βlabeledβ data both easy and intuitive. It aims to be the fundamental high-level building block for doing practical, real-world data analysis in Python.
64. What is the difference between append() and extend() methods?
Both append() and extend() methods are methods used to add elements at the end of a list.
append(element): Adds the given element at the end of the list
extend(another-list): Adds the elements of another list at the end of the list
65. How do you find the current version of Python?
We can find our Python current version by using sys.version.
import syssys.version
66. What does this mean: *args, **kwargs? And why would we use it?
We use *args when we arenβt sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we donβt know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments. The identifiers args and kwargs are optional, as you could change it to another name such as *example **another but it is better to just use the default name.
#Example of *argsdef sample(*args): print(args)sample('time', 1, True)#Example of **kwargsdef sample(**kwargs): print(kwargs)sample(a = 'time', b = 1)
67. What is help() and dir() functions in Python?
The help() function displays the documentation string and helps for its argument.
import numpyhelp(numpy.array)
The dir() function displays all the members of an object(any kind).
import numpydir(numpy.array)
68. What is the meaning of a single- and a double-underscore before an object name?
Single Underscore β Names, in a class, with a leading underscore are simply to indicate to other programmers that the attribute or method is intended to be private. However, nothing special is done with the name itself.
Double Underscore (Name Mangling) β Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where the class name is the current class name with a leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.
69. What is the output of this below query?
ss = βPython Programming!βprint(ss[5])
The answer is βnβ
70. Write a program in Python to produce a Star triangle.
def star_triangle(r): for x in range(r): print(' '*(r-x-1)+'*'*(2*x+1))star_triangle(7)
71. What is wrong with this following code?
counter = 0def increment(): counter += 1increment()
Python doesnβt have variable declarations, so it has to figure out the scope of variables itself. If there is an invitation to a variable inside a function, that variable is considered local. The counter variable above is a global variable and thus, the line of code above would raise an error.
72. How to split a string into a list?
We can use the .split() attribute from the string. It takes the separator as an argument and return list consisting of splitting results of the string based on the separator.
text = 'hello again world !'text.split(' ')
73. Write a program in Python to check if a sequence you input is a Palindrome.
a=input("enter the sequence: ")b=a[::-1]if a==b: print("palindrome")else: print("Not a Palindrome")
74. What is a generator?
Python generator produces a sequence of values to iterate on, often by using a function. We define a function using yieldthat used to yield a value one by one, and then use a for loop looping to iterate on it.
def squares(n): i=1 while(i<=n): yield i**2 i+=1for i in squares(7): print(i)
75. Write a program in Python to check if a number is prime.
a=int(input("enter a number")) if a>1: for x in range(2,a): if(a%x)==0: print("not prime") break else: print("Prime")else: print("not prime")
76. What is the purpose of the single underscore (β_β) variable in Python?
It is to hold the result of the last executed expression(/statement) in an interactive interpreter session. This precedent was set by the standard CPython interpreter, and other interpreters have followed this.
77. What are the types of inheritance in Python?
Python supports different types of inheritance, they are:
Single Inheritance
Multi-level Inheritance
Hierarchical Inheritance
Multiple Inheritance
78. What is tuple unpacking?
Tuple unpacking is a process of unpacking the values in the tuple and input it into a few different variables.
tup = (1,2,3)#Tuple unpacking processa,b,c = tup
79. When you exit Python, is all memory deallocated?
Exiting Python deallocates everything except:
Modules with circular references
Modules with circular references
2. Objects referenced from global namespaces
3. Parts of memory reserved by the C library
80. If a function does not have a return statement, is it valid?
A function that doesnβt return anything returns a None object. Not necessarily does the return keyword mark the end of a function; it merely ends it when present in the function. Normally, a block of code marks a function, and where it ends, the function body ends.
www.edureka.co
www.tutorialspoint.com
intellipaat.com
codingcompiler.com
data-flair.training
If you are not subscribed as a Medium Member, please consider subscribing through my referral.
|
[
{
"code": null,
"e": 510,
"s": 172,
"text": "Many Data Aspirant started learning their Data Science journey with Python Programming Language. Why Python? because it was easy to follow and many companies use Python programming language these days. Moreover, Python is a multi-purpose language that not specific only for Data scientists; people also use Python for developer purposes."
},
{
"code": null,
"e": 857,
"s": 510,
"text": "When you applying for a position as a Data Scientist, many companies would need you to follow a job interview with the Python knowledge. In this case, I try to outline the Python Interview question I collected from many sources and my own. I try to select the question that most likely would be asked and what is important to know. Here they are."
},
{
"code": null,
"e": 876,
"s": 857,
"text": "1. What is Python?"
},
{
"code": null,
"e": 1170,
"s": 876,
"text": "Python is a programming language with objects, modules, threads, exceptions, and automatic memory management. Python is designed to be highly readable. It uses English keywords frequently whereas other languages use punctuation, and it has fewer syntactical constructions than other languages."
},
{
"code": null,
"e": 1212,
"s": 1170,
"text": "2. What are the benefits of using Python?"
},
{
"code": null,
"e": 1337,
"s": 1212,
"text": "The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is open-source."
},
{
"code": null,
"e": 1379,
"s": 1337,
"text": "3. How is Python an interpreted language?"
},
{
"code": null,
"e": 1527,
"s": 1379,
"text": "An interpreted language is any programming language that is not in machine-level code before runtime. Therefore, Python is an interpreted language."
},
{
"code": null,
"e": 1557,
"s": 1527,
"text": "4. How Python is interpreted?"
},
{
"code": null,
"e": 1818,
"s": 1557,
"text": "Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed."
},
{
"code": null,
"e": 1854,
"s": 1818,
"text": "5. How is memory managed in Python?"
},
{
"code": null,
"e": 2106,
"s": 1854,
"text": "Memory in Python is managed by Python private heap space. All Python objects and data structures are located in a private heap. This private heap is taken care of by Python Interpreter itself, and a programmer doesnβt have access to this private heap."
},
{
"code": null,
"e": 2187,
"s": 2106,
"text": "Python memory manager takes care of the allocation of Python private heap space."
},
{
"code": null,
"e": 2333,
"s": 2187,
"text": "Memory for Python private heap space is made available by Pythonβs in-built garbage collector, which recycles and frees up all the unused memory."
},
{
"code": null,
"e": 2351,
"s": 2333,
"text": "6. What is pep 8?"
},
{
"code": null,
"e": 2480,
"s": 2351,
"text": "PEP stands for Python Enhancement Proposal. It is a set of rules that specify how to format Python code for maximum readability."
},
{
"code": null,
"e": 2520,
"s": 2480,
"text": "7. How do you write comments in python?"
},
{
"code": null,
"e": 2565,
"s": 2520,
"text": "Comments in Python start with a # character."
},
{
"code": null,
"e": 2582,
"s": 2565,
"text": "#Comment Example"
},
{
"code": null,
"e": 2629,
"s": 2582,
"text": "8. How to comment on multiple lines in python?"
},
{
"code": null,
"e": 3013,
"s": 2629,
"text": "Multi-line comments appear in more than one line. All the lines to be commented are to be prefixed by a #. You can also a very good shortcut method to comment on multiple lines. All you need to do is hold the ctrl key and left-click in every place wherever you want to include a # character and type a # just once. This will comment on all the lines where you introduced your cursor."
},
{
"code": null,
"e": 3047,
"s": 3013,
"text": "9. What are docstrings in Python?"
},
{
"code": null,
"e": 3267,
"s": 3047,
"text": "Docstrings are not actually comments, but, they are documentation strings. These docstrings are within triple quotes. They are not assigned to any variable and therefore, at times, serve the purpose of comments as well."
},
{
"code": null,
"e": 3339,
"s": 3267,
"text": "\"\"\" This is Docstring exampleIt is useful for documentation purposes\"\"\""
},
{
"code": null,
"e": 3378,
"s": 3339,
"text": "10. Is indentation optional in Python?"
},
{
"code": null,
"e": 3441,
"s": 3378,
"text": "Indentation in Python is compulsory and is part of its syntax."
},
{
"code": null,
"e": 3673,
"s": 3441,
"text": "All programming languages have some way of defining the scope and extent of the block of codes; in Python, it is indentation. Indentation provides better readability to the code, which is probably why Python has made it compulsory."
},
{
"code": null,
"e": 3707,
"s": 3673,
"text": "11. What is a function in Python?"
},
{
"code": null,
"e": 3897,
"s": 3707,
"text": "A function is a block of code that is executed only when it is called. To define a Python function, the def keyword is used. If the function returning something, they need a return keyword."
},
{
"code": null,
"e": 3926,
"s": 3897,
"text": "def example(a): return a*2"
},
{
"code": null,
"e": 3987,
"s": 3926,
"text": "12. What are local variables and global variables in Python?"
},
{
"code": null,
"e": 4005,
"s": 3987,
"text": "Global Variables:"
},
{
"code": null,
"e": 4155,
"s": 4005,
"text": "Variables declared outside a function or in global space are called global variables. These variables can be accessed by any function in the program."
},
{
"code": null,
"e": 4172,
"s": 4155,
"text": "Local Variables:"
},
{
"code": null,
"e": 4315,
"s": 4172,
"text": "Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space."
},
{
"code": null,
"e": 4413,
"s": 4315,
"text": "#Example of Global Variablea = 1#Example of Local Variabledef sample(): #Local Variable a = 1"
},
{
"code": null,
"e": 4444,
"s": 4413,
"text": "13. What is a lambda function?"
},
{
"code": null,
"e": 4675,
"s": 4444,
"text": "An anonymous or unnamed function is known as a lambda function. This function can have any number of parameters but, can have just one statement. It is often used as a one-time function rather than a function that used repeatedly."
},
{
"code": null,
"e": 4741,
"s": 4675,
"text": "#Example of Lambda Functiontest = lambda x,y: x*yprint(test(2,4))"
},
{
"code": null,
"e": 4798,
"s": 4741,
"text": "14. Why lambda forms in python does not have statements?"
},
{
"code": null,
"e": 4922,
"s": 4798,
"text": "A lambda form in python does not have statements as it is used to make new function object and then return them at runtime."
},
{
"code": null,
"e": 4971,
"s": 4922,
"text": "15. What are the supported data types in Python?"
},
{
"code": null,
"e": 5009,
"s": 4971,
"text": "Python has five standard data types β"
},
{
"code": null,
"e": 5037,
"s": 5009,
"text": "Numbers (Integer and Float)"
},
{
"code": null,
"e": 5044,
"s": 5037,
"text": "String"
},
{
"code": null,
"e": 5049,
"s": 5044,
"text": "List"
},
{
"code": null,
"e": 5055,
"s": 5049,
"text": "Tuple"
},
{
"code": null,
"e": 5066,
"s": 5055,
"text": "Dictionary"
},
{
"code": null,
"e": 5088,
"s": 5066,
"text": "16. What are indexes?"
},
{
"code": null,
"e": 5329,
"s": 5088,
"text": "To access an element from ordered sequences, we simply use the index of the element, which is the position number of that particular element. The index usually starts from 0, i.e., the first element has index 0, the second has 1, and so on."
},
{
"code": null,
"e": 5393,
"s": 5329,
"text": "#Example usage of indexlist_ex = [1,2, 'Test']print(list_ex[0])"
},
{
"code": null,
"e": 5446,
"s": 5393,
"text": "17. What are negative indexes and why are they used?"
},
{
"code": null,
"e": 5761,
"s": 5446,
"text": "When we use the index to access elements from the end of a list, itβs called reverse indexing. In reverse indexing, the indexing of elements starts from the last element with the index number β1. The second last element has index ββ2β, and so on. These indexes used in reverse indexing are called negative indexes."
},
{
"code": null,
"e": 5826,
"s": 5761,
"text": "#Example usage of indexlist_ex = [1,2, 'Test']print(list_ex[-1])"
},
{
"code": null,
"e": 5862,
"s": 5826,
"text": "18. What is a dictionary in Python?"
},
{
"code": null,
"e": 6097,
"s": 5862,
"text": "Python dictionary is one of the supported data types in Python. It is an unordered collection of elements. The elements in dictionaries are stored as key-value pairs. Dictionaries are indexed by keys. The data type is presented by{} ."
},
{
"code": null,
"e": 6150,
"s": 6097,
"text": "#Example of Dictionarydictionary = {'key' : 'value'}"
},
{
"code": null,
"e": 6192,
"s": 6150,
"text": "19. How to access values in a dictionary?"
},
{
"code": null,
"e": 6293,
"s": 6192,
"text": "You could access the values in a dictionary by indexing using the key. Indexing is presented by [] ."
},
{
"code": null,
"e": 6369,
"s": 6293,
"text": "#Accessing Dictionarydictionary = {'key' : 'value'}print(dictionary['key'])"
},
{
"code": null,
"e": 6428,
"s": 6369,
"text": "20. How do you get a list of all the keys in a dictionary?"
},
{
"code": null,
"e": 6485,
"s": 6428,
"text": "In Dictionary, there is a keys() attribute we could use."
},
{
"code": null,
"e": 6560,
"s": 6485,
"text": "dictionary = {'key' : 'value', 'key1': : 'value1'}print(dictionary.keys())"
},
{
"code": null,
"e": 6611,
"s": 6560,
"text": "21. What is the difference between list and tuple?"
},
{
"code": null,
"e": 6806,
"s": 6611,
"text": "The difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed for e.g as a key for dictionaries. The list is defined using [] and tuple defined using () ."
},
{
"code": null,
"e": 6974,
"s": 6806,
"text": "#Example of list and tuple#Listlist_ex = [1,2,'test']#List is mutablelist_ex[0] = 100#Tupletuple_ex = (1,2,'test)#Tuple is not mutabletuple_ex[0] = 100 #It would error"
},
{
"code": null,
"e": 7008,
"s": 6974,
"text": "22. In Python what are iterators?"
},
{
"code": null,
"e": 7175,
"s": 7008,
"text": "In Python, iterators are used to iterate a group of elements, containers like the list or string. By iteration, it means that it could be looped by using a statement."
},
{
"code": null,
"e": 7200,
"s": 7175,
"text": "23. What does [::-1} do?"
},
{
"code": null,
"e": 7260,
"s": 7200,
"text": "[::-1] is used to reverse the order of any iterable object."
},
{
"code": null,
"e": 7323,
"s": 7260,
"text": "#Reverse examplestring = 'this is a string'print(string[::-1])"
},
{
"code": null,
"e": 7376,
"s": 7323,
"text": "24. How can the ternary operators be used in python?"
},
{
"code": null,
"e": 7550,
"s": 7376,
"text": "The Ternary operator is the operator that is used to show the conditional statements. This consists of true or false values with a statement that has to be evaluated for it."
},
{
"code": null,
"e": 7689,
"s": 7550,
"text": "#Ternary operators examplea = 1 #The true valuesif a < 1: print('Less')#If the previous condition haven't fulfilledelse: print('More')"
},
{
"code": null,
"e": 7714,
"s": 7689,
"text": "25. How does break work?"
},
{
"code": null,
"e": 7839,
"s": 7714,
"text": "The break statement allows loop termination when some condition is met and the control is transferred to the next statement."
},
{
"code": null,
"e": 7917,
"s": 7839,
"text": "#Break examplefor i in range(5): if i < 3: print(i) else: break"
},
{
"code": null,
"e": 7967,
"s": 7917,
"text": "26. What is the purpose pass statement in python?"
},
{
"code": null,
"e": 8099,
"s": 7967,
"text": "The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute."
},
{
"code": null,
"e": 8179,
"s": 8099,
"text": "#Pass examplefor i in range(10): if i%2 == 0: print(i) else: pass"
},
{
"code": null,
"e": 8217,
"s": 8179,
"text": "27. What is a map function in Python?"
},
{
"code": null,
"e": 8462,
"s": 8217,
"text": "The map() function is a function that takes a function as an argument and then applies that function to all the elements of an iterable, passed to it as another argument. It would return a map object so we need to transform it to a list object."
},
{
"code": null,
"e": 8600,
"s": 8462,
"text": "#map function exampledef number_exponential(num): return num**2number_list = [2,3,4,5]print(list(map(number_exponential, number_list)))"
},
{
"code": null,
"e": 8644,
"s": 8600,
"text": "28. What is a enumerate function in python?"
},
{
"code": null,
"e": 8808,
"s": 8644,
"text": "The enumerate() method adds a counter to an iterable and returns it in a form of enumerate object. The object would consist of the counter and the iterable values."
},
{
"code": null,
"e": 8934,
"s": 8808,
"text": "#Enumerate exampleiter_example = ['test', 'test2', 'test3']for idx, val in enumerate(iter_example): print(idx) print(val)"
},
{
"code": null,
"e": 8980,
"s": 8934,
"text": "29. What is Dict and List comprehensions are?"
},
{
"code": null,
"e": 9146,
"s": 8980,
"text": "They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable. It is created by looping inside the Dictionary or List object."
},
{
"code": null,
"e": 9349,
"s": 9146,
"text": "#Dictionary comprehensiondict_comprehension = {key:val for key, val in emumerate('sample')}print(dict_comprehension)#List comprehensionlist_comprehension = [i for i in range(5)]print(list_comprehension)"
},
{
"code": null,
"e": 9380,
"s": 9349,
"text": "30. What is slicing in Python?"
},
{
"code": null,
"e": 9523,
"s": 9380,
"text": "Slicing is a mechanism to select a range of items from sequence types like list, tuple, strings, etc. This slicing is done by indexing method."
},
{
"code": null,
"e": 9603,
"s": 9523,
"text": "#Slicing examplelist_example = [1,2,3,4,'test','test2']print(list_example[1:4])"
},
{
"code": null,
"e": 9801,
"s": 9603,
"text": "31. What are the purposes of not in the operator?Operators are special functions. They take one or more values and produce a corresponding result. not would return the inverse of the boolean value."
},
{
"code": null,
"e": 9819,
"s": 9801,
"text": "print(not 1 == 2)"
},
{
"code": null,
"e": 9860,
"s": 9819,
"text": "32. What is the purpose of // in python?"
},
{
"code": null,
"e": 9995,
"s": 9860,
"text": "It is a Floor Division operator, which is used for dividing two operands with the result showing only digits before the decimal point."
},
{
"code": null,
"e": 10007,
"s": 9995,
"text": "print(5//2)"
},
{
"code": null,
"e": 10056,
"s": 10007,
"text": "33. How do you add a new value to a list object?"
},
{
"code": null,
"e": 10227,
"s": 10056,
"text": "You can do it by using .append() attribute that list has. By passing any values to the .append() attribute, the new value would be placed at the end of the list sequence."
},
{
"code": null,
"e": 10295,
"s": 10227,
"text": "list_example = [1,2,3,4,5]list_example.append(6)print(list_example)"
},
{
"code": null,
"e": 10323,
"s": 10295,
"text": "34. What is a shallow copy?"
},
{
"code": null,
"e": 10606,
"s": 10323,
"text": "Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. It means when we copying an object to another variable, it would be connected."
},
{
"code": null,
"e": 10724,
"s": 10606,
"text": "#Example of shallow copylist_example = [1,2,3,4,5]another_list = list_exampleanother_list[0] = 100print(list_example)"
},
{
"code": null,
"e": 10749,
"s": 10724,
"text": "35. What is a deep copy?"
},
{
"code": null,
"e": 11134,
"s": 10749,
"text": "Deep copy is used to store the values that are already copied. The deep copy doesnβt copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. Contrast with a shallow copy, The changes made in the original copy wonβt affect any other copy that uses the object. It means they are not connected."
},
{
"code": null,
"e": 11296,
"s": 11134,
"text": "#Example of Deep copylist_example = [1,2,3,4,5]#Iniating Deep copy with .copy attributeanother_list = list_example.copy()another_list[0] = 100print(list_example)"
},
{
"code": null,
"e": 11340,
"s": 11296,
"text": "36. How to create an empty class in Python?"
},
{
"code": null,
"e": 11616,
"s": 11340,
"text": "An empty class is a class that does not have any code defined within its block. It can be created using the pass keyword. However, you can create objects of this class outside the class itself. In Python, the passcommand does nothing when its executed. itβs a null statement."
},
{
"code": null,
"e": 11684,
"s": 11616,
"text": "class sample: passtest=sample()test.name=\"test1\"print(test.name)"
},
{
"code": null,
"e": 11720,
"s": 11684,
"text": "37. What is self-keyword in Python?"
},
{
"code": null,
"e": 12159,
"s": 11720,
"text": "Self-keyword is used as the first parameter of a function inside a class that represents the instance of the class. The object or the instance of the class is automatically passed to the method that it belongs to and is received in the βself-keyword.β Users can use another name for the first parameter of the function that catches the object of the class, but it is recommended to use βself-keywordβ as it is more of a Python convention."
},
{
"code": null,
"e": 12229,
"s": 12159,
"text": "38. Will the do-while loop work if you donβt end it with a semicolon?"
},
{
"code": null,
"e": 12384,
"s": 12229,
"text": "This is a Trick question! Python does not support an intrinsic do-while loop. Secondly, to terminate do-while loops is a necessity for languages like C++."
},
{
"code": null,
"e": 12431,
"s": 12384,
"text": "39. How will you convert a list into a string?"
},
{
"code": null,
"e": 12551,
"s": 12431,
"text": "In this case, we could use a .join() attribute from the string object. Here we passed the list object to the attribute."
},
{
"code": null,
"e": 12624,
"s": 12551,
"text": "list_example = ['apple', 'grape', 'orange']print(' '.join(list_example))"
},
{
"code": null,
"e": 12659,
"s": 12624,
"text": "40. What is a membership operator?"
},
{
"code": null,
"e": 12772,
"s": 12659,
"text": "It is an operator that can confirm if a value is a member in another object. The operators are βinβ and βnot inβ"
},
{
"code": null,
"e": 12861,
"s": 12772,
"text": "#Example membership operatorsprint('me' in 'membership')print('mes' not in 'membership')"
},
{
"code": null,
"e": 12903,
"s": 12861,
"text": "41. What is identity operators in Python?"
},
{
"code": null,
"e": 13025,
"s": 12903,
"text": "Identity operators is an operator that tell us if two values have the same identity. The operators are βisβ and βis notβ."
},
{
"code": null,
"e": 13087,
"s": 13025,
"text": "#Example Identity operatorsprint(1 is '1')print(2 is not '2')"
},
{
"code": null,
"e": 13124,
"s": 13087,
"text": "42. How do you take input in Python?"
},
{
"code": null,
"e": 13279,
"s": 13124,
"text": "For taking input from the user, we could use the function input(). This function would take input from the user and return the input into a string object."
},
{
"code": null,
"e": 13323,
"s": 13279,
"text": "test = input('input a number: ')print(test)"
},
{
"code": null,
"e": 13360,
"s": 13323,
"text": "43. What does the function zip() do?"
},
{
"code": null,
"e": 13526,
"s": 13360,
"text": "It would return an iterator of tuples. It would form an n-pair of value from iterable passed on the function. The n is the number of iterable passed on the function."
},
{
"code": null,
"e": 13749,
"s": 13526,
"text": "#Zip function exampleprint(list(zip([1,2,3], ['apple', 'grape', 'orange'], ['x', 2, True])))for num, fruit, thing in zip([1,2,3], ['apple', 'grape', 'orange'], ['x', 2, True]): print(num) print(fruit) print(thing)"
},
{
"code": null,
"e": 13852,
"s": 13749,
"text": "44. What is the difference if range() function takes one argument, two arguments, and three arguments?"
},
{
"code": null,
"e": 14045,
"s": 13852,
"text": "When we pass only one argument, it takes it as the stop value. Here, the start value is 0, and the step value is +1. The iteration with a range would always stop 1 value before the stop value."
},
{
"code": null,
"e": 14075,
"s": 14045,
"text": "for i in range(5): print(i)"
},
{
"code": null,
"e": 14171,
"s": 14075,
"text": "When we pass two arguments, the first one is the start value, and the second is the stop value."
},
{
"code": null,
"e": 14203,
"s": 14171,
"text": "for i in range(1,5): print(i)"
},
{
"code": null,
"e": 14328,
"s": 14203,
"text": "Using three arguments, the first argument is the start value, the second is the stop value, and the third is the step value."
},
{
"code": null,
"e": 14363,
"s": 14328,
"text": "for i in range(1,10,2): print(i)"
},
{
"code": null,
"e": 14424,
"s": 14363,
"text": "45. What is the best code you can write to swap two numbers?"
},
{
"code": null,
"e": 14477,
"s": 14424,
"text": "You can perform the swab with a single line of code."
},
{
"code": null,
"e": 14512,
"s": 14477,
"text": "a = 1b = 2#Swab numbera, b = b, a "
},
{
"code": null,
"e": 14578,
"s": 14512,
"text": "46. How can you declare multiple assignments in one line of code?"
},
{
"code": null,
"e": 14671,
"s": 14578,
"text": "There are two ways to do this. First is by separately declare the variable in the same line."
},
{
"code": null,
"e": 14688,
"s": 14671,
"text": "a, b, c = 1,2,3 "
},
{
"code": null,
"e": 14767,
"s": 14688,
"text": "Another way is by declaring the variable in the same line with only one value."
},
{
"code": null,
"e": 14775,
"s": 14767,
"text": "a=b=c=1"
},
{
"code": null,
"e": 14818,
"s": 14775,
"text": "47. How to break out of the Infinite loop?"
},
{
"code": null,
"e": 14885,
"s": 14818,
"text": "You can do it by pressing Ctrl+C to interrupt the looping process."
},
{
"code": null,
"e": 14926,
"s": 14885,
"text": "48. What is the withstatement in Python?"
},
{
"code": null,
"e": 15408,
"s": 14926,
"text": "The with statement in Python ensures that cleanup code is executed when working with unmanaged resources by encapsulating common preparation and cleanup tasks. It may be used to open a file, do something, and then automatically close the file at the end. It may be used to open a database connection, do some processing, then automatically close the connection to ensure resources are closed and available for others. with will cleanup the resources even if an exception is thrown."
},
{
"code": null,
"e": 15484,
"s": 15408,
"text": "#Example of with statementwith open('database.txt') as data: print(data)"
},
{
"code": null,
"e": 15542,
"s": 15484,
"text": "49. In a try-except block, when is except block executed?"
},
{
"code": null,
"e": 15725,
"s": 15542,
"text": "The try-except block is commonly used when we want something to execute when errors were raised. The except block is executed when the code in the try block has encountered an error."
},
{
"code": null,
"e": 15788,
"s": 15725,
"text": "a = (1,2,3)try: a[0] = 2except: print('There is an error')"
},
{
"code": null,
"e": 15833,
"s": 15788,
"text": "50. Where will you use whilerather than for?"
},
{
"code": null,
"e": 15972,
"s": 15833,
"text": "For simple repetitive looping and when we donβt need to iterate through a list of items- like database records and characters in a string."
},
{
"code": null,
"e": 16001,
"s": 15972,
"text": "51. What is a Python module?"
},
{
"code": null,
"e": 16339,
"s": 16001,
"text": "Modules are independent Python scripts with the .py extension that can be reused in other Python codes or scripts using the import statement. A module can consist of functions, classes, and variables, or some runnable code. Modules not only help in keeping Python codes organized but also in making codes less complex and more efficient."
},
{
"code": null,
"e": 16366,
"s": 16339,
"text": "import #name of the module"
},
{
"code": null,
"e": 16390,
"s": 16366,
"text": "52. What is PYTHONPATH?"
},
{
"code": null,
"e": 16654,
"s": 16390,
"text": "It is an environment variable that is used when a module is imported. Whenever a module is imported, PYTHONPATH is also looked up to check for the existence of the imported modules in various directories. The interpreter uses it to determine which module to load."
},
{
"code": null,
"e": 16713,
"s": 16654,
"text": "53. Name the example of file-processing modes with Python?"
},
{
"code": null,
"e": 16742,
"s": 16713,
"text": "We have the following modes:"
},
{
"code": null,
"e": 16812,
"s": 16742,
"text": "Read-only mode(βrβ): Open a file for reading. It is the default mode."
},
{
"code": null,
"e": 16935,
"s": 16812,
"text": "Write-only mode(βwβ): Open a file for writing. If the file contains data, data would be lost. Another new file is created."
},
{
"code": null,
"e": 17019,
"s": 16935,
"text": "Read-Write mode(βrwβ): Open a file for reading, write mode. It means updating mode."
},
{
"code": null,
"e": 17106,
"s": 17019,
"text": "Append mode(βaβ): Open for writing, append to the end of the file, if the file exists."
},
{
"code": null,
"e": 17143,
"s": 17106,
"text": "54. What is pickling and unpickling?"
},
{
"code": null,
"e": 17428,
"s": 17143,
"text": "Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using a dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling."
},
{
"code": null,
"e": 17563,
"s": 17428,
"text": "import picklea = 1#Pickling processpickle.dump(a, open('file.sav', 'wb'))#Unpickling processfile = pickle.load(open('file.sav', 'rb'))"
},
{
"code": null,
"e": 17608,
"s": 17563,
"text": "55. Is python NumPy array better than lists?"
},
{
"code": null,
"e": 17688,
"s": 17608,
"text": "We use python NumPy array instead of a list because of the below three reasons:"
},
{
"code": null,
"e": 17714,
"s": 17688,
"text": "Less MemoryFastConvenient"
},
{
"code": null,
"e": 17726,
"s": 17714,
"text": "Less Memory"
},
{
"code": null,
"e": 17731,
"s": 17726,
"text": "Fast"
},
{
"code": null,
"e": 17742,
"s": 17731,
"text": "Convenient"
},
{
"code": null,
"e": 17791,
"s": 17742,
"text": "56. How do you calculate percentiles with NumPy?"
},
{
"code": null,
"e": 17935,
"s": 17791,
"text": "Percentiles is the position of the ordered number in a certain percentile. We can calculate the percentile with NumPy using the following code."
},
{
"code": null,
"e": 18061,
"s": 17935,
"text": "import numpy as npa = np.array([i for i in range(100)])p = np.percentile(a, 50) #Returns 50th percentile, e.g. medianprint(p)"
},
{
"code": null,
"e": 18124,
"s": 18061,
"text": "57. How do you get the current working directory using Python?"
},
{
"code": null,
"e": 18318,
"s": 18124,
"text": "Working with Python, you may need to read and write files from various directories. To find out which directory weβre presently working under, we can use the getcwd() method from the os module."
},
{
"code": null,
"e": 18339,
"s": 18318,
"text": "import osos.getcwd()"
},
{
"code": null,
"e": 18402,
"s": 18339,
"text": "58. What do you see below? What would happen if we execute it?"
},
{
"code": null,
"e": 18463,
"s": 18402,
"text": "a = '1'b = '2'c = '3's = a + β[β + b + β:β + c + β]βprint(s)"
},
{
"code": null,
"e": 18640,
"s": 18463,
"text": "This is string concatenation. If even one of the variables isnβt a string, this would raise a TypeError. What would happen is that we get an output of the string concatenation."
},
{
"code": null,
"e": 18701,
"s": 18640,
"text": "59. How would you randomize the contents of a list in-place?"
},
{
"code": null,
"e": 18767,
"s": 18701,
"text": "We can use the help of function shuffle() from the module random."
},
{
"code": null,
"e": 18847,
"s": 18767,
"text": "from random import shufflelist_example = [1,2,3,4,5,6,7,8]shuffle(list_example)"
},
{
"code": null,
"e": 18877,
"s": 18847,
"text": "60. What is a cast in Python?"
},
{
"code": null,
"e": 19095,
"s": 18877,
"text": "Casting is when we convert a variable value from one type to another. In Python, it could be done with functions such as list(),int(), float() or str() . An example is when you convert a string into an integer object."
},
{
"code": null,
"e": 19113,
"s": 19095,
"text": "a = '1'b = int(a)"
},
{
"code": null,
"e": 19159,
"s": 19113,
"text": "61. Explain why are we getting an error here?"
},
{
"code": null,
"e": 19353,
"s": 19159,
"text": "from numpy imprt stdevImportError Traceback (most recent call last)<ipython-input-26-685c12521ed4> in <module>----> 1 from numpy import stdevImportError: cannot import name 'stdev' from 'numpy'"
},
{
"code": null,
"e": 19466,
"s": 19353,
"text": "In the above code, we try to import a non-exist function from the numpy module. That is why we getting an error."
},
{
"code": null,
"e": 19520,
"s": 19466,
"text": "62. How can you unsign or delete variables in Python?"
},
{
"code": null,
"e": 19685,
"s": 19520,
"text": "We could use the del() function to remove or unsign a variable. This is considered a good practice to remove all the unnecessary variables when we are not using it."
},
{
"code": null,
"e": 19696,
"s": 19685,
"text": "a = 1del a"
},
{
"code": null,
"e": 19728,
"s": 19696,
"text": "63. What is a pandas in Python?"
},
{
"code": null,
"e": 20011,
"s": 19728,
"text": "pandas is a Python package providing fast, flexible, and expressive data structures designed to make working with βrelationalβ or βlabeledβ data both easy and intuitive. It aims to be the fundamental high-level building block for doing practical, real-world data analysis in Python."
},
{
"code": null,
"e": 20077,
"s": 20011,
"text": "64. What is the difference between append() and extend() methods?"
},
{
"code": null,
"e": 20167,
"s": 20077,
"text": "Both append() and extend() methods are methods used to add elements at the end of a list."
},
{
"code": null,
"e": 20230,
"s": 20167,
"text": "append(element): Adds the given element at the end of the list"
},
{
"code": null,
"e": 20309,
"s": 20230,
"text": "extend(another-list): Adds the elements of another list at the end of the list"
},
{
"code": null,
"e": 20360,
"s": 20309,
"text": "65. How do you find the current version of Python?"
},
{
"code": null,
"e": 20421,
"s": 20360,
"text": "We can find our Python current version by using sys.version."
},
{
"code": null,
"e": 20443,
"s": 20421,
"text": "import syssys.version"
},
{
"code": null,
"e": 20510,
"s": 20443,
"text": "66. What does this mean: *args, **kwargs? And why would we use it?"
},
{
"code": null,
"e": 21000,
"s": 20510,
"text": "We use *args when we arenβt sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we donβt know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments. The identifiers args and kwargs are optional, as you could change it to another name such as *example **another but it is better to just use the default name."
},
{
"code": null,
"e": 21157,
"s": 21000,
"text": "#Example of *argsdef sample(*args): print(args)sample('time', 1, True)#Example of **kwargsdef sample(**kwargs): print(kwargs)sample(a = 'time', b = 1)"
},
{
"code": null,
"e": 21207,
"s": 21157,
"text": "67. What is help() and dir() functions in Python?"
},
{
"code": null,
"e": 21289,
"s": 21207,
"text": "The help() function displays the documentation string and helps for its argument."
},
{
"code": null,
"e": 21319,
"s": 21289,
"text": "import numpyhelp(numpy.array)"
},
{
"code": null,
"e": 21387,
"s": 21319,
"text": "The dir() function displays all the members of an object(any kind)."
},
{
"code": null,
"e": 21416,
"s": 21387,
"text": "import numpydir(numpy.array)"
},
{
"code": null,
"e": 21500,
"s": 21416,
"text": "68. What is the meaning of a single- and a double-underscore before an object name?"
},
{
"code": null,
"e": 21720,
"s": 21500,
"text": "Single Underscore β Names, in a class, with a leading underscore are simply to indicate to other programmers that the attribute or method is intended to be private. However, nothing special is done with the name itself."
},
{
"code": null,
"e": 22274,
"s": 21720,
"text": "Double Underscore (Name Mangling) β Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where the class name is the current class name with a leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes."
},
{
"code": null,
"e": 22318,
"s": 22274,
"text": "69. What is the output of this below query?"
},
{
"code": null,
"e": 22357,
"s": 22318,
"text": "ss = βPython Programming!βprint(ss[5])"
},
{
"code": null,
"e": 22375,
"s": 22357,
"text": "The answer is βnβ"
},
{
"code": null,
"e": 22433,
"s": 22375,
"text": "70. Write a program in Python to produce a Star triangle."
},
{
"code": null,
"e": 22528,
"s": 22433,
"text": "def star_triangle(r): for x in range(r): print(' '*(r-x-1)+'*'*(2*x+1))star_triangle(7)"
},
{
"code": null,
"e": 22572,
"s": 22528,
"text": "71. What is wrong with this following code?"
},
{
"code": null,
"e": 22626,
"s": 22572,
"text": "counter = 0def increment(): counter += 1increment()"
},
{
"code": null,
"e": 22921,
"s": 22626,
"text": "Python doesnβt have variable declarations, so it has to figure out the scope of variables itself. If there is an invitation to a variable inside a function, that variable is considered local. The counter variable above is a global variable and thus, the line of code above would raise an error."
},
{
"code": null,
"e": 22960,
"s": 22921,
"text": "72. How to split a string into a list?"
},
{
"code": null,
"e": 23135,
"s": 22960,
"text": "We can use the .split() attribute from the string. It takes the separator as an argument and return list consisting of splitting results of the string based on the separator."
},
{
"code": null,
"e": 23179,
"s": 23135,
"text": "text = 'hello again world !'text.split(' ')"
},
{
"code": null,
"e": 23259,
"s": 23179,
"text": "73. Write a program in Python to check if a sequence you input is a Palindrome."
},
{
"code": null,
"e": 23363,
"s": 23259,
"text": "a=input(\"enter the sequence: \")b=a[::-1]if a==b: print(\"palindrome\")else: print(\"Not a Palindrome\")"
},
{
"code": null,
"e": 23388,
"s": 23363,
"text": "74. What is a generator?"
},
{
"code": null,
"e": 23598,
"s": 23388,
"text": "Python generator produces a sequence of values to iterate on, often by using a function. We define a function using yieldthat used to yield a value one by one, and then use a for loop looping to iterate on it."
},
{
"code": null,
"e": 23699,
"s": 23598,
"text": "def squares(n): i=1 while(i<=n): yield i**2 i+=1for i in squares(7): print(i)"
},
{
"code": null,
"e": 23760,
"s": 23699,
"text": "75. Write a program in Python to check if a number is prime."
},
{
"code": null,
"e": 23951,
"s": 23760,
"text": "a=int(input(\"enter a number\")) if a>1: for x in range(2,a): if(a%x)==0: print(\"not prime\") break else: print(\"Prime\")else: print(\"not prime\")"
},
{
"code": null,
"e": 24026,
"s": 23951,
"text": "76. What is the purpose of the single underscore (β_β) variable in Python?"
},
{
"code": null,
"e": 24237,
"s": 24026,
"text": "It is to hold the result of the last executed expression(/statement) in an interactive interpreter session. This precedent was set by the standard CPython interpreter, and other interpreters have followed this."
},
{
"code": null,
"e": 24286,
"s": 24237,
"text": "77. What are the types of inheritance in Python?"
},
{
"code": null,
"e": 24344,
"s": 24286,
"text": "Python supports different types of inheritance, they are:"
},
{
"code": null,
"e": 24363,
"s": 24344,
"text": "Single Inheritance"
},
{
"code": null,
"e": 24387,
"s": 24363,
"text": "Multi-level Inheritance"
},
{
"code": null,
"e": 24412,
"s": 24387,
"text": "Hierarchical Inheritance"
},
{
"code": null,
"e": 24433,
"s": 24412,
"text": "Multiple Inheritance"
},
{
"code": null,
"e": 24462,
"s": 24433,
"text": "78. What is tuple unpacking?"
},
{
"code": null,
"e": 24573,
"s": 24462,
"text": "Tuple unpacking is a process of unpacking the values in the tuple and input it into a few different variables."
},
{
"code": null,
"e": 24622,
"s": 24573,
"text": "tup = (1,2,3)#Tuple unpacking processa,b,c = tup"
},
{
"code": null,
"e": 24675,
"s": 24622,
"text": "79. When you exit Python, is all memory deallocated?"
},
{
"code": null,
"e": 24721,
"s": 24675,
"text": "Exiting Python deallocates everything except:"
},
{
"code": null,
"e": 24754,
"s": 24721,
"text": "Modules with circular references"
},
{
"code": null,
"e": 24787,
"s": 24754,
"text": "Modules with circular references"
},
{
"code": null,
"e": 24832,
"s": 24787,
"text": "2. Objects referenced from global namespaces"
},
{
"code": null,
"e": 24877,
"s": 24832,
"text": "3. Parts of memory reserved by the C library"
},
{
"code": null,
"e": 24942,
"s": 24877,
"text": "80. If a function does not have a return statement, is it valid?"
},
{
"code": null,
"e": 25208,
"s": 24942,
"text": "A function that doesnβt return anything returns a None object. Not necessarily does the return keyword mark the end of a function; it merely ends it when present in the function. Normally, a block of code marks a function, and where it ends, the function body ends."
},
{
"code": null,
"e": 25223,
"s": 25208,
"text": "www.edureka.co"
},
{
"code": null,
"e": 25246,
"s": 25223,
"text": "www.tutorialspoint.com"
},
{
"code": null,
"e": 25262,
"s": 25246,
"text": "intellipaat.com"
},
{
"code": null,
"e": 25281,
"s": 25262,
"text": "codingcompiler.com"
},
{
"code": null,
"e": 25301,
"s": 25281,
"text": "data-flair.training"
}
] |
Floor in Binary Search Tree (BST) - GeeksforGeeks
|
19 Jul, 2021
Given a Binary Search Tree and a number x, find floor of x in the given BST.
Input : x = 14 and root of below tree
10
/ \
5 15
/ \
12 30
Output : 12
Input : x = 15 and root of below tree
10
/ \
5 15
/ \
12 30
Output : 15
A simple solution is to traverse the tree using (Inorder or Preorder or Postorder) and keep track of closest smaller or same element. Time complexity of this solution is O(n) where n is total number of Nodes in BST.We can efficiently find closest smaller or same element in O(h) time where h is height of BST. Algorithm to find the floor of a key in a binary search tree (BST):
1 Start at the root Node.
2 If root->data == key,
floor of the key is equal
to the root.
3 Else if root->data > key, then
floor of the key must lie in the
left subtree.
4 Else floor may lie in the right subtree
but only if there is a value lesser than
or equal to the key.If not, then root is
the key.
For finding ceil of BST you can refer to this article.
C++
Java
Python3
C#
Javascript
// C++ code to find floor of a key in BST#include <bits/stdc++.h>using namespace std; /*Structure of each Node in the tree*/struct Node { int data; Node *left, *right;}; /*This function is used to create andinitializes new Nodes*/Node* newNode(int key){ Node* temp = new Node; temp->left = temp->right = NULL; temp->data = key; return temp;} /* This function is used to insert new values in BST*/Node* insert(Node* root, int key){ if (!root) return newNode(key); if (key < root->data) root->left = insert(root->left, key); else root->right = insert(root->right, key); return root;} /*This function is used to find floor of a key*/int floor(Node* root, int key){ if (!root) return INT_MAX; /* If root->data is equal to key */ if (root->data == key) return root->data; /* If root->data is greater than the key */ if (root->data > key) return floor(root->left, key); /* Else, the floor may lie in right subtree or may be equal to the root*/ int floorValue = floor(root->right, key); return (floorValue <= key) ? floorValue : root->data;} int main(){ /* Let us create following BST 7 / \ 5 10 / \ / \ 3 6 8 12 */ Node* root = NULL; root = insert(root, 7); insert(root, 10); insert(root, 5); insert(root, 3); insert(root, 6); insert(root, 8); insert(root, 12); cout << floor(root, 9) << endl; return 0;}
// Java code to find floor of a key in BSTclass GfG { /*Structure of each Node in the tree*/ static class Node { int data; Node left, right; } /*This function is used to create andinitializes new Nodes*/ static Node newNode(int key) { Node temp = new Node(); temp.left = null; temp.right = null; temp.data = key; return temp; } /* This function is used to insertnew values in BST*/ static Node insert(Node root, int key) { if (root == null) return newNode(key); if (key < root.data) root.left = insert(root.left, key); else root.right = insert(root.right, key); return root; } /*This function is used to find floor of a key*/ static int floor(Node root, int key) { if (root == null) return Integer.MAX_VALUE; /* If root->data is equal to key */ if (root.data == key) return root.data; /* If root->data is greater than the key */ if (root.data > key) return floor(root.left, key); /* Else, the floor may lie in right subtree or may be equal to the root*/ int floorValue = floor(root.right, key); return (floorValue <= key) ? floorValue : root.data; } public static void main(String[] args) { /* Let us create following BST 7 / \ 5 10 / \ / \ 3 6 8 12 */ Node root = null; root = insert(root, 7); insert(root, 10); insert(root, 5); insert(root, 3); insert(root, 6); insert(root, 8); insert(root, 12); System.out.println(floor(root, 9)); }}
# Python3 code to find floor of a key in BSTINT_MAX = 2147483647 # Binary Tree Node""" A utility function to create anew BST node """class newNode: # Construct to create a newNode def __init__(self, data): self.data = data self.left = None self.right = None """ This function is used to insertnew values in BST"""def insert(root, key): if (not root): return newNode(key) if (key < root.data): root.left = insert(root.left, key) else: root.right = insert(root.right, key) return root """This function is used to find floor of a key"""def floor(root, key) : if (not root): return INT_MAX """ If root.data is equal to key """ if (root.data == key) : return root.data """ If root.data is greater than the key """ if (root.data > key) : return floor(root.left, key) """ Else, the floor may lie in right subtree or may be equal to the root""" floorValue = floor(root.right, key) return floorValue if (floorValue <= key) else root.data # Driver Codeif __name__ == '__main__': """ Let us create following BST 7 / \ 5 10 / \ / \ 3 6 8 12 """ root = None root = insert(root, 7) insert(root, 10) insert(root, 5) insert(root, 3) insert(root, 6) insert(root, 8) insert(root, 12) print(floor(root, 9)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
// C# code to find floor of a key in BSTusing System; class GfG { /*Structure of each Node in the tree*/ public class Node { public int data; public Node left, right; } /*This function is used to create andinitializes new Nodes*/ static Node newNode(int key) { Node temp = new Node(); temp.left = null; temp.right = null; temp.data = key; return temp; } /* This function is used to insertnew values in BST*/ static Node insert(Node root, int key) { if (root == null) return newNode(key); if (key < root.data) root.left = insert(root.left, key); else root.right = insert(root.right, key); return root; } /*This function is used to find floor of a key*/ static int floor(Node root, int key) { if (root == null) return int.MaxValue; /* If root->data is equal to key */ if (root.data == key) return root.data; /* If root->data is greater than the key */ if (root.data > key) return floor(root.left, key); /* Else, the floor may lie in right subtree or may be equal to the root*/ int floorValue = floor(root.right, key); return (floorValue <= key) ? floorValue : root.data; } // Driver code public static void Main(String[] args) { /* Let us create following BST 7 / \ 5 10 / \ / \ 3 6 8 12 */ Node root = null; root = insert(root, 7); insert(root, 10); insert(root, 5); insert(root, 3); insert(root, 6); insert(root, 8); insert(root, 12); Console.WriteLine(floor(root, 9)); }} // This code has been contributed by 29AjayKumar
<script>// Javascript code to find floor of a key in BST class Node{ constructor() { this.data=0; this.left=this.right=null; }} /*This function is used to create andinitializes new Nodes*/function newNode(key){ let temp = new Node(); temp.left = null; temp.right = null; temp.data = key; return temp;} /* This function is used to insertnew values in BST*/function insert(root,key){ if (root == null) return newNode(key); if (key < root.data) root.left = insert(root.left, key); else root.right = insert(root.right, key); return root;} /*This function is used to find floor of a key*/function floor(root,key){ if (root == null) return Number.MAX_VALUE; /* If root->data is equal to key */ if (root.data == key) return root.data; /* If root->data is greater than the key */ if (root.data > key) return floor(root.left, key); /* Else, the floor may lie in right subtree or may be equal to the root*/ let floorValue = floor(root.right, key); return (floorValue <= key) ? floorValue : root.data;} /* Let us create following BST 7 / \ 5 10 / \ / \ 3 6 8 12 */let root = null;root = insert(root, 7);insert(root, 10);insert(root, 5);insert(root, 3);insert(root, 6);insert(root, 8);insert(root, 12);document.write(floor(root, 9)); // This code is contributed by rag2127</script>
8
SHUBHAMSINGH10
prerna saini
29AjayKumar
mukulbindal170299
praveenkumargamisaharghat
rag2127
Binary Search Tree
Searching
Searching
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Red-Black Tree | Set 2 (Insert)
Inorder Successor in Binary Search Tree
Two nodes of a BST are swapped, correct the BST
Optimal Binary Search Tree | DP-24
Find k-th smallest element in BST (Order Statistics in BST)
Binary Search
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Given an array of size n and a number k, find all elements that appear more than n/k times
K'th Smallest/Largest Element in Unsorted Array | Set 1
|
[
{
"code": null,
"e": 24855,
"s": 24827,
"text": "\n19 Jul, 2021"
},
{
"code": null,
"e": 24933,
"s": 24855,
"text": "Given a Binary Search Tree and a number x, find floor of x in the given BST. "
},
{
"code": null,
"e": 25216,
"s": 24933,
"text": "Input : x = 14 and root of below tree\n 10\n / \\\n 5 15\n / \\\n 12 30\nOutput : 12\n\nInput : x = 15 and root of below tree\n 10\n / \\\n 5 15\n / \\\n 12 30\nOutput : 15 "
},
{
"code": null,
"e": 25598,
"s": 25218,
"text": "A simple solution is to traverse the tree using (Inorder or Preorder or Postorder) and keep track of closest smaller or same element. Time complexity of this solution is O(n) where n is total number of Nodes in BST.We can efficiently find closest smaller or same element in O(h) time where h is height of BST. Algorithm to find the floor of a key in a binary search tree (BST): "
},
{
"code": null,
"e": 25931,
"s": 25598,
"text": "1 Start at the root Node.\n2 If root->data == key, \n floor of the key is equal \n to the root.\n3 Else if root->data > key, then \n floor of the key must lie in the\n left subtree.\n4 Else floor may lie in the right subtree \n but only if there is a value lesser than \n or equal to the key.If not, then root is\n the key."
},
{
"code": null,
"e": 25988,
"s": 25931,
"text": "For finding ceil of BST you can refer to this article. "
},
{
"code": null,
"e": 25992,
"s": 25988,
"text": "C++"
},
{
"code": null,
"e": 25997,
"s": 25992,
"text": "Java"
},
{
"code": null,
"e": 26005,
"s": 25997,
"text": "Python3"
},
{
"code": null,
"e": 26008,
"s": 26005,
"text": "C#"
},
{
"code": null,
"e": 26019,
"s": 26008,
"text": "Javascript"
},
{
"code": "// C++ code to find floor of a key in BST#include <bits/stdc++.h>using namespace std; /*Structure of each Node in the tree*/struct Node { int data; Node *left, *right;}; /*This function is used to create andinitializes new Nodes*/Node* newNode(int key){ Node* temp = new Node; temp->left = temp->right = NULL; temp->data = key; return temp;} /* This function is used to insert new values in BST*/Node* insert(Node* root, int key){ if (!root) return newNode(key); if (key < root->data) root->left = insert(root->left, key); else root->right = insert(root->right, key); return root;} /*This function is used to find floor of a key*/int floor(Node* root, int key){ if (!root) return INT_MAX; /* If root->data is equal to key */ if (root->data == key) return root->data; /* If root->data is greater than the key */ if (root->data > key) return floor(root->left, key); /* Else, the floor may lie in right subtree or may be equal to the root*/ int floorValue = floor(root->right, key); return (floorValue <= key) ? floorValue : root->data;} int main(){ /* Let us create following BST 7 / \\ 5 10 / \\ / \\ 3 6 8 12 */ Node* root = NULL; root = insert(root, 7); insert(root, 10); insert(root, 5); insert(root, 3); insert(root, 6); insert(root, 8); insert(root, 12); cout << floor(root, 9) << endl; return 0;}",
"e": 27524,
"s": 26019,
"text": null
},
{
"code": "// Java code to find floor of a key in BSTclass GfG { /*Structure of each Node in the tree*/ static class Node { int data; Node left, right; } /*This function is used to create andinitializes new Nodes*/ static Node newNode(int key) { Node temp = new Node(); temp.left = null; temp.right = null; temp.data = key; return temp; } /* This function is used to insertnew values in BST*/ static Node insert(Node root, int key) { if (root == null) return newNode(key); if (key < root.data) root.left = insert(root.left, key); else root.right = insert(root.right, key); return root; } /*This function is used to find floor of a key*/ static int floor(Node root, int key) { if (root == null) return Integer.MAX_VALUE; /* If root->data is equal to key */ if (root.data == key) return root.data; /* If root->data is greater than the key */ if (root.data > key) return floor(root.left, key); /* Else, the floor may lie in right subtree or may be equal to the root*/ int floorValue = floor(root.right, key); return (floorValue <= key) ? floorValue : root.data; } public static void main(String[] args) { /* Let us create following BST 7 / \\ 5 10 / \\ / \\ 3 6 8 12 */ Node root = null; root = insert(root, 7); insert(root, 10); insert(root, 5); insert(root, 3); insert(root, 6); insert(root, 8); insert(root, 12); System.out.println(floor(root, 9)); }}",
"e": 29243,
"s": 27524,
"text": null
},
{
"code": "# Python3 code to find floor of a key in BSTINT_MAX = 2147483647 # Binary Tree Node\"\"\" A utility function to create anew BST node \"\"\"class newNode: # Construct to create a newNode def __init__(self, data): self.data = data self.left = None self.right = None \"\"\" This function is used to insertnew values in BST\"\"\"def insert(root, key): if (not root): return newNode(key) if (key < root.data): root.left = insert(root.left, key) else: root.right = insert(root.right, key) return root \"\"\"This function is used to find floor of a key\"\"\"def floor(root, key) : if (not root): return INT_MAX \"\"\" If root.data is equal to key \"\"\" if (root.data == key) : return root.data \"\"\" If root.data is greater than the key \"\"\" if (root.data > key) : return floor(root.left, key) \"\"\" Else, the floor may lie in right subtree or may be equal to the root\"\"\" floorValue = floor(root.right, key) return floorValue if (floorValue <= key) else root.data # Driver Codeif __name__ == '__main__': \"\"\" Let us create following BST 7 / \\ 5 10 / \\ / \\ 3 6 8 12 \"\"\" root = None root = insert(root, 7) insert(root, 10) insert(root, 5) insert(root, 3) insert(root, 6) insert(root, 8) insert(root, 12) print(floor(root, 9)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)",
"e": 30684,
"s": 29243,
"text": null
},
{
"code": "// C# code to find floor of a key in BSTusing System; class GfG { /*Structure of each Node in the tree*/ public class Node { public int data; public Node left, right; } /*This function is used to create andinitializes new Nodes*/ static Node newNode(int key) { Node temp = new Node(); temp.left = null; temp.right = null; temp.data = key; return temp; } /* This function is used to insertnew values in BST*/ static Node insert(Node root, int key) { if (root == null) return newNode(key); if (key < root.data) root.left = insert(root.left, key); else root.right = insert(root.right, key); return root; } /*This function is used to find floor of a key*/ static int floor(Node root, int key) { if (root == null) return int.MaxValue; /* If root->data is equal to key */ if (root.data == key) return root.data; /* If root->data is greater than the key */ if (root.data > key) return floor(root.left, key); /* Else, the floor may lie in right subtree or may be equal to the root*/ int floorValue = floor(root.right, key); return (floorValue <= key) ? floorValue : root.data; } // Driver code public static void Main(String[] args) { /* Let us create following BST 7 / \\ 5 10 / \\ / \\ 3 6 8 12 */ Node root = null; root = insert(root, 7); insert(root, 10); insert(root, 5); insert(root, 3); insert(root, 6); insert(root, 8); insert(root, 12); Console.WriteLine(floor(root, 9)); }} // This code has been contributed by 29AjayKumar",
"e": 32490,
"s": 30684,
"text": null
},
{
"code": "<script>// Javascript code to find floor of a key in BST class Node{ constructor() { this.data=0; this.left=this.right=null; }} /*This function is used to create andinitializes new Nodes*/function newNode(key){ let temp = new Node(); temp.left = null; temp.right = null; temp.data = key; return temp;} /* This function is used to insertnew values in BST*/function insert(root,key){ if (root == null) return newNode(key); if (key < root.data) root.left = insert(root.left, key); else root.right = insert(root.right, key); return root;} /*This function is used to find floor of a key*/function floor(root,key){ if (root == null) return Number.MAX_VALUE; /* If root->data is equal to key */ if (root.data == key) return root.data; /* If root->data is greater than the key */ if (root.data > key) return floor(root.left, key); /* Else, the floor may lie in right subtree or may be equal to the root*/ let floorValue = floor(root.right, key); return (floorValue <= key) ? floorValue : root.data;} /* Let us create following BST 7 / \\ 5 10 / \\ / \\ 3 6 8 12 */let root = null;root = insert(root, 7);insert(root, 10);insert(root, 5);insert(root, 3);insert(root, 6);insert(root, 8);insert(root, 12);document.write(floor(root, 9)); // This code is contributed by rag2127</script>",
"e": 34012,
"s": 32490,
"text": null
},
{
"code": null,
"e": 34014,
"s": 34012,
"text": "8"
},
{
"code": null,
"e": 34031,
"s": 34016,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 34044,
"s": 34031,
"text": "prerna saini"
},
{
"code": null,
"e": 34056,
"s": 34044,
"text": "29AjayKumar"
},
{
"code": null,
"e": 34074,
"s": 34056,
"text": "mukulbindal170299"
},
{
"code": null,
"e": 34100,
"s": 34074,
"text": "praveenkumargamisaharghat"
},
{
"code": null,
"e": 34108,
"s": 34100,
"text": "rag2127"
},
{
"code": null,
"e": 34127,
"s": 34108,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 34137,
"s": 34127,
"text": "Searching"
},
{
"code": null,
"e": 34147,
"s": 34137,
"text": "Searching"
},
{
"code": null,
"e": 34166,
"s": 34147,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 34264,
"s": 34166,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34273,
"s": 34264,
"text": "Comments"
},
{
"code": null,
"e": 34286,
"s": 34273,
"text": "Old Comments"
},
{
"code": null,
"e": 34318,
"s": 34286,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 34358,
"s": 34318,
"text": "Inorder Successor in Binary Search Tree"
},
{
"code": null,
"e": 34406,
"s": 34358,
"text": "Two nodes of a BST are swapped, correct the BST"
},
{
"code": null,
"e": 34441,
"s": 34406,
"text": "Optimal Binary Search Tree | DP-24"
},
{
"code": null,
"e": 34501,
"s": 34441,
"text": "Find k-th smallest element in BST (Order Statistics in BST)"
},
{
"code": null,
"e": 34515,
"s": 34501,
"text": "Binary Search"
},
{
"code": null,
"e": 34529,
"s": 34515,
"text": "Linear Search"
},
{
"code": null,
"e": 34597,
"s": 34529,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 34688,
"s": 34597,
"text": "Given an array of size n and a number k, find all elements that appear more than n/k times"
}
] |
Functions in MATLAB - GeeksforGeeks
|
16 Aug, 2021
Methods are also popularly known as functions. The main aim of the methods is to reuse the code. A method is a block of code which is invoked and executed when it is called by the user. It contains local workspace and independent of base workspace which belongs to command prompt. Letβs take a glance of method syntax.
Syntax:
function [y1, y2 ,y3 . . . . , yn] = functionName(arguments)
. . . . .
end
where, y1 . . . . yn are output variables.
MATLAB syntax is quite peculiar compared to other programming languages. We can return one or more values from a function. We can also pass one or more arguments/variables while calling a function. MATLAB functions must be defined in separate files and function name must match with the file name. Letβs also see the few more ways of defining a function as per the user needs.
Anonymous Functions
Sub Functions
Nested Functions
Private Functions
Now letβs dive into an example and understand how to define a basic function.
Example:
MATLAB
% A MATLAB program to illustrate% defining a function function result = adder(x, y, z) % This function adds the 3 input argumentsresult = x+y+z;end
The comment line that is written just after the function statement works as the help text. Save the above code as adder.m and observe the output by calling it from the command prompt.
Output:
Calling the user defined function
An Anonymous function is as an inline function with one output variable. It can contain multiple input and output arguments. A user canβt access/call an anonymous function from outside the file. User can define an anonymous function in the command prompt or within a script or function file.
Syntax:
output = @(arguments) expression
Parameters:
output = output to be returned
arguments = required inputs to be passed
expression = a single formula/logic to be
Example:
Output
In the above block of code, an anonymous function is defined and accessed in the command prompt itself.
Sub functions are the functions that are defined after a primary function. Every function must be defined in a file except anonymous functions. Sub functions are defined in the primary function file and these functions are not visible to any other functions except the primary and sub functions that are defined within the file. Unlike primary functions, sub-functions canβt be accessed from command prompt/another file.
Syntax:
function output = mainFunction(x)
. . . . . .
subFunction(y)
. . . . . .
end
function result = subFunction(y)
. . . . . .
end
Example:
MATLAB
% Printing the sum of two numbers% using sub functions % Primary Functionfunction result = adder(x,y)result = x+y; % Calling Sub functionprint(result);end % Sub functionfunction print(result)fprintf('The addition of given two number is %d',result);end
Save the above code with the primary function name adder.m and observe the output by calling it from the command prompt.
Output:
Adding Two Numbers
Unlike Sub functions, Nested functions are defined inside the primary functions. The scope of a nested function is within the file. One canβt access the nested function from outside the file. Primary functionβs workspace can be accessed by all the nested functions that are defined within the body of the primary function.
MATLAB
% A MATLAB program to illustrate nested functions % Primary Functionfunction result = adder(x,y)result = x+y; % Nested Functionfunction print(result)fprintf('The sum of two numbers added in the nested function %d',result);end % Calling Nested Functionprint(result);end
Save the above code with the primary file name adder.m and observe the output by calling the function.
Output:
Result
The name itself suggests that these functions are private and will only be visible to limited functions/files. These functions files are stored in a separate subfolder named private. Generally, we canβt access files that are not in the current path/folder. But this works for private functions. These functions reside in subfolder and accessible to the parent folder and private folder itself. Now letβs dive into some example to understand the concept better.
Example:
MATLAB
% A MATLAB program to illustrate% private functions % Adder Functionfunction result = adder(x,y)result = x+y; % Calling private functionprint(result);end
Save the above code as adder.m in separate folder and create one more folder called private.
MATLAB
% A MATLAB program to illustrate% private functions % private functionfunction print(result)fprintf('The sum of two numbers added in the nested function is %d',result);end
Save the above code as print.m and save it in the private folder.
MATLAB
% A MATLAB program to illustrate% private functions % Subtractor Functionfunction result = adder(x,y)result = x-y; % Calling private functionprint(result);end
Save the above code as subtractor.m and store it in outside of parent folder. Now letβs observe the output by accessing the above functions.
Output:
Calling private function from subtractor function
In the above case, you can observe the error when we try to access private functions from the location other than the parent folder.
Calling private function from adder function
The program compiled successfully and gave the output when we tried to access the private function from adder function which is stored in the parent folder. One must check the current file path while working on private functions.
varshagumber28
MATLAB
Advanced Computer Subject
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Copying Files to and from Docker Containers
Principal Component Analysis with Python
OpenCV - Overview
Fuzzy Logic | Introduction
Classifying data using Support Vector Machines(SVMs) in Python
Arrow operator -> in C/C++ with Examples
Modulo Operator (%) in C/C++ with Examples
Structures in C++
Differences between Procedural and Object Oriented Programming
Top 10 Programming Languages to Learn in 2022
|
[
{
"code": null,
"e": 23861,
"s": 23833,
"text": "\n16 Aug, 2021"
},
{
"code": null,
"e": 24180,
"s": 23861,
"text": "Methods are also popularly known as functions. The main aim of the methods is to reuse the code. A method is a block of code which is invoked and executed when it is called by the user. It contains local workspace and independent of base workspace which belongs to command prompt. Letβs take a glance of method syntax."
},
{
"code": null,
"e": 24188,
"s": 24180,
"text": "Syntax:"
},
{
"code": null,
"e": 24259,
"s": 24188,
"text": " function [y1, y2 ,y3 . . . . , yn] = functionName(arguments)"
},
{
"code": null,
"e": 24280,
"s": 24259,
"text": " . . . . . "
},
{
"code": null,
"e": 24293,
"s": 24280,
"text": " end"
},
{
"code": null,
"e": 24336,
"s": 24293,
"text": "where, y1 . . . . yn are output variables."
},
{
"code": null,
"e": 24713,
"s": 24336,
"text": "MATLAB syntax is quite peculiar compared to other programming languages. We can return one or more values from a function. We can also pass one or more arguments/variables while calling a function. MATLAB functions must be defined in separate files and function name must match with the file name. Letβs also see the few more ways of defining a function as per the user needs."
},
{
"code": null,
"e": 24733,
"s": 24713,
"text": "Anonymous Functions"
},
{
"code": null,
"e": 24747,
"s": 24733,
"text": "Sub Functions"
},
{
"code": null,
"e": 24764,
"s": 24747,
"text": "Nested Functions"
},
{
"code": null,
"e": 24782,
"s": 24764,
"text": "Private Functions"
},
{
"code": null,
"e": 24860,
"s": 24782,
"text": "Now letβs dive into an example and understand how to define a basic function."
},
{
"code": null,
"e": 24869,
"s": 24860,
"text": "Example:"
},
{
"code": null,
"e": 24876,
"s": 24869,
"text": "MATLAB"
},
{
"code": "% A MATLAB program to illustrate% defining a function function result = adder(x, y, z) % This function adds the 3 input argumentsresult = x+y+z;end",
"e": 25024,
"s": 24876,
"text": null
},
{
"code": null,
"e": 25208,
"s": 25024,
"text": "The comment line that is written just after the function statement works as the help text. Save the above code as adder.m and observe the output by calling it from the command prompt."
},
{
"code": null,
"e": 25216,
"s": 25208,
"text": "Output:"
},
{
"code": null,
"e": 25250,
"s": 25216,
"text": "Calling the user defined function"
},
{
"code": null,
"e": 25545,
"s": 25252,
"text": "An Anonymous function is as an inline function with one output variable. It can contain multiple input and output arguments. A user canβt access/call an anonymous function from outside the file. User can define an anonymous function in the command prompt or within a script or function file. "
},
{
"code": null,
"e": 25553,
"s": 25545,
"text": "Syntax:"
},
{
"code": null,
"e": 25595,
"s": 25553,
"text": " output = @(arguments) expression"
},
{
"code": null,
"e": 25607,
"s": 25595,
"text": "Parameters:"
},
{
"code": null,
"e": 25647,
"s": 25607,
"text": " output = output to be returned"
},
{
"code": null,
"e": 25696,
"s": 25647,
"text": " arguments = required inputs to be passed"
},
{
"code": null,
"e": 25747,
"s": 25696,
"text": " expression = a single formula/logic to be "
},
{
"code": null,
"e": 25756,
"s": 25747,
"text": "Example:"
},
{
"code": null,
"e": 25763,
"s": 25756,
"text": "Output"
},
{
"code": null,
"e": 25867,
"s": 25763,
"text": "In the above block of code, an anonymous function is defined and accessed in the command prompt itself."
},
{
"code": null,
"e": 26290,
"s": 25867,
"text": "Sub functions are the functions that are defined after a primary function. Every function must be defined in a file except anonymous functions. Sub functions are defined in the primary function file and these functions are not visible to any other functions except the primary and sub functions that are defined within the file. Unlike primary functions, sub-functions canβt be accessed from command prompt/another file. "
},
{
"code": null,
"e": 26298,
"s": 26290,
"text": "Syntax:"
},
{
"code": null,
"e": 26340,
"s": 26298,
"text": " function output = mainFunction(x)"
},
{
"code": null,
"e": 26360,
"s": 26340,
"text": " . . . . . ."
},
{
"code": null,
"e": 26383,
"s": 26360,
"text": " subFunction(y)"
},
{
"code": null,
"e": 26404,
"s": 26383,
"text": " . . . . . . "
},
{
"code": null,
"e": 26416,
"s": 26404,
"text": " end"
},
{
"code": null,
"e": 26456,
"s": 26416,
"text": " function result = subFunction(y)"
},
{
"code": null,
"e": 26475,
"s": 26456,
"text": " . . . . . ."
},
{
"code": null,
"e": 26486,
"s": 26475,
"text": " end "
},
{
"code": null,
"e": 26495,
"s": 26486,
"text": "Example:"
},
{
"code": null,
"e": 26502,
"s": 26495,
"text": "MATLAB"
},
{
"code": "% Printing the sum of two numbers% using sub functions % Primary Functionfunction result = adder(x,y)result = x+y; % Calling Sub functionprint(result);end % Sub functionfunction print(result)fprintf('The addition of given two number is %d',result);end",
"e": 26754,
"s": 26502,
"text": null
},
{
"code": null,
"e": 26879,
"s": 26758,
"text": "Save the above code with the primary function name adder.m and observe the output by calling it from the command prompt."
},
{
"code": null,
"e": 26889,
"s": 26881,
"text": "Output:"
},
{
"code": null,
"e": 26910,
"s": 26891,
"text": "Adding Two Numbers"
},
{
"code": null,
"e": 27235,
"s": 26912,
"text": "Unlike Sub functions, Nested functions are defined inside the primary functions. The scope of a nested function is within the file. One canβt access the nested function from outside the file. Primary functionβs workspace can be accessed by all the nested functions that are defined within the body of the primary function."
},
{
"code": null,
"e": 27244,
"s": 27237,
"text": "MATLAB"
},
{
"code": "% A MATLAB program to illustrate nested functions % Primary Functionfunction result = adder(x,y)result = x+y; % Nested Functionfunction print(result)fprintf('The sum of two numbers added in the nested function %d',result);end % Calling Nested Functionprint(result);end",
"e": 27513,
"s": 27244,
"text": null
},
{
"code": null,
"e": 27620,
"s": 27517,
"text": "Save the above code with the primary file name adder.m and observe the output by calling the function."
},
{
"code": null,
"e": 27630,
"s": 27622,
"text": "Output:"
},
{
"code": null,
"e": 27639,
"s": 27632,
"text": "Result"
},
{
"code": null,
"e": 28102,
"s": 27641,
"text": "The name itself suggests that these functions are private and will only be visible to limited functions/files. These functions files are stored in a separate subfolder named private. Generally, we canβt access files that are not in the current path/folder. But this works for private functions. These functions reside in subfolder and accessible to the parent folder and private folder itself. Now letβs dive into some example to understand the concept better."
},
{
"code": null,
"e": 28113,
"s": 28104,
"text": "Example:"
},
{
"code": null,
"e": 28122,
"s": 28115,
"text": "MATLAB"
},
{
"code": "% A MATLAB program to illustrate% private functions % Adder Functionfunction result = adder(x,y)result = x+y; % Calling private functionprint(result);end",
"e": 28276,
"s": 28122,
"text": null
},
{
"code": null,
"e": 28373,
"s": 28280,
"text": "Save the above code as adder.m in separate folder and create one more folder called private."
},
{
"code": null,
"e": 28382,
"s": 28375,
"text": "MATLAB"
},
{
"code": "% A MATLAB program to illustrate% private functions % private functionfunction print(result)fprintf('The sum of two numbers added in the nested function is %d',result);end",
"e": 28554,
"s": 28382,
"text": null
},
{
"code": null,
"e": 28624,
"s": 28558,
"text": "Save the above code as print.m and save it in the private folder."
},
{
"code": null,
"e": 28633,
"s": 28626,
"text": "MATLAB"
},
{
"code": "% A MATLAB program to illustrate% private functions % Subtractor Functionfunction result = adder(x,y)result = x-y; % Calling private functionprint(result);end",
"e": 28792,
"s": 28633,
"text": null
},
{
"code": null,
"e": 28937,
"s": 28796,
"text": "Save the above code as subtractor.m and store it in outside of parent folder. Now letβs observe the output by accessing the above functions."
},
{
"code": null,
"e": 28947,
"s": 28939,
"text": "Output:"
},
{
"code": null,
"e": 28999,
"s": 28949,
"text": "Calling private function from subtractor function"
},
{
"code": null,
"e": 29134,
"s": 29001,
"text": "In the above case, you can observe the error when we try to access private functions from the location other than the parent folder."
},
{
"code": null,
"e": 29181,
"s": 29136,
"text": "Calling private function from adder function"
},
{
"code": null,
"e": 29413,
"s": 29183,
"text": "The program compiled successfully and gave the output when we tried to access the private function from adder function which is stored in the parent folder. One must check the current file path while working on private functions."
},
{
"code": null,
"e": 29430,
"s": 29415,
"text": "varshagumber28"
},
{
"code": null,
"e": 29437,
"s": 29430,
"text": "MATLAB"
},
{
"code": null,
"e": 29463,
"s": 29437,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 29484,
"s": 29463,
"text": "Programming Language"
},
{
"code": null,
"e": 29582,
"s": 29484,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29591,
"s": 29582,
"text": "Comments"
},
{
"code": null,
"e": 29604,
"s": 29591,
"text": "Old Comments"
},
{
"code": null,
"e": 29648,
"s": 29604,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 29689,
"s": 29648,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 29707,
"s": 29689,
"text": "OpenCV - Overview"
},
{
"code": null,
"e": 29734,
"s": 29707,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 29797,
"s": 29734,
"text": "Classifying data using Support Vector Machines(SVMs) in Python"
},
{
"code": null,
"e": 29838,
"s": 29797,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 29881,
"s": 29838,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 29899,
"s": 29881,
"text": "Structures in C++"
},
{
"code": null,
"e": 29962,
"s": 29899,
"text": "Differences between Procedural and Object Oriented Programming"
}
] |
Ethical Hacking - SQL Injection
|
SQL injection is a set of SQL commands that are placed in a URL string or in data structures in order to retrieve a response that we want from the databases that are connected with the web applications. This type of attacks generally takes place on webpages developed using PHP or ASP.NET.
An SQL injection attack can be done with the following intentions β
To dump the whole database of a system,
To dump the whole database of a system,
To modify the content of the databases, or
To modify the content of the databases, or
To perform different queries that are not allowed by the application.
To perform different queries that are not allowed by the application.
This type of attack works when the applications donβt validate the inputs properly, before passing them to an SQL statement. Injections are normally placed put in address bars, search fields, or data fields.
The easiest way to detect if a web application is vulnerable to an SQL injection attack is to use the " β " character in a string and see if you get any error.
Letβs try to understand this concept using a few examples. As shown in the following screenshot, we have used a " β " character in the Name field.
Now, click the Login button. It should produce the following response β
It means that the βNameβ field is vulnerable to SQL injection.
We have this URL β http://10.10.10.101/mutillidae/index.php?page=site-footer-xssdiscussion.php
And we want to test the variable βpageβ but observe how we have injected a " β " character in the string URL.
When we press Enter, it will produce the following result which is with errors.
SQLMAP is one of the best tools available to detect SQL injections. It can be downloaded from http://sqlmap.org/
It comes pre-compiled in the Kali distribution. You can locate it at β Applications β Database Assessment β Sqlmap.
After opening SQLMAP, we go to the page that we have the SQL injection and then get the header request. From the header, we run the following command in SQL β
./sqlmap.py --headers="User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:25.0)
Gecko/20100101 Firefox/25.0" --cookie="security=low;
PHPSESSID=oikbs8qcic2omf5gnd09kihsm7" -u '
http://localhost/dvwa/vulnerabilities/sqli_blind/?id=1&Submit=Submit#' -
level=5 risk=3 -p id --suffix="-BR" -v3
The SQLMAP will test all the variables and the result will show that the parameter βidβ is vulnerable, as shown in the following screenshot.
SQLNinja is another SQL injection tool that is available in Kali distribution.
JSQL Injection is in Java and it makes automated SQL injections.
To prevent your web application from SQL injection attacks, you should keep the following points in mind β
Unchecked user-input to database should not be allowed to pass through the application GUI.
Unchecked user-input to database should not be allowed to pass through the application GUI.
Every variable that passes into the application should be sanitized and validated.
Every variable that passes into the application should be sanitized and validated.
The user input which is passed into the database should be quoted.
The user input which is passed into the database should be quoted.
36 Lectures
5 hours
Sharad Kumar
31 Lectures
3.5 hours
Abhilash Nelson
22 Lectures
3 hours
Blair Cook
74 Lectures
4.5 hours
199courses
75 Lectures
4.5 hours
199courses
148 Lectures
28.5 hours
Joseph Delgadillo
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2769,
"s": 2479,
"text": "SQL injection is a set of SQL commands that are placed in a URL string or in data structures in order to retrieve a response that we want from the databases that are connected with the web applications. This type of attacks generally takes place on webpages developed using PHP or ASP.NET."
},
{
"code": null,
"e": 2837,
"s": 2769,
"text": "An SQL injection attack can be done with the following intentions β"
},
{
"code": null,
"e": 2877,
"s": 2837,
"text": "To dump the whole database of a system,"
},
{
"code": null,
"e": 2917,
"s": 2877,
"text": "To dump the whole database of a system,"
},
{
"code": null,
"e": 2960,
"s": 2917,
"text": "To modify the content of the databases, or"
},
{
"code": null,
"e": 3003,
"s": 2960,
"text": "To modify the content of the databases, or"
},
{
"code": null,
"e": 3073,
"s": 3003,
"text": "To perform different queries that are not allowed by the application."
},
{
"code": null,
"e": 3143,
"s": 3073,
"text": "To perform different queries that are not allowed by the application."
},
{
"code": null,
"e": 3351,
"s": 3143,
"text": "This type of attack works when the applications donβt validate the inputs properly, before passing them to an SQL statement. Injections are normally placed put in address bars, search fields, or data fields."
},
{
"code": null,
"e": 3511,
"s": 3351,
"text": "The easiest way to detect if a web application is vulnerable to an SQL injection attack is to use the \" β \" character in a string and see if you get any error."
},
{
"code": null,
"e": 3658,
"s": 3511,
"text": "Letβs try to understand this concept using a few examples. As shown in the following screenshot, we have used a \" β \" character in the Name field."
},
{
"code": null,
"e": 3730,
"s": 3658,
"text": "Now, click the Login button. It should produce the following response β"
},
{
"code": null,
"e": 3793,
"s": 3730,
"text": "It means that the βNameβ field is vulnerable to SQL injection."
},
{
"code": null,
"e": 3888,
"s": 3793,
"text": "We have this URL β http://10.10.10.101/mutillidae/index.php?page=site-footer-xssdiscussion.php"
},
{
"code": null,
"e": 3998,
"s": 3888,
"text": "And we want to test the variable βpageβ but observe how we have injected a \" β \" character in the string URL."
},
{
"code": null,
"e": 4078,
"s": 3998,
"text": "When we press Enter, it will produce the following result which is with errors."
},
{
"code": null,
"e": 4191,
"s": 4078,
"text": "SQLMAP is one of the best tools available to detect SQL injections. It can be downloaded from http://sqlmap.org/"
},
{
"code": null,
"e": 4307,
"s": 4191,
"text": "It comes pre-compiled in the Kali distribution. You can locate it at β Applications β Database Assessment β Sqlmap."
},
{
"code": null,
"e": 4466,
"s": 4307,
"text": "After opening SQLMAP, we go to the page that we have the SQL injection and then get the header request. From the header, we run the following command in SQL β"
},
{
"code": null,
"e": 4759,
"s": 4466,
"text": "./sqlmap.py --headers=\"User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:25.0) \nGecko/20100101 Firefox/25.0\" --cookie=\"security=low;\nPHPSESSID=oikbs8qcic2omf5gnd09kihsm7\" -u '\nhttp://localhost/dvwa/vulnerabilities/sqli_blind/?id=1&Submit=Submit#' -\nlevel=5 risk=3 -p id --suffix=\"-BR\" -v3\n"
},
{
"code": null,
"e": 4900,
"s": 4759,
"text": "The SQLMAP will test all the variables and the result will show that the parameter βidβ is vulnerable, as shown in the following screenshot."
},
{
"code": null,
"e": 4979,
"s": 4900,
"text": "SQLNinja is another SQL injection tool that is available in Kali distribution."
},
{
"code": null,
"e": 5044,
"s": 4979,
"text": "JSQL Injection is in Java and it makes automated SQL injections."
},
{
"code": null,
"e": 5151,
"s": 5044,
"text": "To prevent your web application from SQL injection attacks, you should keep the following points in mind β"
},
{
"code": null,
"e": 5243,
"s": 5151,
"text": "Unchecked user-input to database should not be allowed to pass through the application GUI."
},
{
"code": null,
"e": 5335,
"s": 5243,
"text": "Unchecked user-input to database should not be allowed to pass through the application GUI."
},
{
"code": null,
"e": 5418,
"s": 5335,
"text": "Every variable that passes into the application should be sanitized and validated."
},
{
"code": null,
"e": 5501,
"s": 5418,
"text": "Every variable that passes into the application should be sanitized and validated."
},
{
"code": null,
"e": 5568,
"s": 5501,
"text": "The user input which is passed into the database should be quoted."
},
{
"code": null,
"e": 5635,
"s": 5568,
"text": "The user input which is passed into the database should be quoted."
},
{
"code": null,
"e": 5668,
"s": 5635,
"text": "\n 36 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5682,
"s": 5668,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 5717,
"s": 5682,
"text": "\n 31 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5734,
"s": 5717,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5767,
"s": 5734,
"text": "\n 22 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5779,
"s": 5767,
"text": " Blair Cook"
},
{
"code": null,
"e": 5814,
"s": 5779,
"text": "\n 74 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5826,
"s": 5814,
"text": " 199courses"
},
{
"code": null,
"e": 5861,
"s": 5826,
"text": "\n 75 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5873,
"s": 5861,
"text": " 199courses"
},
{
"code": null,
"e": 5910,
"s": 5873,
"text": "\n 148 Lectures \n 28.5 hours \n"
},
{
"code": null,
"e": 5929,
"s": 5910,
"text": " Joseph Delgadillo"
},
{
"code": null,
"e": 5936,
"s": 5929,
"text": " Print"
},
{
"code": null,
"e": 5947,
"s": 5936,
"text": " Add Notes"
}
] |
Adding CSP headers in Django Project - GeeksforGeeks
|
31 Dec, 2021
Website security has been an important factor while developing websites and web applications. Many frameworks come with their own security policies and developers also try to implement the utmost security policies while developing their applications. Still even after this much hard work hackers will find new ways to penetrate into our app, exploit our code to vulnerabilities. In this article, we are going to implement a security header often referred to as CSP headers to a Django application.
CSP: Content-Security-Policy is an HTTP response header that modern browsers use to enhance the security of the web page by allowing you to restrict how resources such as JavaScript, CSS, or pretty much anything that the browser loads.
HTTP header: HTTP headers let the client and the server pass additional information with an HTTP request or response like MIME type, request status code, cookie, and proxy information, and more
XSS: Also abbreviated as Cross Side Scripting, XSS attacks enable attackers to inject client-side scripts into web pages viewed by other users in simple words if exploited can change the look and behavior of the webpage
Django: Django is a python based web application framework used to build a variety of web apps
Content-Security-Policy is an HTTP response header that modern browsers use to enhance the security of the web page by allowing you to restrict how resources such as JavaScript, CSS, or pretty much anything that the browser loads are designed to prevent XSS attacks which enable attackers to inject client-side scripts into web pages viewed by other users in simple words if exploited can change look and behavior of webpage. It is also called the successor of X-Content-Security-Policy or X-Webkit-CSP headers. CSP can also be implemented using the meta tag.
Some CSP header terminology is
default-src: the default source to load everything
style-src: source to load styles
script-src: source to load javascript or generally scripts
img-src: source to load images
object-src: source to load media
report-to: URI to send reports for violating CSP
βselfβ: load from the same host
βunsafe-inlineβ: allow inline styles and scripts
βunsafe-evalβ: allows eval() and similar methods for creating code from strings
βnonceβ: a random string that should be unique per request
CSP works by blocking the execution of styles, scripts, and other things unless they are allowed in the policy. CSP doesnβt allow execution of inline scripts and styles which means we canβt use <script/> and <style/> tags for javascript and styling.
An example of CSP headers is
Content-Security-Policy: default-src 'self';
style-src: 'self' stakpath.bootstrapcdn.com;
script 'self' *.cloudflare.com;
img-src 'self' imgur.com;
In this CSP header, we are telling the browser that the default source for all the styles, scripts, images, objects should be the domain that is passed in the header, along with that we are also allowing stylesheet from stackpath.bootstrapcdn.com which is CDN for bootstrap styles. We are also allowing scripts to be loaded from all Cloudflare subdomains using wildcard subdomain and for images, the browser can allow loading from imgur.com. Apart from these if the webpage tries to load from other domains like twitter the browser will block the requests.
Django doesnβt come with CSP headers in its core but thanks to Mozilla, they have created a package Django-CSP to add CSP headers.
# installing django-csp
pip3 install django-csp
add CSP to middleware in our setting.py file of the Django project and then we will configure our headers
Python3
MIDDLEWARE = ( # ... 'csp.middleware.CSPMiddleware', # ...)
Go to the settings file of the Django project and add the following in the last or anywhere you want
Python3
# uri to report policy violations# uri to report policy violationsCSP_REPORT_URI = '<add your reporting uri>' # default source as selfCSP_DEFAULT_SRC = ("'self'", ) # style from our domain and bootstrapcdnCSP_STYLE_SRC = ("'self'", "stackpath.bootstrapcdn.com") # scripts from our domain and other domainsCSP_SCRIPT_SRC = ("'self'", "ajax.cloudflare.com", "static.cloudflareinsights.com", "www.google-analytics.com", "ssl.google-analytics.com", "cdn.ampproject.org", "www.googletagservices.com", "pagead2.googlesyndication.com") # images from our domain and other domainsCSP_IMG_SRC = ("'self'", "www.google-analytics.com", "raw.githubusercontent.com", "googleads.g.doubleclick.net") # loading manifest, workers, frames, etcCSP_FONT_SRC = ("'self'", )CSP_CONNECT_SRC = ("'self'", "www.google-analytics.com" )CSP_OBJECT_SRC = ("'self'", )CSP_BASE_URI = ("'self'", )CSP_FRAME_ANCESTORS = ("'self'", )CSP_FORM_ACTION = ("'self'", )CSP_INCLUDE_NONCE_IN = ('script-src', )CSP_MANIFEST_SRC = ("'self'", )CSP_WORKER_SRC = ("'self'", )CSP_MEDIA_SRC = ("'self'", )
You can add the required hostname according to your needs
Here are some instructions to perfectly implement CSP in your web apps
Try to avoid adding unnecessary hostnames
Check as many times as possible while adding or removing hostnames
Until absolutely necessary donβt add βunsafe-inlineβ, it will weaken our security policy
Try to avoid inline style and scripts
It is better not to use CSP in the development server right from the start
Always try to use HTTPS while loading scripts, styles, images.
sagar0719kumar
kalrap615
ddeevviissaavviittaa
Python Django
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n31 Dec, 2021"
},
{
"code": null,
"e": 24790,
"s": 24292,
"text": "Website security has been an important factor while developing websites and web applications. Many frameworks come with their own security policies and developers also try to implement the utmost security policies while developing their applications. Still even after this much hard work hackers will find new ways to penetrate into our app, exploit our code to vulnerabilities. In this article, we are going to implement a security header often referred to as CSP headers to a Django application."
},
{
"code": null,
"e": 25026,
"s": 24790,
"text": "CSP: Content-Security-Policy is an HTTP response header that modern browsers use to enhance the security of the web page by allowing you to restrict how resources such as JavaScript, CSS, or pretty much anything that the browser loads."
},
{
"code": null,
"e": 25220,
"s": 25026,
"text": "HTTP header: HTTP headers let the client and the server pass additional information with an HTTP request or response like MIME type, request status code, cookie, and proxy information, and more"
},
{
"code": null,
"e": 25440,
"s": 25220,
"text": "XSS: Also abbreviated as Cross Side Scripting, XSS attacks enable attackers to inject client-side scripts into web pages viewed by other users in simple words if exploited can change the look and behavior of the webpage"
},
{
"code": null,
"e": 25535,
"s": 25440,
"text": "Django: Django is a python based web application framework used to build a variety of web apps"
},
{
"code": null,
"e": 26095,
"s": 25535,
"text": "Content-Security-Policy is an HTTP response header that modern browsers use to enhance the security of the web page by allowing you to restrict how resources such as JavaScript, CSS, or pretty much anything that the browser loads are designed to prevent XSS attacks which enable attackers to inject client-side scripts into web pages viewed by other users in simple words if exploited can change look and behavior of webpage. It is also called the successor of X-Content-Security-Policy or X-Webkit-CSP headers. CSP can also be implemented using the meta tag."
},
{
"code": null,
"e": 26126,
"s": 26095,
"text": "Some CSP header terminology is"
},
{
"code": null,
"e": 26177,
"s": 26126,
"text": "default-src: the default source to load everything"
},
{
"code": null,
"e": 26210,
"s": 26177,
"text": "style-src: source to load styles"
},
{
"code": null,
"e": 26269,
"s": 26210,
"text": "script-src: source to load javascript or generally scripts"
},
{
"code": null,
"e": 26300,
"s": 26269,
"text": "img-src: source to load images"
},
{
"code": null,
"e": 26333,
"s": 26300,
"text": "object-src: source to load media"
},
{
"code": null,
"e": 26382,
"s": 26333,
"text": "report-to: URI to send reports for violating CSP"
},
{
"code": null,
"e": 26414,
"s": 26382,
"text": "βselfβ: load from the same host"
},
{
"code": null,
"e": 26463,
"s": 26414,
"text": "βunsafe-inlineβ: allow inline styles and scripts"
},
{
"code": null,
"e": 26543,
"s": 26463,
"text": "βunsafe-evalβ: allows eval() and similar methods for creating code from strings"
},
{
"code": null,
"e": 26602,
"s": 26543,
"text": "βnonceβ: a random string that should be unique per request"
},
{
"code": null,
"e": 26852,
"s": 26602,
"text": "CSP works by blocking the execution of styles, scripts, and other things unless they are allowed in the policy. CSP doesnβt allow execution of inline scripts and styles which means we canβt use <script/> and <style/> tags for javascript and styling."
},
{
"code": null,
"e": 26881,
"s": 26852,
"text": "An example of CSP headers is"
},
{
"code": null,
"e": 27029,
"s": 26881,
"text": "Content-Security-Policy: default-src 'self';\nstyle-src: 'self' stakpath.bootstrapcdn.com;\nscript 'self' *.cloudflare.com;\nimg-src 'self' imgur.com;"
},
{
"code": null,
"e": 27586,
"s": 27029,
"text": "In this CSP header, we are telling the browser that the default source for all the styles, scripts, images, objects should be the domain that is passed in the header, along with that we are also allowing stylesheet from stackpath.bootstrapcdn.com which is CDN for bootstrap styles. We are also allowing scripts to be loaded from all Cloudflare subdomains using wildcard subdomain and for images, the browser can allow loading from imgur.com. Apart from these if the webpage tries to load from other domains like twitter the browser will block the requests."
},
{
"code": null,
"e": 27717,
"s": 27586,
"text": "Django doesnβt come with CSP headers in its core but thanks to Mozilla, they have created a package Django-CSP to add CSP headers."
},
{
"code": null,
"e": 27765,
"s": 27717,
"text": "# installing django-csp\npip3 install django-csp"
},
{
"code": null,
"e": 27871,
"s": 27765,
"text": "add CSP to middleware in our setting.py file of the Django project and then we will configure our headers"
},
{
"code": null,
"e": 27879,
"s": 27871,
"text": "Python3"
},
{
"code": "MIDDLEWARE = ( # ... 'csp.middleware.CSPMiddleware', # ...)",
"e": 27948,
"s": 27879,
"text": null
},
{
"code": null,
"e": 28049,
"s": 27948,
"text": "Go to the settings file of the Django project and add the following in the last or anywhere you want"
},
{
"code": null,
"e": 28057,
"s": 28049,
"text": "Python3"
},
{
"code": "# uri to report policy violations# uri to report policy violationsCSP_REPORT_URI = '<add your reporting uri>' # default source as selfCSP_DEFAULT_SRC = (\"'self'\", ) # style from our domain and bootstrapcdnCSP_STYLE_SRC = (\"'self'\", \"stackpath.bootstrapcdn.com\") # scripts from our domain and other domainsCSP_SCRIPT_SRC = (\"'self'\", \"ajax.cloudflare.com\", \"static.cloudflareinsights.com\", \"www.google-analytics.com\", \"ssl.google-analytics.com\", \"cdn.ampproject.org\", \"www.googletagservices.com\", \"pagead2.googlesyndication.com\") # images from our domain and other domainsCSP_IMG_SRC = (\"'self'\", \"www.google-analytics.com\", \"raw.githubusercontent.com\", \"googleads.g.doubleclick.net\") # loading manifest, workers, frames, etcCSP_FONT_SRC = (\"'self'\", )CSP_CONNECT_SRC = (\"'self'\", \"www.google-analytics.com\" )CSP_OBJECT_SRC = (\"'self'\", )CSP_BASE_URI = (\"'self'\", )CSP_FRAME_ANCESTORS = (\"'self'\", )CSP_FORM_ACTION = (\"'self'\", )CSP_INCLUDE_NONCE_IN = ('script-src', )CSP_MANIFEST_SRC = (\"'self'\", )CSP_WORKER_SRC = (\"'self'\", )CSP_MEDIA_SRC = (\"'self'\", )",
"e": 29156,
"s": 28057,
"text": null
},
{
"code": null,
"e": 29214,
"s": 29156,
"text": "You can add the required hostname according to your needs"
},
{
"code": null,
"e": 29285,
"s": 29214,
"text": "Here are some instructions to perfectly implement CSP in your web apps"
},
{
"code": null,
"e": 29327,
"s": 29285,
"text": "Try to avoid adding unnecessary hostnames"
},
{
"code": null,
"e": 29394,
"s": 29327,
"text": "Check as many times as possible while adding or removing hostnames"
},
{
"code": null,
"e": 29483,
"s": 29394,
"text": "Until absolutely necessary donβt add βunsafe-inlineβ, it will weaken our security policy"
},
{
"code": null,
"e": 29521,
"s": 29483,
"text": "Try to avoid inline style and scripts"
},
{
"code": null,
"e": 29596,
"s": 29521,
"text": "It is better not to use CSP in the development server right from the start"
},
{
"code": null,
"e": 29659,
"s": 29596,
"text": "Always try to use HTTPS while loading scripts, styles, images."
},
{
"code": null,
"e": 29674,
"s": 29659,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 29684,
"s": 29674,
"text": "kalrap615"
},
{
"code": null,
"e": 29705,
"s": 29684,
"text": "ddeevviissaavviittaa"
},
{
"code": null,
"e": 29719,
"s": 29705,
"text": "Python Django"
},
{
"code": null,
"e": 29743,
"s": 29719,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29750,
"s": 29743,
"text": "Python"
},
{
"code": null,
"e": 29769,
"s": 29750,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29867,
"s": 29769,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29899,
"s": 29867,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29955,
"s": 29899,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29997,
"s": 29955,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30039,
"s": 29997,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30061,
"s": 30039,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30100,
"s": 30061,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30131,
"s": 30100,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30186,
"s": 30131,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 30215,
"s": 30186,
"text": "Create a directory in Python"
}
] |
How to create and run an EMR cluster using AWS CLI | by Tran Nguyen | Towards Data Science
|
βApache Spark is a unified analytics engine for large-scale data processingβ. Spark is considered as βthe king of the βbig dataβ jungleβ with various applications in data analysis, machine learning, streaming and graph analytics, etc. There are 4 different Spark modes: (1) Local mode: Spark on a single machine such as a laptop for learning syntax and prototyping the project; the other 3 modes are cluster manager modes: (2) Stand-alone mode is used for working on a private cluster; (3) YARN and (4) Mesos modes are used when sharing cluster with a team. With stand-alone mode, Spark is deployed on a private cluster such as EC2 on Amazon Web Service AWS. A Spark cluster includes multiple machines. To use Spark code on each machine, Spark and its dependencies need to be downloaded and installed manually. With Elastic Map Reduce service, EMR, from AWS, everything is ready to use without any manual installation. So instead of using EC2, we use the EMR service to set up Spark clusters.
I did spend many hours struggling to create, set up, and run the Spark cluster on EMR using AWS Command Line Interface, AWS CLI. Although there are a few tutorials for this task that I found or were provided through courses, most of them are so frustrating to follow. Some are not clear enough; some miss some crucial steps; or assume the learners know some prior knowledge about AWS, CLI configurations, etc. After successfully setting up and getting the cluster running, I realized that this task is actually not that complicated; and we should get it done with ease. I donβt want to see people struggling with this anymore. Therefore, I decided to make this tutorial.
This article assumes that you already have some working knowledge of Spark, PySpark, command-line environment, and AWS. Specifically, this article is for readers who know why they need to create the Spark cluster :). For more about Spark, please read the reference here.
This is a long and detailed tutorial. In brief, all the steps include:
Create an AWS accountCreate an IAM userSet up credentials in EC2Create an S3 bucket to store log files produced by the clusterInstall AWS CLI package awscliSet up AWS CLI environment (create the credentials and config files)Create an EMR clusterAllow SSH AccessCreate an SSH connection with the master node of the clusterStart using the EMR cluster
Create an AWS account
Create an IAM user
Set up credentials in EC2
Create an S3 bucket to store log files produced by the cluster
Install AWS CLI package awscli
Set up AWS CLI environment (create the credentials and config files)
Create an EMR cluster
Allow SSH Access
Create an SSH connection with the master node of the cluster
Start using the EMR cluster
Please feel free to skip any step that you already know. The Jupyter notebook version of this tutorial, together with other tutorials on Spark and many more data science tutorials could be found on my Github. Now, letβs dive in!
I am so glad that many of you found this tutorial useful. It is my honor to discuss any issue you encountered during the EMR creating process with you all. Based on some of our discussions, here are some updates for this tutorial.
Some cautions:
1. For this tutorial, AWS regular account should be used instead of AWS Educate account. The AWS regular account provides users the full access to AWS resources and IAM roles; while educate account has some limited access.
2. This is your responsibility for monitoring usage charges on the AWS account you use. Remember to terminate the cluster and other related resources each time you finish working. I have implemented the EMR cluster many times; and this tutorial should produce no cost or cost less than $0.5 on AWS.
3. The AWS console and Udacity content are subjected to change/upgrade through time, so I would recommend you to search AWS site and your Udacityβs lessons for any updated tutorials/guidelines. This tutorial was generated according to the AWS console in July, 2020.
4. This tutorial is produced using Chrome and Mac OS X. It should not be so much different on Windows platform.
Some of the materials are from the Data Engineer nanodegree program on Udacity.
Some ideas and issues were collected from the Knowledge β Udacity Q&A Platform and the Student Hub β Udacity chat platform.
Creating a regular AWS account if you donβt have one already. The instruction is very easy to follow on the AWS site.
Log into your AWS account.
(Optional) To increase security on your AWS resources, you can configure and enable a virtual multi-factor authentication (MFA) device according to the easy AWS guide here.
From the AWS console, click onService, type βIAMβ to go to IAM console:
=> Choose User => Add user => Enter a user name such as 'emr_user' , Choose Access type as Programmatic access, and then Next: Permissions.
Click on Attach existence policies directly page, type and set permission as Administrator Access and then choose Next: Tags.
Skip this tag page and choose Next: Review => Choose Create user => Save the user name, Access Key and Secret Access Key.
We will use this IAM user and the access and secret key to set up and access AWS via AWS CLI.
From the AWS console, click on Service, type 'EC2' to go to EC2 console
Choose Key Pairs in Network & Security on the left panel => Choose Create key pair
Type the name for the key pairs, such as "emr-cluster", File format: pem => Choose Create key pair . After this step, a .pem file will be automatically downloaded, in this case, the file name is emr_cluster.pem. We will use this file in Step 6.
This will be the AWS bucket to store the log files produced by the cluster we will create and set up. If we donβt specify an S3 bucket, an S3 bucket will be automatically created for us when an EMR cluster is created and run.
From the AWS console, click on Service, type 'S3' and go to S3 console => Choose Create bucket => Enter a name for the bucket such as 's3-for-emr-cluster', choose your preferred region, such as βUS West(Oregon). Keep other options at default to create a bucket.
Note that for the best performance and to avoid any error, remember to use the same AWS region/sub-region for all of your work (on S3, EC2, EMR, etc.)
On the terminal, install awscliusing the commandpip install awscli
Type aws help to check if the installation is correct. The installation should be successful if the output is as below:
This step will help us automatically access AWS on the awscli environment using the user credentials we got on Step 2 above.
There are 2 approaches for this set-up: manually creating the credentials and config files (approach 1) or creating these files using theaws command (approach 2). You can use either one.
Approach 1:
Create the credentials file on the terminal as follow (you can use nano or any other text editor of your choice):
On the terminal, navigate to desire folder, usually the root directory and create a hidden directory such as aws :
$mkdir .aws (period to denote a hidden directory)
Change to that directory $cd .aws
Create acredentials file using nano: $nano credentials Type the content of the credentials file as followed (Replace the key βEXAMPLE_IDβ and secret key βEXAMPle_Keyβ with the ones produced for the user βemr-userβ in Step 2):
Use Ctrl + X, and then Y to save the file and exit nano.
Create the config file:
$nano config Type the content of the config file as followed (The region we use would be the same we use to create an S3 bucket in Step 4):
[default]region=us-west-2
Use Ctrl + X, and then Y to save the file and exit nano.
On the terminal, type $aws configure and type in the required information as followed:
AWS Access Key ID [None]: (Enter your access key from the user 'emr-user' created in Step 2)AWS Secret Access Key [None]: (Enter your secret key from the user 'emr-user' created in Step 2)Default region name [None]: us-west-2 (The same region used in Step 4)Default output format [None]:
The 2 files will be automatically created in the hidden folder .aws, usually located at root directory as follow:
$cd ~/.aws
Type$ls to verify the existence of the 2 files. The information should be the same as in Approach 1, we can check the content by typing:
$cat credentials
$cat config
To connect to the cluster, we need the .pem file created in step 3. Move the .pem file we downloaded in Step 3 to a desire location used for the project. For me, I put it to the same location as credentials and config files in the hidden folder .aws located at the root directory ~/.aws/emr-cluster.pem )
$ mv ~/Downloads/emr-cluster.pem .
When using this .pem file to set up the ssh, there would be an error if the .pem file is too open. An example of warning would be: βPermissions 0644 for β~/.aws/emr-cluster.pemβ are too open. It is required that your private key files are NOT accessible by others. This private key will be ignored.β
In that case, we need to change the permission for this .pem file using the command: sudo chmod 600 ~/.aws/emr-cluster.pem
To verify if we successfully install awscli and set up the credentials, type some aws commands such as
List all IAM user: $aws iam list-users
List all buckets in s3: $aws s3 ls This command will list all the s3 bucket that we have in AWS:
Now we are ready to create our EMR cluster on the terminal. On the terminal, type the command:
aws emr create-cluster --name test-emr-cluster --use-default-roles --release-label emr-5.28.0 --instance-count 3 --instance-type m5.xlarge --applications Name=JupyterHub Name=Spark Name=Hadoop --ec2-attributes KeyName=emr-cluster --log-uri s3://s3-for-emr-cluster/
The explanation for the EMR script components:
--name: the name for the cluster, in this case, is 'test-emr-cluster'
--use-default-roles: use the default service role (EMR_DefaultRole) and instance profile (EMR_EC2_DefaultRole) for permissions to access other AWS services
--release-label emr-5.28.0: build a cluster with EMR version 5.28.0
--instance-count 3 and--instance-type m5.xlarge: build 1 Master node and 2 Core nodes of type m5.xlarge
--applications Name=JupyterHub Name=Spark Name=Hadoop: install JupyterHub, Spark, and Hadoop on this cluster
--ec2-attributes KeyName=emr-cluster: configures Amazon EC2 instance configurations, KeyName is the EC2 instance name that we set up in step 3 (Set up credentials in EC2 and get the .pem file). In this case, the name is emr-cluster.
--log-uri s3://s3-for-emr-cluster/: specify the S3 bucket where you want to store log files. In this case, the S3 bucket is 's3-for-emr-cluster'. This field is optional (as explained in Step 4).
Since EMR clusters are costly, we can put the option --auto-terminate to auto-terminate the cluster when all the actions on the cluster are done. For this to work, we also need to specify the bootstrap action in the command using --bootstrap-actions Path="s3://bootstrap.sh". When you use auto-termination, the cluster starts, runs any bootstrap actions that you specify, and then executes steps that typically input data, process the data, and then produce and save the output. When the steps finish, Amazon EMR automatically terminates the cluster Amazon EC2 instances. If we don't put any bootstrap action, we should remove this field. The reference for bootstrap could be found in detail on the AWS site.
Desired output after we create an EMR cluster would be:
Using the ClusterId to check status and information of the cluster (j- EXAMPLECLUSTERID) using the command:
aws emr describe-cluster --cluster-id j-EXAMPLECLUSTERID
We should wait for a few minutes for the cluster to be available (Status changes to βavailableβ) before proceeding to the next step.
***Update 1: If you run into the problem that "EMR_DefaultRole is invalid" or "EMR_EC2_DefaultRole is invalid" error when creating an Amazon EMR cluster, you may have to delete the roles and the instance profile; then recreate the roles as this instruction. Thank Trevor S. for discussing this issue.
***Update 2: To make the cluster available for the notebook on EMR, we may need to include the SubnetIds in β ec2-attributes:
aws emr create-cluster --name test-emr-cluster --use-default-roles --release-label emr-5.28.0 --instance-count 3 --instance-type m5.xlarge --applications Name=JupyterHub Name=Spark Name=Hadoop --ec2-attributes SubnetIds=subnet-YOURSUBNET,KeyName=emr-cluster --log-uri s3://s3-for-emr-cluster/
(Thank Saverio G. for discussing me about this issue.)
How to find SubnetIds?
Click on the VPCSubnets tab on the EMR console to choose from the list.
Another safe way for the beginner: Create a similar EMR cluster using the AWS console. Then look at the βNetwork and hardwareβ session on the Summary page of that cluster to see the Subnet ID:
You can access Subnets via VPC Dashboard on AWS. More about subnet and VPC could be found on the AWS site.
From the AWS console, click on Service, type EMR, and go to EMR console.
=> Choose Clusters => Choose the name of the cluster on the list, in this case, is test-emr-cluster
On the Summary tab, scroll down to see the part Security and access, choose the Security groups for Master link
Choose the Security group ID for ElasticMapReduce-master
Scroll down on Inbound rules, Edit inbound rules => For safety, delete any SSH rule if have, then choose Add Rule => Choose Type: SSH, TCP for Protocol and 22 for Port Range => For source, select My IP => Choose Save .
Approach 1:
On the terminal, check the id of the cluster using the command
aws emr list-clusters
Use this command to connect to the cluster. Remember to specify the right path of the .pem file:
aws emr ssh --cluster-id j-EXAMPLECLUSTERID --key-pair-file ~/.aws/emr-cluster.pem
If we see the screen with the EMR letter as below, congratulations, you successfully create, set up, and connect to the EMR cluster using AWS CLI !!!!
Close the connection to the cluster using the command $logout .
Approach 2:
From the AWS console, click on Service, type EMR, and go to EMR console.
Choose Clusters => Click on the name of the cluster on the list, in this case test-emr-cluster => On the Summary tab, Click the link Connect to the Master Node Using SSH.
Copy the command shown on the pop-up window and paste it on the terminal.
Remember to replace ~/emr-cluster.pem with the location and filename of the private key file (.pem) we have set up. For example
ssh -i ~/.aws/emr-cluster.pem [email protected]
If we see the screen with the EMR letter, congratulations, you successfully create, set up, and connect to the EMR cluster using AWS CLI !!!!
Create a simple Spark task, for example, create a Spark data frame containing the time as type string and then convert that column to a different format.
On the cluster terminal, create the file test_emr.py
$nano test_emr.py
Copy and paste this script to test_emr.py
### Content of the file 'test_emr.py'from pyspark.sql import SparkSession, functions as Fif __name__ == "__main__": """ example of script submited to spark cluster """ spark = SparkSession.builder.getOrCreate() df = spark.createDataFrame([('01/Jul/1995:00:00:01 -0400', ),('01/Jul/1995:00:00:11 -0400',),('26/Jul/1995:17$ ('19/Jul/1995:01:56:43 -0400',), ('11/Jul/1995:12:50:18 -0400',)], ['TIME']) df = df.withColumn("date", F.unix_timestamp(F.col('TIME'), 'dd/MMM/yyyy:HH:mm:ss Z').cast('timestamp')) # show the dataframe df.show() #### stop the spark, otherwise the program will be hanged spark.stop()
The content of the file as shown on nano text editor:
Submit the script on the cluster terminal using the command:
$spark-submit --master yarn ./test_emr.py
When the task runs, it may get overwhelming with any information on the terminal, which is normal in Spark. The output could be found among the info logging:
Remember to terminate the cluster when not using it anymore.
Type logout to log out of the cluster. Then terminate the cluster using this command:
$aws emr terminate-clusters --cluster-id j-EXAMPLECLUSTERID
Notice that we can easily create a cluster with the same configurations again using the AWS CLI command, which could be found when clicking on the AWS CLI export tab when we choose the terminated cluster `test-emr-cluster` on the EMR console:
I hope no one has to struggle to create, set up, and run the Spark cluster on EMR using AWS CLI anymore. Please let me know if you have any issues or find anything wrong with this tutorial.
The Jupyter notebook version of this tutorial, together with other tutorials on Spark and many more data science tutorials could be found on my Github. Please enjoy!
|
[
{
"code": null,
"e": 1165,
"s": 172,
"text": "βApache Spark is a unified analytics engine for large-scale data processingβ. Spark is considered as βthe king of the βbig dataβ jungleβ with various applications in data analysis, machine learning, streaming and graph analytics, etc. There are 4 different Spark modes: (1) Local mode: Spark on a single machine such as a laptop for learning syntax and prototyping the project; the other 3 modes are cluster manager modes: (2) Stand-alone mode is used for working on a private cluster; (3) YARN and (4) Mesos modes are used when sharing cluster with a team. With stand-alone mode, Spark is deployed on a private cluster such as EC2 on Amazon Web Service AWS. A Spark cluster includes multiple machines. To use Spark code on each machine, Spark and its dependencies need to be downloaded and installed manually. With Elastic Map Reduce service, EMR, from AWS, everything is ready to use without any manual installation. So instead of using EC2, we use the EMR service to set up Spark clusters."
},
{
"code": null,
"e": 1836,
"s": 1165,
"text": "I did spend many hours struggling to create, set up, and run the Spark cluster on EMR using AWS Command Line Interface, AWS CLI. Although there are a few tutorials for this task that I found or were provided through courses, most of them are so frustrating to follow. Some are not clear enough; some miss some crucial steps; or assume the learners know some prior knowledge about AWS, CLI configurations, etc. After successfully setting up and getting the cluster running, I realized that this task is actually not that complicated; and we should get it done with ease. I donβt want to see people struggling with this anymore. Therefore, I decided to make this tutorial."
},
{
"code": null,
"e": 2107,
"s": 1836,
"text": "This article assumes that you already have some working knowledge of Spark, PySpark, command-line environment, and AWS. Specifically, this article is for readers who know why they need to create the Spark cluster :). For more about Spark, please read the reference here."
},
{
"code": null,
"e": 2178,
"s": 2107,
"text": "This is a long and detailed tutorial. In brief, all the steps include:"
},
{
"code": null,
"e": 2527,
"s": 2178,
"text": "Create an AWS accountCreate an IAM userSet up credentials in EC2Create an S3 bucket to store log files produced by the clusterInstall AWS CLI package awscliSet up AWS CLI environment (create the credentials and config files)Create an EMR clusterAllow SSH AccessCreate an SSH connection with the master node of the clusterStart using the EMR cluster"
},
{
"code": null,
"e": 2549,
"s": 2527,
"text": "Create an AWS account"
},
{
"code": null,
"e": 2568,
"s": 2549,
"text": "Create an IAM user"
},
{
"code": null,
"e": 2594,
"s": 2568,
"text": "Set up credentials in EC2"
},
{
"code": null,
"e": 2657,
"s": 2594,
"text": "Create an S3 bucket to store log files produced by the cluster"
},
{
"code": null,
"e": 2688,
"s": 2657,
"text": "Install AWS CLI package awscli"
},
{
"code": null,
"e": 2757,
"s": 2688,
"text": "Set up AWS CLI environment (create the credentials and config files)"
},
{
"code": null,
"e": 2779,
"s": 2757,
"text": "Create an EMR cluster"
},
{
"code": null,
"e": 2796,
"s": 2779,
"text": "Allow SSH Access"
},
{
"code": null,
"e": 2857,
"s": 2796,
"text": "Create an SSH connection with the master node of the cluster"
},
{
"code": null,
"e": 2885,
"s": 2857,
"text": "Start using the EMR cluster"
},
{
"code": null,
"e": 3114,
"s": 2885,
"text": "Please feel free to skip any step that you already know. The Jupyter notebook version of this tutorial, together with other tutorials on Spark and many more data science tutorials could be found on my Github. Now, letβs dive in!"
},
{
"code": null,
"e": 3345,
"s": 3114,
"text": "I am so glad that many of you found this tutorial useful. It is my honor to discuss any issue you encountered during the EMR creating process with you all. Based on some of our discussions, here are some updates for this tutorial."
},
{
"code": null,
"e": 3360,
"s": 3345,
"text": "Some cautions:"
},
{
"code": null,
"e": 3583,
"s": 3360,
"text": "1. For this tutorial, AWS regular account should be used instead of AWS Educate account. The AWS regular account provides users the full access to AWS resources and IAM roles; while educate account has some limited access."
},
{
"code": null,
"e": 3882,
"s": 3583,
"text": "2. This is your responsibility for monitoring usage charges on the AWS account you use. Remember to terminate the cluster and other related resources each time you finish working. I have implemented the EMR cluster many times; and this tutorial should produce no cost or cost less than $0.5 on AWS."
},
{
"code": null,
"e": 4148,
"s": 3882,
"text": "3. The AWS console and Udacity content are subjected to change/upgrade through time, so I would recommend you to search AWS site and your Udacityβs lessons for any updated tutorials/guidelines. This tutorial was generated according to the AWS console in July, 2020."
},
{
"code": null,
"e": 4260,
"s": 4148,
"text": "4. This tutorial is produced using Chrome and Mac OS X. It should not be so much different on Windows platform."
},
{
"code": null,
"e": 4340,
"s": 4260,
"text": "Some of the materials are from the Data Engineer nanodegree program on Udacity."
},
{
"code": null,
"e": 4464,
"s": 4340,
"text": "Some ideas and issues were collected from the Knowledge β Udacity Q&A Platform and the Student Hub β Udacity chat platform."
},
{
"code": null,
"e": 4582,
"s": 4464,
"text": "Creating a regular AWS account if you donβt have one already. The instruction is very easy to follow on the AWS site."
},
{
"code": null,
"e": 4609,
"s": 4582,
"text": "Log into your AWS account."
},
{
"code": null,
"e": 4782,
"s": 4609,
"text": "(Optional) To increase security on your AWS resources, you can configure and enable a virtual multi-factor authentication (MFA) device according to the easy AWS guide here."
},
{
"code": null,
"e": 4854,
"s": 4782,
"text": "From the AWS console, click onService, type βIAMβ to go to IAM console:"
},
{
"code": null,
"e": 4994,
"s": 4854,
"text": "=> Choose User => Add user => Enter a user name such as 'emr_user' , Choose Access type as Programmatic access, and then Next: Permissions."
},
{
"code": null,
"e": 5120,
"s": 4994,
"text": "Click on Attach existence policies directly page, type and set permission as Administrator Access and then choose Next: Tags."
},
{
"code": null,
"e": 5242,
"s": 5120,
"text": "Skip this tag page and choose Next: Review => Choose Create user => Save the user name, Access Key and Secret Access Key."
},
{
"code": null,
"e": 5336,
"s": 5242,
"text": "We will use this IAM user and the access and secret key to set up and access AWS via AWS CLI."
},
{
"code": null,
"e": 5408,
"s": 5336,
"text": "From the AWS console, click on Service, type 'EC2' to go to EC2 console"
},
{
"code": null,
"e": 5491,
"s": 5408,
"text": "Choose Key Pairs in Network & Security on the left panel => Choose Create key pair"
},
{
"code": null,
"e": 5736,
"s": 5491,
"text": "Type the name for the key pairs, such as \"emr-cluster\", File format: pem => Choose Create key pair . After this step, a .pem file will be automatically downloaded, in this case, the file name is emr_cluster.pem. We will use this file in Step 6."
},
{
"code": null,
"e": 5962,
"s": 5736,
"text": "This will be the AWS bucket to store the log files produced by the cluster we will create and set up. If we donβt specify an S3 bucket, an S3 bucket will be automatically created for us when an EMR cluster is created and run."
},
{
"code": null,
"e": 6224,
"s": 5962,
"text": "From the AWS console, click on Service, type 'S3' and go to S3 console => Choose Create bucket => Enter a name for the bucket such as 's3-for-emr-cluster', choose your preferred region, such as βUS West(Oregon). Keep other options at default to create a bucket."
},
{
"code": null,
"e": 6375,
"s": 6224,
"text": "Note that for the best performance and to avoid any error, remember to use the same AWS region/sub-region for all of your work (on S3, EC2, EMR, etc.)"
},
{
"code": null,
"e": 6442,
"s": 6375,
"text": "On the terminal, install awscliusing the commandpip install awscli"
},
{
"code": null,
"e": 6562,
"s": 6442,
"text": "Type aws help to check if the installation is correct. The installation should be successful if the output is as below:"
},
{
"code": null,
"e": 6687,
"s": 6562,
"text": "This step will help us automatically access AWS on the awscli environment using the user credentials we got on Step 2 above."
},
{
"code": null,
"e": 6874,
"s": 6687,
"text": "There are 2 approaches for this set-up: manually creating the credentials and config files (approach 1) or creating these files using theaws command (approach 2). You can use either one."
},
{
"code": null,
"e": 6886,
"s": 6874,
"text": "Approach 1:"
},
{
"code": null,
"e": 7000,
"s": 6886,
"text": "Create the credentials file on the terminal as follow (you can use nano or any other text editor of your choice):"
},
{
"code": null,
"e": 7115,
"s": 7000,
"text": "On the terminal, navigate to desire folder, usually the root directory and create a hidden directory such as aws :"
},
{
"code": null,
"e": 7165,
"s": 7115,
"text": "$mkdir .aws (period to denote a hidden directory)"
},
{
"code": null,
"e": 7199,
"s": 7165,
"text": "Change to that directory $cd .aws"
},
{
"code": null,
"e": 7425,
"s": 7199,
"text": "Create acredentials file using nano: $nano credentials Type the content of the credentials file as followed (Replace the key βEXAMPLE_IDβ and secret key βEXAMPle_Keyβ with the ones produced for the user βemr-userβ in Step 2):"
},
{
"code": null,
"e": 7482,
"s": 7425,
"text": "Use Ctrl + X, and then Y to save the file and exit nano."
},
{
"code": null,
"e": 7506,
"s": 7482,
"text": "Create the config file:"
},
{
"code": null,
"e": 7646,
"s": 7506,
"text": "$nano config Type the content of the config file as followed (The region we use would be the same we use to create an S3 bucket in Step 4):"
},
{
"code": null,
"e": 7672,
"s": 7646,
"text": "[default]region=us-west-2"
},
{
"code": null,
"e": 7729,
"s": 7672,
"text": "Use Ctrl + X, and then Y to save the file and exit nano."
},
{
"code": null,
"e": 7816,
"s": 7729,
"text": "On the terminal, type $aws configure and type in the required information as followed:"
},
{
"code": null,
"e": 8104,
"s": 7816,
"text": "AWS Access Key ID [None]: (Enter your access key from the user 'emr-user' created in Step 2)AWS Secret Access Key [None]: (Enter your secret key from the user 'emr-user' created in Step 2)Default region name [None]: us-west-2 (The same region used in Step 4)Default output format [None]:"
},
{
"code": null,
"e": 8218,
"s": 8104,
"text": "The 2 files will be automatically created in the hidden folder .aws, usually located at root directory as follow:"
},
{
"code": null,
"e": 8229,
"s": 8218,
"text": "$cd ~/.aws"
},
{
"code": null,
"e": 8366,
"s": 8229,
"text": "Type$ls to verify the existence of the 2 files. The information should be the same as in Approach 1, we can check the content by typing:"
},
{
"code": null,
"e": 8383,
"s": 8366,
"text": "$cat credentials"
},
{
"code": null,
"e": 8395,
"s": 8383,
"text": "$cat config"
},
{
"code": null,
"e": 8700,
"s": 8395,
"text": "To connect to the cluster, we need the .pem file created in step 3. Move the .pem file we downloaded in Step 3 to a desire location used for the project. For me, I put it to the same location as credentials and config files in the hidden folder .aws located at the root directory ~/.aws/emr-cluster.pem )"
},
{
"code": null,
"e": 8735,
"s": 8700,
"text": "$ mv ~/Downloads/emr-cluster.pem ."
},
{
"code": null,
"e": 9035,
"s": 8735,
"text": "When using this .pem file to set up the ssh, there would be an error if the .pem file is too open. An example of warning would be: βPermissions 0644 for β~/.aws/emr-cluster.pemβ are too open. It is required that your private key files are NOT accessible by others. This private key will be ignored.β"
},
{
"code": null,
"e": 9158,
"s": 9035,
"text": "In that case, we need to change the permission for this .pem file using the command: sudo chmod 600 ~/.aws/emr-cluster.pem"
},
{
"code": null,
"e": 9261,
"s": 9158,
"text": "To verify if we successfully install awscli and set up the credentials, type some aws commands such as"
},
{
"code": null,
"e": 9300,
"s": 9261,
"text": "List all IAM user: $aws iam list-users"
},
{
"code": null,
"e": 9397,
"s": 9300,
"text": "List all buckets in s3: $aws s3 ls This command will list all the s3 bucket that we have in AWS:"
},
{
"code": null,
"e": 9492,
"s": 9397,
"text": "Now we are ready to create our EMR cluster on the terminal. On the terminal, type the command:"
},
{
"code": null,
"e": 9758,
"s": 9492,
"text": "aws emr create-cluster --name test-emr-cluster --use-default-roles --release-label emr-5.28.0 --instance-count 3 --instance-type m5.xlarge --applications Name=JupyterHub Name=Spark Name=Hadoop --ec2-attributes KeyName=emr-cluster --log-uri s3://s3-for-emr-cluster/"
},
{
"code": null,
"e": 9805,
"s": 9758,
"text": "The explanation for the EMR script components:"
},
{
"code": null,
"e": 9875,
"s": 9805,
"text": "--name: the name for the cluster, in this case, is 'test-emr-cluster'"
},
{
"code": null,
"e": 10031,
"s": 9875,
"text": "--use-default-roles: use the default service role (EMR_DefaultRole) and instance profile (EMR_EC2_DefaultRole) for permissions to access other AWS services"
},
{
"code": null,
"e": 10099,
"s": 10031,
"text": "--release-label emr-5.28.0: build a cluster with EMR version 5.28.0"
},
{
"code": null,
"e": 10203,
"s": 10099,
"text": "--instance-count 3 and--instance-type m5.xlarge: build 1 Master node and 2 Core nodes of type m5.xlarge"
},
{
"code": null,
"e": 10312,
"s": 10203,
"text": "--applications Name=JupyterHub Name=Spark Name=Hadoop: install JupyterHub, Spark, and Hadoop on this cluster"
},
{
"code": null,
"e": 10545,
"s": 10312,
"text": "--ec2-attributes KeyName=emr-cluster: configures Amazon EC2 instance configurations, KeyName is the EC2 instance name that we set up in step 3 (Set up credentials in EC2 and get the .pem file). In this case, the name is emr-cluster."
},
{
"code": null,
"e": 10740,
"s": 10545,
"text": "--log-uri s3://s3-for-emr-cluster/: specify the S3 bucket where you want to store log files. In this case, the S3 bucket is 's3-for-emr-cluster'. This field is optional (as explained in Step 4)."
},
{
"code": null,
"e": 11449,
"s": 10740,
"text": "Since EMR clusters are costly, we can put the option --auto-terminate to auto-terminate the cluster when all the actions on the cluster are done. For this to work, we also need to specify the bootstrap action in the command using --bootstrap-actions Path=\"s3://bootstrap.sh\". When you use auto-termination, the cluster starts, runs any bootstrap actions that you specify, and then executes steps that typically input data, process the data, and then produce and save the output. When the steps finish, Amazon EMR automatically terminates the cluster Amazon EC2 instances. If we don't put any bootstrap action, we should remove this field. The reference for bootstrap could be found in detail on the AWS site."
},
{
"code": null,
"e": 11505,
"s": 11449,
"text": "Desired output after we create an EMR cluster would be:"
},
{
"code": null,
"e": 11613,
"s": 11505,
"text": "Using the ClusterId to check status and information of the cluster (j- EXAMPLECLUSTERID) using the command:"
},
{
"code": null,
"e": 11670,
"s": 11613,
"text": "aws emr describe-cluster --cluster-id j-EXAMPLECLUSTERID"
},
{
"code": null,
"e": 11803,
"s": 11670,
"text": "We should wait for a few minutes for the cluster to be available (Status changes to βavailableβ) before proceeding to the next step."
},
{
"code": null,
"e": 12104,
"s": 11803,
"text": "***Update 1: If you run into the problem that \"EMR_DefaultRole is invalid\" or \"EMR_EC2_DefaultRole is invalid\" error when creating an Amazon EMR cluster, you may have to delete the roles and the instance profile; then recreate the roles as this instruction. Thank Trevor S. for discussing this issue."
},
{
"code": null,
"e": 12230,
"s": 12104,
"text": "***Update 2: To make the cluster available for the notebook on EMR, we may need to include the SubnetIds in β ec2-attributes:"
},
{
"code": null,
"e": 12524,
"s": 12230,
"text": "aws emr create-cluster --name test-emr-cluster --use-default-roles --release-label emr-5.28.0 --instance-count 3 --instance-type m5.xlarge --applications Name=JupyterHub Name=Spark Name=Hadoop --ec2-attributes SubnetIds=subnet-YOURSUBNET,KeyName=emr-cluster --log-uri s3://s3-for-emr-cluster/"
},
{
"code": null,
"e": 12579,
"s": 12524,
"text": "(Thank Saverio G. for discussing me about this issue.)"
},
{
"code": null,
"e": 12602,
"s": 12579,
"text": "How to find SubnetIds?"
},
{
"code": null,
"e": 12674,
"s": 12602,
"text": "Click on the VPCSubnets tab on the EMR console to choose from the list."
},
{
"code": null,
"e": 12867,
"s": 12674,
"text": "Another safe way for the beginner: Create a similar EMR cluster using the AWS console. Then look at the βNetwork and hardwareβ session on the Summary page of that cluster to see the Subnet ID:"
},
{
"code": null,
"e": 12974,
"s": 12867,
"text": "You can access Subnets via VPC Dashboard on AWS. More about subnet and VPC could be found on the AWS site."
},
{
"code": null,
"e": 13047,
"s": 12974,
"text": "From the AWS console, click on Service, type EMR, and go to EMR console."
},
{
"code": null,
"e": 13147,
"s": 13047,
"text": "=> Choose Clusters => Choose the name of the cluster on the list, in this case, is test-emr-cluster"
},
{
"code": null,
"e": 13259,
"s": 13147,
"text": "On the Summary tab, scroll down to see the part Security and access, choose the Security groups for Master link"
},
{
"code": null,
"e": 13316,
"s": 13259,
"text": "Choose the Security group ID for ElasticMapReduce-master"
},
{
"code": null,
"e": 13535,
"s": 13316,
"text": "Scroll down on Inbound rules, Edit inbound rules => For safety, delete any SSH rule if have, then choose Add Rule => Choose Type: SSH, TCP for Protocol and 22 for Port Range => For source, select My IP => Choose Save ."
},
{
"code": null,
"e": 13547,
"s": 13535,
"text": "Approach 1:"
},
{
"code": null,
"e": 13610,
"s": 13547,
"text": "On the terminal, check the id of the cluster using the command"
},
{
"code": null,
"e": 13632,
"s": 13610,
"text": "aws emr list-clusters"
},
{
"code": null,
"e": 13729,
"s": 13632,
"text": "Use this command to connect to the cluster. Remember to specify the right path of the .pem file:"
},
{
"code": null,
"e": 13812,
"s": 13729,
"text": "aws emr ssh --cluster-id j-EXAMPLECLUSTERID --key-pair-file ~/.aws/emr-cluster.pem"
},
{
"code": null,
"e": 13963,
"s": 13812,
"text": "If we see the screen with the EMR letter as below, congratulations, you successfully create, set up, and connect to the EMR cluster using AWS CLI !!!!"
},
{
"code": null,
"e": 14027,
"s": 13963,
"text": "Close the connection to the cluster using the command $logout ."
},
{
"code": null,
"e": 14039,
"s": 14027,
"text": "Approach 2:"
},
{
"code": null,
"e": 14112,
"s": 14039,
"text": "From the AWS console, click on Service, type EMR, and go to EMR console."
},
{
"code": null,
"e": 14283,
"s": 14112,
"text": "Choose Clusters => Click on the name of the cluster on the list, in this case test-emr-cluster => On the Summary tab, Click the link Connect to the Master Node Using SSH."
},
{
"code": null,
"e": 14357,
"s": 14283,
"text": "Copy the command shown on the pop-up window and paste it on the terminal."
},
{
"code": null,
"e": 14485,
"s": 14357,
"text": "Remember to replace ~/emr-cluster.pem with the location and filename of the private key file (.pem) we have set up. For example"
},
{
"code": null,
"e": 14571,
"s": 14485,
"text": "ssh -i ~/.aws/emr-cluster.pem [email protected]"
},
{
"code": null,
"e": 14713,
"s": 14571,
"text": "If we see the screen with the EMR letter, congratulations, you successfully create, set up, and connect to the EMR cluster using AWS CLI !!!!"
},
{
"code": null,
"e": 14867,
"s": 14713,
"text": "Create a simple Spark task, for example, create a Spark data frame containing the time as type string and then convert that column to a different format."
},
{
"code": null,
"e": 14920,
"s": 14867,
"text": "On the cluster terminal, create the file test_emr.py"
},
{
"code": null,
"e": 14938,
"s": 14920,
"text": "$nano test_emr.py"
},
{
"code": null,
"e": 14980,
"s": 14938,
"text": "Copy and paste this script to test_emr.py"
},
{
"code": null,
"e": 15655,
"s": 14980,
"text": "### Content of the file 'test_emr.py'from pyspark.sql import SparkSession, functions as Fif __name__ == \"__main__\": \"\"\" example of script submited to spark cluster \"\"\" spark = SparkSession.builder.getOrCreate() df = spark.createDataFrame([('01/Jul/1995:00:00:01 -0400', ),('01/Jul/1995:00:00:11 -0400',),('26/Jul/1995:17$ ('19/Jul/1995:01:56:43 -0400',), ('11/Jul/1995:12:50:18 -0400',)], ['TIME']) df = df.withColumn(\"date\", F.unix_timestamp(F.col('TIME'), 'dd/MMM/yyyy:HH:mm:ss Z').cast('timestamp')) # show the dataframe df.show() #### stop the spark, otherwise the program will be hanged spark.stop()"
},
{
"code": null,
"e": 15709,
"s": 15655,
"text": "The content of the file as shown on nano text editor:"
},
{
"code": null,
"e": 15770,
"s": 15709,
"text": "Submit the script on the cluster terminal using the command:"
},
{
"code": null,
"e": 15812,
"s": 15770,
"text": "$spark-submit --master yarn ./test_emr.py"
},
{
"code": null,
"e": 15970,
"s": 15812,
"text": "When the task runs, it may get overwhelming with any information on the terminal, which is normal in Spark. The output could be found among the info logging:"
},
{
"code": null,
"e": 16031,
"s": 15970,
"text": "Remember to terminate the cluster when not using it anymore."
},
{
"code": null,
"e": 16117,
"s": 16031,
"text": "Type logout to log out of the cluster. Then terminate the cluster using this command:"
},
{
"code": null,
"e": 16177,
"s": 16117,
"text": "$aws emr terminate-clusters --cluster-id j-EXAMPLECLUSTERID"
},
{
"code": null,
"e": 16420,
"s": 16177,
"text": "Notice that we can easily create a cluster with the same configurations again using the AWS CLI command, which could be found when clicking on the AWS CLI export tab when we choose the terminated cluster `test-emr-cluster` on the EMR console:"
},
{
"code": null,
"e": 16610,
"s": 16420,
"text": "I hope no one has to struggle to create, set up, and run the Spark cluster on EMR using AWS CLI anymore. Please let me know if you have any issues or find anything wrong with this tutorial."
}
] |
Non-deterministic PDA
|
Theory of Computation
A non-deterministic PDA is used to generate a language that a deterministic automata cannot generate. It is more powerful than a deterministic PDA. So, a push down automata is allowed to be non-deterministic.
M = (Q,Ξ£,Ξ,Ξ΄,q0,Z0,F)
Q- It is the finite set of states, Ξ£ - finite set of input alphabet, Ξ - finite set of stack alphabet, Ξ΄ - transition function, q0 - initial state, Z0 - stack start symbol, F - finite states.
|
[
{
"code": null,
"e": 112,
"s": 90,
"text": "Theory of Computation"
},
{
"code": null,
"e": 321,
"s": 112,
"text": "A non-deterministic PDA is used to generate a language that a deterministic automata cannot generate. It is more powerful than a deterministic PDA. So, a push down automata is allowed to be non-deterministic."
},
{
"code": null,
"e": 343,
"s": 321,
"text": "M = (Q,Ξ£,Ξ,Ξ΄,q0,Z0,F)"
}
] |
Deep Learning with Magnetic Resonance and Computed Tomography Images | by Jacob Reinhold | Towards Data Science
|
Getting started with applying deep learning to magnetic resonance (MR) or computed tomography (CT) images is not straightforward; finding appropriate data sets, preprocessing the data, and creating the data loader structures necessary to do the work is a pain to figure out. In this post I hope to alleviate some of that pain for newcomers. To do so, Iβll link to several freely-available datasets, review some common/necessary preprocessing techniques specific to MR and CT, and show how to use the fastai library to load (structural) MR images and train a deep neural network for a synthesis task.
Before we get into the meat and bones of this post, it will be useful to do a quick overview of the medical images that weβll be talking about and some idiosyncrasies of the types of images in discussion. Iβll only be talking about structural MR images and (to a lesser degree) computed tomography (CT) images. Both of these types of imaging modalities are used to view the structure of the tissue; this is opposed to functional MR images (fMRI) or positron emission tomography (PET) scans which image blood flow activity and metabolic activity, respectively.
For people not acquainted with medical images at all, note that medical image statistics are different from natural image statistics. For example, a mammography image looks nothing like any picture that a human would take with their smart phone. This is obvious of course; however, I think it is important to have this in mind when designing networks and working with the data to make some sort of machine learning (ML) algorithm. That is not to say that using common networks or transfer learning from domains outside medical imaging wonβt work; it is only to say that knowing the characteristics of common issues regarding medical imaging will help you debug your algorithm. Iβll discuss specific examples of these characteristics in the preprocessing section below and show ways to reduce the impact of some of these unique problems.
Iβm not going to go into much detail about the intricacies of structural MR imaging. A good place to start for more in-depth details of MR is this website, which goes into depth regarding any topic that an ML practitioner working with MR would care about. Iβll note that there are many different types of MR images that an MR scanner can produce. For instance, there are T1-weighted, T2-weighted, PD-weighted, FLuid-Attenuated Inversion Recovery (FLAIR), among others. To make things more complicated, there are sub-types of those types of images (e.g., T1-weighted images come in the flavors: MPRAGE, SPGR, etc.). Depending on your task, this information may be extremely useful because of the unique characteristics of each of these types and sub-types of images. The reason for all these different types of images is because MR scanners are flexible machines that can be programmed to collect different information according to different pulse sequences. The upshot is that all of these images are not just redundant information; they contain useful and unique information regarding clinical markers that radiologists (or us as image processors) care about. Again, Iβll discuss more details regarding unique aspects of MR in the preprocessing section.
While there is contrast and non-contrast CT, there are not as many varieties of images that can be created with a CT scanner. Vaguely, the CT scanner shoots high-energy photons through you whose energy is calculated via a detector on the other side of your body which the photons hit. When images like this are taken from a variety of angles, we can use our knowledge of the geometry at which the images were acquired to reconstruct the image into a 3D volume. The physical representation of the energy lets us map the found intensity values to a standard scale which also simplifies our life and is discussed more in the preprocessing section. I should note that while MR is good at soft-tissue contrast (e.g., the ability to discern between gray-matter and white-matter in the brain), CT has somewhat poor soft-tissue contrast. See the below head scans from an MR image and a CT image as an example, noting the contrast between the grey-matter (along the outside of the brain) and white-matter (the brighter tissue interior to the grey-matter) as well as the general noise level present in the brain for both images.
Some of the reasons that MR scans are not always used are: 1) some people canβt due to a variety of reasons (e.g., no access, certain types of metal implants, etc.), 2) MR scans take a relatively long time compared to CT scans and 3) radiologists are interested in the particular measurements that CT can provide (e.g., looking at bone structure). Now that we have a basic understanding of the data and some of the intricacies of the imaging modalities, letβs discuss some datasets.
Labeled data is somewhat sparse for medical images because radiologists are expensive, hospitals are concerned about lawsuits, and researchers are (often overly) protective of their data. As a result, there is not an ImageNet-equivalent in MR or CT. However, there are many commonly used datasets depending on the application domain. Since I mostly work with brain MR images, Iβll supply a small list of easily accessible datasets for MR and CT (brain) images along with the data format in parenthesis at the end of the bullet:
Brainweb: Simulated normal and MS brains with tissue/lesion segmentations (MINC)
Kirby 21: Set of 21 healthy patients scanned twice (NIfTI)
IXI dataset: Set of 600 healthy subject scans (NIfTI)
Qure.ai CT head scan data: Set of 491 head CT scans with pathology [no segmentation, but radiology report] (DICOM)
Here is a list of not so easy to download (but very useful) datasets.
BraTS 2018 Brain Tumor data: Large set of patients with brain tumors along with the tumor segmentation (mha)
ISBI 2015 Multiple Sclerosis Challenge data: Set of 20 patients with multiple sclerosis (MS) [only 5 have lesion segmentations] (NIfTI)
I have not worked with the set of datasets below, but I know people who have and am including them for completeness.
OASIS
Low Dose CT
fastMRI
ADNI
Another place to look for datasets is in OpenNeuro which is a repository for researchers to host their brain imaging datasets; it mostly consists of fMRI from what I can tell. If your passion lies somewhere besides MR and CT brain images, then Iβm unfortunately not a great resource. My first guess would be to look at the βgrand challengesβ listed here and see if it is possible to gain access to the data.
Not to bury the lede too much, but perhaps the easiest way to get access to some of the above data is through this website. Iβm not sure that everything is sanctioned to be on there, which is why I have delayed to bring this up.
The amount of data wrangling and preprocessing required to work with MR and CT can be considerable. Iβll outline the bare necessities below.
The first thing to consider is how to load the images into python. The simplest route is to use nibabel. Then you can simply use
import nibabel as nibdata = nib.load('mydata.nii.gz').get_data()
to get a numpy array containing the data inside the mydata.nii.gz file. Note that Iβll refer to the indices of this 3D volume as a voxel which is the 3D-equivalent of a pixel for a 2D image. For work with brain images at least, Iβd recommend always converting the files to NIfTI (which corresponds to the .nii or .nii.gz extension). I find converting everything to NIfTI first makes my life easier since I can assume all input images are of type NIfTI. Here is a tool to convert DICOM to NIfTI, here is a script to convert MHA to NIfTI and here is a script to convert PAR/REC files to NIfTI. There are more file formats that youβll probably need to work with, and you can use some of those scripts as inspiration to convert those file types.
Weβll first outline resampling, bias-field correction and registration which are staples of any medical image analysis. For these preprocessing steps, Iβd recommend ANTs and specifically the ANTsPy variety (assuming you are coming from a python background). ANTs is actively maintained and has reliable tools to solve all of these (and many more) problems. Unfortunately, ANTsPy is not always easy to install, but I believe work is being done on it to solve some of the issues and once you are up and running with it you can access most of the tools ANTs offers natively from python. In particular, it supports the resampling, bias-field correction and registration preprocessing steps Iβll be discussing next.
As with natural images, MR and CT images do not have a standard resolution or standard image size. Iβd argue that this fact is of greater importance in MR and CT though and must be considered for optimal ML performance. Consider the following: you train a 3D convolutional neural network with data acquired at 1x1x3 mm3 resolution and then you input an image into the network with 1x1x1 mm3. I would expect the result to be sub-optimal since the convolutional kernels will not be using the same spatial information. This is debatable and I havenβt examined the problem closely, but the non-standard resolution is something to keep in mind if you run into problems at test time. We can naively address the non-standard resolution problem by resampling the image to a desired, standard resolution (with cubic B-splines, of course, for the best quality).
For many applications, both MR and CT often require a process called registration in order to align objects across a set of images for direct comparison. Why would we want to do this? Letβs say you want to learn a function that takes an MR image and outputs an estimate of what the CT image would look like. If you have paired data (that is, an MR and CT image from the same patient), then a simple way of approaching this problem would be to learn the voxel-wise map between the image intensities. However, if the anatomy is not aligned in the image space, then we cannot learn this map in a supervised way. We solve this problem by registering the images and, in fact, we examine this problem in the experiment section.
The next two problems (described in the next two paragraphs) are specific to MR. First is that we have inhomogeneous image intensities due to the scanner in MR images. Since this inhomogeneity is not a biological feature, we generally want to remove it and we do so with a process referred to as bias-field correction (Iβll discuss one solution in the experiment section).
Another issue in MR are inconsistent tissue intensities across different MR scanners. While CT images have a standard intensity scale (see Hounsfield units), we are not so lucky with MR images. MR images absolutely do not have a standard scale, and the impact on algorithm performance can be quite large if not accounted for in preprocessing. See the images below for an example where we plot the histograms of a set of T1-weighted MR images without any intensity normalization applied (see the image with βRawβ in the title). This variation is due to effects caused by the scanner and not due to the biology, which is the thing we generally care about.
There are a litany of intensity normalization techniques that attempt to remove this scanner variation (several of which I have collected in this repository called intensity-normalization). The techniques range from the very simple (e.g., simple standardization which Iβll refer to as z-score normalization) to the fairly technical (e.g., RAVEL). For neuroimaging, a good combination of speed and quality can be found in the Fuzzy C-Means (FCM) normalization technique which creates a rough tissue-class segmentation between the white-matter (WM), grey-matter and cerebrospinal fluid based on the T1-weighted image. The WM segmentation mask is then used to calculate the mean of the WM in the image which is set to some user-defined constant. This normalization technique seems to almost always produce the desired result in brain images. If you are not working on brain images, then you may want to look at either the NyuΜl & Udupa method or simple z-score normalization. All of these normalization methods are available as command-line interfaces (or importable modules) in the intensity-normalization repository.
The last preprocessing step weβll consider is specific to brain images. In brain images, we generally only care about the brain and not necessarily the tissues outside of brain (e.g., the skull, fat and skin surrounding the brain). Furthermore, this extraneous tissue can complicate the learning procedure and trip up classification, segmentation, or regression tasks. To get around this we can use skull-stripping algorithms to create a mask of the brain and zero out the background. The simplest way to go about this (in MR) β with reasonable results β is with ROBEX: a command-line tool that generally does a good job at extracting the brain from the image. Iβve seen it fail a few times on some data containing large pathologies or imaging artifacts, but other than that it is usually good enough for most machine learning tasks. For what itβs worth, Iβd try to avoid skull-stripping your data since it is just another point of possible failure in your preprocessing routine, but sometimes it substantially helps.
Since MR and CT images arenβt standard like JPEG, your computer doesnβt have a native way to display it. If you want to visualize your data, take a look at MIPAV for non-DICOM images (e.g., NIfTI) and Horos for DICOM images. It is always good to look at your data, especially after preprocessing so we can verify that everything looks reasonable. For instance, perhaps the registration failed (it often does) or perhaps the skull-stripping failed (again, it often occurs). If you pipe your crappy data into your ML algorithm, youβre probably going to get crappy output and youβll waste a lot of time doing unnecessary debugging. So be kind to yourself and examine the data.
While deep neural networks applied to MR and CT are increasingly moving to 3D models, there has been good success with 2D models. If you have limited memory on your GPU or you have very limited training data, you may want to use a 2D network to squeeze the most performance out of the network. If you use a 3D network, you will quickly run into memory issues when passing a full image or patches through the network.
If you decide a 2D network is the way to go for your application (a reasonable choice), youβll need to figure out/design a data loader to handle this. After fussing around with complicated data loaders that take the 3D image to a 2D image patch or slice for a while, I realized that that was all an unnecessary burden that made it harder to use pre-built data loader/data augmentation tools that aid in training. Thus my recommended solution to this problem is to simply convert the 3D volumes to 2D images. Since the original volumes are floating point numbers, I went with the TIFF image format which supports such types. Here is a command-line script which takes a directory of NIfTI images and creates a directory of corresponding 2D TIFF images (with some options to create slices based on axis and to only create slices from a portion of the image in order to avoid background slices).
In the following section, Iβll build a deep neural network with 3D convolutional layers. Iβm doing this as opposed to using 2D convolutional layers because β once you convert the 3D volume to 2D images like TIFF β you can basically just use any 2D architecture you have lying around substituting the head for the appropriate application. Since the 3D problem is slightly more tricky to approach, Iβll dig into it below.
*** If you are just coming to this blog post (after 05/07/20), note that the fastai package has changed significantly and the code below may not work as expected. However, the code examples and general experimental setup below should still be useful for learning purposes. For what itβs worth, Iβd recommend using PyTorch over fastai for future deep learning projects. If you want NIfTI support in PyTorch, I have an actively maintained package which has working code examples and importable functions here. ***
In this section, Iβll outline the steps required to train a 3D convolutional neural network for a MR-to-MR synthesis task using pytorch and fastai. If you just want to look at the code, then there is also a notebook which contains most of the experiment (excluding preprocessing) here.
The setup is as follows: weβll train a very small resnet to take an entire 3D volume from one MR contrast to another MR contrast; weβll be learning the transform to map T1-weighted images to FLAIR images. This task is called MR image synthesis and weβll refer to the network as a synthesis network. There are a variety of applications for this type of synthesis, but motivation for this problem is mostly that: MR scan time is limited, so not all contrasts can be collected. But we want to eat our cake and have it too, and we sometimes want those uncollected contrasts for image processing purposes. Thus we create some fake data using the data that actually was collected, where the fake data will be the result of our synthesis network.
In this experiment, Iβll be using 11 and 7 images as training and validation, respectively, from the Kirby 21 dataset. All images have been resampled to 1x1x1 mm3, bias-field corrected using N4, and the FLAIR images have been (affine) registered to the T1-weighted images using ANTsPy. Look here and here for the actual code I used to do the preprocessing (both are available as command-line interfaces when the intensity-normalization package is installed along with ANTsPy). Finally, all the images were individually z-score normalized using the entire image.
Now that we have motivated the problem somewhat and talked about the data we will use, letβs get to the code. The code block below defines some necessary constructs to work with fastai, specifically to use the data_block API.
There is nothing particular to remark on here, except that once you figure out how to setup these types of structures, they are quite convenient (see the ItemList tutorial for more details). Note that not all functionality is supported with the current setup β I stripped it down to make it as simple as possible β but itβll get the job done. Iβll show how this creates the training and validation dataloaders below. First, letβs define a preprocessing transform:
Why am I defining this odd cropping function? The reason is two-fold. The first reason is that the neck is not present in the FLAIR images but is present in the T1-weighted images. I donβt want the network to learn to take tissue to zero, so Iβm removing that part of the data by only using the data in the 20β80 percent range along the axis corresponding to the axial plane. The second reason is that I can fit twice as many samples into a batch (that means a batch size of 2). The reason for the small batch size is that, like I previously mentioned, 3D networks with large images are memory-intensive. Why no other data augmentation? Unfortunately, 3D transforms are not natively supported with pytorch or fastai so Iβd have to incorporate my own and I am not doing this for simplicity. Now letβs use the data_block API of fastai to create the training and validation dataloaders:
You can see the notebook for more details, but essentially I have the T1-weighted images in one directory with train, valid, test subdirectories and a parallel directory with the FLAIR images. The get_y_fn function grabs the FLAIR image corresponding to the source T1-weighted image. Look here for more in-depth explanation of the remaining commands. Note that the (tfms,tfms) means that I am applying the previously defined crop to both the training and validation set. Applying that transform to the validation set isnβt ideal, but is required because of memory-constraints. Now letβs create some 3D convolutional and residual block layers which weβll use to define our model:
Iβm closely following the definition of the 2D convolutional and residual block layers as defined in the fastai repository. As a side note, I left the spectral normalization and weight normalization routines in the conv3d definition, but disappointingly received worse results with those methods than when using batch norm (and Iβm still not sure whether batch norm is applied before or after the activation). Now letβs define our model using the above layers:
Here I have just defined the very small resnet model. Why so few layers? I am using as large of a network as my GPU can contain in memory. The creation of many channels with the entire 3D volume and the residual connections are burdens on the GPU memory. The only other thing of possible intrigue is that I use a 1x1x1 kernel at the end, which empirically produces crisper images (and I think is fairly standard). As a note, I realize that I should have removed the activation from the final layer; however, it is not a problem because I am z-score normalizing (i.e., mean subtracting and dividing by the standard deviation) the images with their backgrounds. The backgrounds, which are approximately zero, take up the vast majority of the volume of the image. Thus the z-score normalization essentially puts the background (corresponding to the mean) at zero, which makes the intensities of the head greater than zero. A fine result for the ReLU. Now letβs train this network:
Again fairly normal. Mean square error is used because we want each voxel intensity in our source T1-weighted image to match the voxel intensity of the corresponding target FLAIR image. We use lr_find to help us pick a larger learning rate (as described here) for faster training, in addition to using the one-cycle policy. I always collect my training and validation data into a CSV file to look at how the network is converging, especially on machines where launching a jupyter notebook is a pain. I picked 100 epochs because I ran this a couple times and did not notice a great amount performance gain with more epochs.
After training completes, we input an entire image (not seen in either training or validation) into the network. An example is shown in below figure, where the synthesis result is the right-most image (with the title βSynβ).
While the above figure could have been had better window/level settings for better comparison, we see that the T1-weighted image does take on many of the characteristics of the true FLAIR image. Most notably, inside the brain, we see that the white-matter becomes less bright than the grey-matter while the cerebrospinal fluid remains dark. The noise characteristics are not the same though and there are some bright spots in the true FLAIR that are not captured in the synthesized image.
This result is not state-of-the-art by any means, but itβs interesting to see that we can learn an approximate transform with such an incredibly small dataset, no data augmentation, and a very small network. This network would assuredly be better with more data, data augmentation and a larger network, but this is just a simple, pedagogical toy example. I should note that unless you have a particularly large GPU (and contradicting my last statement), you may not be able to train this network with the full images. Youβll probably have to use either 3D patches or 2D slices (or 2D patches).
Hopefully this post provided you with a starting point for applying deep learning to MR and CT images with fastai. Like most machine learning tasks, there is a considerable amount of domain-specific knowledge, data-wrangling and preprocessing that is required to get started, but once you have this under your belt, it is fairly easy to get up-and-running with training a network with pytorch and fastai. Where to go from here? Iβd download a dataset from one of the links I posted in the Datasets section and try to do something similar to what I showed above, or even just try to recreate what I did. If you can get to that stage, youβll be in a comfortable place to apply deep learning to other problems in MR and CT.
I should note that there is work being done to create standard code bases from which you can apply deep learning to MR and CT images. The two that I am aware of are NiftyNet and medicaltorch. NiftyNet abstracts away most of the neural network design and data handling, so that the user only has to call some command-line interfaces by which to download a pre-trained network, fine-tune it, and do whatever. So if that is good enough for your needs, then go right ahead; it seems like a great tool and has some pre-trained networks available. medicaltorch provides some dataloaders and generic deep learning models with medical images in pytorch. I have not tested either extensively, so I cannot comment on their utility.
If you donβt like python, there is neuroconductor in R or NIfTI.jl and Flux.jl packages in Julia which can read NIfTI images and build neural networks, respectively. There are countless other relevant software packages, but those are the ones the first come to mind and that Iβve worked with.
As a final note, if you have luck creating a nice application for MR or CT make sure to share your work! Write a paper/blog post, put it up on a forum, share the network weights. It would be great to see more people apply deep learning techniques to this domain and push the boundary of the field where possible. Best of luck.
|
[
{
"code": null,
"e": 771,
"s": 171,
"text": "Getting started with applying deep learning to magnetic resonance (MR) or computed tomography (CT) images is not straightforward; finding appropriate data sets, preprocessing the data, and creating the data loader structures necessary to do the work is a pain to figure out. In this post I hope to alleviate some of that pain for newcomers. To do so, Iβll link to several freely-available datasets, review some common/necessary preprocessing techniques specific to MR and CT, and show how to use the fastai library to load (structural) MR images and train a deep neural network for a synthesis task."
},
{
"code": null,
"e": 1331,
"s": 771,
"text": "Before we get into the meat and bones of this post, it will be useful to do a quick overview of the medical images that weβll be talking about and some idiosyncrasies of the types of images in discussion. Iβll only be talking about structural MR images and (to a lesser degree) computed tomography (CT) images. Both of these types of imaging modalities are used to view the structure of the tissue; this is opposed to functional MR images (fMRI) or positron emission tomography (PET) scans which image blood flow activity and metabolic activity, respectively."
},
{
"code": null,
"e": 2168,
"s": 1331,
"text": "For people not acquainted with medical images at all, note that medical image statistics are different from natural image statistics. For example, a mammography image looks nothing like any picture that a human would take with their smart phone. This is obvious of course; however, I think it is important to have this in mind when designing networks and working with the data to make some sort of machine learning (ML) algorithm. That is not to say that using common networks or transfer learning from domains outside medical imaging wonβt work; it is only to say that knowing the characteristics of common issues regarding medical imaging will help you debug your algorithm. Iβll discuss specific examples of these characteristics in the preprocessing section below and show ways to reduce the impact of some of these unique problems."
},
{
"code": null,
"e": 3423,
"s": 2168,
"text": "Iβm not going to go into much detail about the intricacies of structural MR imaging. A good place to start for more in-depth details of MR is this website, which goes into depth regarding any topic that an ML practitioner working with MR would care about. Iβll note that there are many different types of MR images that an MR scanner can produce. For instance, there are T1-weighted, T2-weighted, PD-weighted, FLuid-Attenuated Inversion Recovery (FLAIR), among others. To make things more complicated, there are sub-types of those types of images (e.g., T1-weighted images come in the flavors: MPRAGE, SPGR, etc.). Depending on your task, this information may be extremely useful because of the unique characteristics of each of these types and sub-types of images. The reason for all these different types of images is because MR scanners are flexible machines that can be programmed to collect different information according to different pulse sequences. The upshot is that all of these images are not just redundant information; they contain useful and unique information regarding clinical markers that radiologists (or us as image processors) care about. Again, Iβll discuss more details regarding unique aspects of MR in the preprocessing section."
},
{
"code": null,
"e": 4542,
"s": 3423,
"text": "While there is contrast and non-contrast CT, there are not as many varieties of images that can be created with a CT scanner. Vaguely, the CT scanner shoots high-energy photons through you whose energy is calculated via a detector on the other side of your body which the photons hit. When images like this are taken from a variety of angles, we can use our knowledge of the geometry at which the images were acquired to reconstruct the image into a 3D volume. The physical representation of the energy lets us map the found intensity values to a standard scale which also simplifies our life and is discussed more in the preprocessing section. I should note that while MR is good at soft-tissue contrast (e.g., the ability to discern between gray-matter and white-matter in the brain), CT has somewhat poor soft-tissue contrast. See the below head scans from an MR image and a CT image as an example, noting the contrast between the grey-matter (along the outside of the brain) and white-matter (the brighter tissue interior to the grey-matter) as well as the general noise level present in the brain for both images."
},
{
"code": null,
"e": 5025,
"s": 4542,
"text": "Some of the reasons that MR scans are not always used are: 1) some people canβt due to a variety of reasons (e.g., no access, certain types of metal implants, etc.), 2) MR scans take a relatively long time compared to CT scans and 3) radiologists are interested in the particular measurements that CT can provide (e.g., looking at bone structure). Now that we have a basic understanding of the data and some of the intricacies of the imaging modalities, letβs discuss some datasets."
},
{
"code": null,
"e": 5553,
"s": 5025,
"text": "Labeled data is somewhat sparse for medical images because radiologists are expensive, hospitals are concerned about lawsuits, and researchers are (often overly) protective of their data. As a result, there is not an ImageNet-equivalent in MR or CT. However, there are many commonly used datasets depending on the application domain. Since I mostly work with brain MR images, Iβll supply a small list of easily accessible datasets for MR and CT (brain) images along with the data format in parenthesis at the end of the bullet:"
},
{
"code": null,
"e": 5634,
"s": 5553,
"text": "Brainweb: Simulated normal and MS brains with tissue/lesion segmentations (MINC)"
},
{
"code": null,
"e": 5693,
"s": 5634,
"text": "Kirby 21: Set of 21 healthy patients scanned twice (NIfTI)"
},
{
"code": null,
"e": 5747,
"s": 5693,
"text": "IXI dataset: Set of 600 healthy subject scans (NIfTI)"
},
{
"code": null,
"e": 5862,
"s": 5747,
"text": "Qure.ai CT head scan data: Set of 491 head CT scans with pathology [no segmentation, but radiology report] (DICOM)"
},
{
"code": null,
"e": 5932,
"s": 5862,
"text": "Here is a list of not so easy to download (but very useful) datasets."
},
{
"code": null,
"e": 6041,
"s": 5932,
"text": "BraTS 2018 Brain Tumor data: Large set of patients with brain tumors along with the tumor segmentation (mha)"
},
{
"code": null,
"e": 6177,
"s": 6041,
"text": "ISBI 2015 Multiple Sclerosis Challenge data: Set of 20 patients with multiple sclerosis (MS) [only 5 have lesion segmentations] (NIfTI)"
},
{
"code": null,
"e": 6294,
"s": 6177,
"text": "I have not worked with the set of datasets below, but I know people who have and am including them for completeness."
},
{
"code": null,
"e": 6300,
"s": 6294,
"text": "OASIS"
},
{
"code": null,
"e": 6312,
"s": 6300,
"text": "Low Dose CT"
},
{
"code": null,
"e": 6320,
"s": 6312,
"text": "fastMRI"
},
{
"code": null,
"e": 6325,
"s": 6320,
"text": "ADNI"
},
{
"code": null,
"e": 6733,
"s": 6325,
"text": "Another place to look for datasets is in OpenNeuro which is a repository for researchers to host their brain imaging datasets; it mostly consists of fMRI from what I can tell. If your passion lies somewhere besides MR and CT brain images, then Iβm unfortunately not a great resource. My first guess would be to look at the βgrand challengesβ listed here and see if it is possible to gain access to the data."
},
{
"code": null,
"e": 6962,
"s": 6733,
"text": "Not to bury the lede too much, but perhaps the easiest way to get access to some of the above data is through this website. Iβm not sure that everything is sanctioned to be on there, which is why I have delayed to bring this up."
},
{
"code": null,
"e": 7103,
"s": 6962,
"text": "The amount of data wrangling and preprocessing required to work with MR and CT can be considerable. Iβll outline the bare necessities below."
},
{
"code": null,
"e": 7232,
"s": 7103,
"text": "The first thing to consider is how to load the images into python. The simplest route is to use nibabel. Then you can simply use"
},
{
"code": null,
"e": 7297,
"s": 7232,
"text": "import nibabel as nibdata = nib.load('mydata.nii.gz').get_data()"
},
{
"code": null,
"e": 8039,
"s": 7297,
"text": "to get a numpy array containing the data inside the mydata.nii.gz file. Note that Iβll refer to the indices of this 3D volume as a voxel which is the 3D-equivalent of a pixel for a 2D image. For work with brain images at least, Iβd recommend always converting the files to NIfTI (which corresponds to the .nii or .nii.gz extension). I find converting everything to NIfTI first makes my life easier since I can assume all input images are of type NIfTI. Here is a tool to convert DICOM to NIfTI, here is a script to convert MHA to NIfTI and here is a script to convert PAR/REC files to NIfTI. There are more file formats that youβll probably need to work with, and you can use some of those scripts as inspiration to convert those file types."
},
{
"code": null,
"e": 8750,
"s": 8039,
"text": "Weβll first outline resampling, bias-field correction and registration which are staples of any medical image analysis. For these preprocessing steps, Iβd recommend ANTs and specifically the ANTsPy variety (assuming you are coming from a python background). ANTs is actively maintained and has reliable tools to solve all of these (and many more) problems. Unfortunately, ANTsPy is not always easy to install, but I believe work is being done on it to solve some of the issues and once you are up and running with it you can access most of the tools ANTs offers natively from python. In particular, it supports the resampling, bias-field correction and registration preprocessing steps Iβll be discussing next."
},
{
"code": null,
"e": 9602,
"s": 8750,
"text": "As with natural images, MR and CT images do not have a standard resolution or standard image size. Iβd argue that this fact is of greater importance in MR and CT though and must be considered for optimal ML performance. Consider the following: you train a 3D convolutional neural network with data acquired at 1x1x3 mm3 resolution and then you input an image into the network with 1x1x1 mm3. I would expect the result to be sub-optimal since the convolutional kernels will not be using the same spatial information. This is debatable and I havenβt examined the problem closely, but the non-standard resolution is something to keep in mind if you run into problems at test time. We can naively address the non-standard resolution problem by resampling the image to a desired, standard resolution (with cubic B-splines, of course, for the best quality)."
},
{
"code": null,
"e": 10324,
"s": 9602,
"text": "For many applications, both MR and CT often require a process called registration in order to align objects across a set of images for direct comparison. Why would we want to do this? Letβs say you want to learn a function that takes an MR image and outputs an estimate of what the CT image would look like. If you have paired data (that is, an MR and CT image from the same patient), then a simple way of approaching this problem would be to learn the voxel-wise map between the image intensities. However, if the anatomy is not aligned in the image space, then we cannot learn this map in a supervised way. We solve this problem by registering the images and, in fact, we examine this problem in the experiment section."
},
{
"code": null,
"e": 10697,
"s": 10324,
"text": "The next two problems (described in the next two paragraphs) are specific to MR. First is that we have inhomogeneous image intensities due to the scanner in MR images. Since this inhomogeneity is not a biological feature, we generally want to remove it and we do so with a process referred to as bias-field correction (Iβll discuss one solution in the experiment section)."
},
{
"code": null,
"e": 11351,
"s": 10697,
"text": "Another issue in MR are inconsistent tissue intensities across different MR scanners. While CT images have a standard intensity scale (see Hounsfield units), we are not so lucky with MR images. MR images absolutely do not have a standard scale, and the impact on algorithm performance can be quite large if not accounted for in preprocessing. See the images below for an example where we plot the histograms of a set of T1-weighted MR images without any intensity normalization applied (see the image with βRawβ in the title). This variation is due to effects caused by the scanner and not due to the biology, which is the thing we generally care about."
},
{
"code": null,
"e": 12467,
"s": 11351,
"text": "There are a litany of intensity normalization techniques that attempt to remove this scanner variation (several of which I have collected in this repository called intensity-normalization). The techniques range from the very simple (e.g., simple standardization which Iβll refer to as z-score normalization) to the fairly technical (e.g., RAVEL). For neuroimaging, a good combination of speed and quality can be found in the Fuzzy C-Means (FCM) normalization technique which creates a rough tissue-class segmentation between the white-matter (WM), grey-matter and cerebrospinal fluid based on the T1-weighted image. The WM segmentation mask is then used to calculate the mean of the WM in the image which is set to some user-defined constant. This normalization technique seems to almost always produce the desired result in brain images. If you are not working on brain images, then you may want to look at either the NyuΜl & Udupa method or simple z-score normalization. All of these normalization methods are available as command-line interfaces (or importable modules) in the intensity-normalization repository."
},
{
"code": null,
"e": 13485,
"s": 12467,
"text": "The last preprocessing step weβll consider is specific to brain images. In brain images, we generally only care about the brain and not necessarily the tissues outside of brain (e.g., the skull, fat and skin surrounding the brain). Furthermore, this extraneous tissue can complicate the learning procedure and trip up classification, segmentation, or regression tasks. To get around this we can use skull-stripping algorithms to create a mask of the brain and zero out the background. The simplest way to go about this (in MR) β with reasonable results β is with ROBEX: a command-line tool that generally does a good job at extracting the brain from the image. Iβve seen it fail a few times on some data containing large pathologies or imaging artifacts, but other than that it is usually good enough for most machine learning tasks. For what itβs worth, Iβd try to avoid skull-stripping your data since it is just another point of possible failure in your preprocessing routine, but sometimes it substantially helps."
},
{
"code": null,
"e": 14159,
"s": 13485,
"text": "Since MR and CT images arenβt standard like JPEG, your computer doesnβt have a native way to display it. If you want to visualize your data, take a look at MIPAV for non-DICOM images (e.g., NIfTI) and Horos for DICOM images. It is always good to look at your data, especially after preprocessing so we can verify that everything looks reasonable. For instance, perhaps the registration failed (it often does) or perhaps the skull-stripping failed (again, it often occurs). If you pipe your crappy data into your ML algorithm, youβre probably going to get crappy output and youβll waste a lot of time doing unnecessary debugging. So be kind to yourself and examine the data."
},
{
"code": null,
"e": 14576,
"s": 14159,
"text": "While deep neural networks applied to MR and CT are increasingly moving to 3D models, there has been good success with 2D models. If you have limited memory on your GPU or you have very limited training data, you may want to use a 2D network to squeeze the most performance out of the network. If you use a 3D network, you will quickly run into memory issues when passing a full image or patches through the network."
},
{
"code": null,
"e": 15468,
"s": 14576,
"text": "If you decide a 2D network is the way to go for your application (a reasonable choice), youβll need to figure out/design a data loader to handle this. After fussing around with complicated data loaders that take the 3D image to a 2D image patch or slice for a while, I realized that that was all an unnecessary burden that made it harder to use pre-built data loader/data augmentation tools that aid in training. Thus my recommended solution to this problem is to simply convert the 3D volumes to 2D images. Since the original volumes are floating point numbers, I went with the TIFF image format which supports such types. Here is a command-line script which takes a directory of NIfTI images and creates a directory of corresponding 2D TIFF images (with some options to create slices based on axis and to only create slices from a portion of the image in order to avoid background slices)."
},
{
"code": null,
"e": 15888,
"s": 15468,
"text": "In the following section, Iβll build a deep neural network with 3D convolutional layers. Iβm doing this as opposed to using 2D convolutional layers because β once you convert the 3D volume to 2D images like TIFF β you can basically just use any 2D architecture you have lying around substituting the head for the appropriate application. Since the 3D problem is slightly more tricky to approach, Iβll dig into it below."
},
{
"code": null,
"e": 16400,
"s": 15888,
"text": "*** If you are just coming to this blog post (after 05/07/20), note that the fastai package has changed significantly and the code below may not work as expected. However, the code examples and general experimental setup below should still be useful for learning purposes. For what itβs worth, Iβd recommend using PyTorch over fastai for future deep learning projects. If you want NIfTI support in PyTorch, I have an actively maintained package which has working code examples and importable functions here. ***"
},
{
"code": null,
"e": 16686,
"s": 16400,
"text": "In this section, Iβll outline the steps required to train a 3D convolutional neural network for a MR-to-MR synthesis task using pytorch and fastai. If you just want to look at the code, then there is also a notebook which contains most of the experiment (excluding preprocessing) here."
},
{
"code": null,
"e": 17426,
"s": 16686,
"text": "The setup is as follows: weβll train a very small resnet to take an entire 3D volume from one MR contrast to another MR contrast; weβll be learning the transform to map T1-weighted images to FLAIR images. This task is called MR image synthesis and weβll refer to the network as a synthesis network. There are a variety of applications for this type of synthesis, but motivation for this problem is mostly that: MR scan time is limited, so not all contrasts can be collected. But we want to eat our cake and have it too, and we sometimes want those uncollected contrasts for image processing purposes. Thus we create some fake data using the data that actually was collected, where the fake data will be the result of our synthesis network."
},
{
"code": null,
"e": 17988,
"s": 17426,
"text": "In this experiment, Iβll be using 11 and 7 images as training and validation, respectively, from the Kirby 21 dataset. All images have been resampled to 1x1x1 mm3, bias-field corrected using N4, and the FLAIR images have been (affine) registered to the T1-weighted images using ANTsPy. Look here and here for the actual code I used to do the preprocessing (both are available as command-line interfaces when the intensity-normalization package is installed along with ANTsPy). Finally, all the images were individually z-score normalized using the entire image."
},
{
"code": null,
"e": 18214,
"s": 17988,
"text": "Now that we have motivated the problem somewhat and talked about the data we will use, letβs get to the code. The code block below defines some necessary constructs to work with fastai, specifically to use the data_block API."
},
{
"code": null,
"e": 18678,
"s": 18214,
"text": "There is nothing particular to remark on here, except that once you figure out how to setup these types of structures, they are quite convenient (see the ItemList tutorial for more details). Note that not all functionality is supported with the current setup β I stripped it down to make it as simple as possible β but itβll get the job done. Iβll show how this creates the training and validation dataloaders below. First, letβs define a preprocessing transform:"
},
{
"code": null,
"e": 19562,
"s": 18678,
"text": "Why am I defining this odd cropping function? The reason is two-fold. The first reason is that the neck is not present in the FLAIR images but is present in the T1-weighted images. I donβt want the network to learn to take tissue to zero, so Iβm removing that part of the data by only using the data in the 20β80 percent range along the axis corresponding to the axial plane. The second reason is that I can fit twice as many samples into a batch (that means a batch size of 2). The reason for the small batch size is that, like I previously mentioned, 3D networks with large images are memory-intensive. Why no other data augmentation? Unfortunately, 3D transforms are not natively supported with pytorch or fastai so Iβd have to incorporate my own and I am not doing this for simplicity. Now letβs use the data_block API of fastai to create the training and validation dataloaders:"
},
{
"code": null,
"e": 20241,
"s": 19562,
"text": "You can see the notebook for more details, but essentially I have the T1-weighted images in one directory with train, valid, test subdirectories and a parallel directory with the FLAIR images. The get_y_fn function grabs the FLAIR image corresponding to the source T1-weighted image. Look here for more in-depth explanation of the remaining commands. Note that the (tfms,tfms) means that I am applying the previously defined crop to both the training and validation set. Applying that transform to the validation set isnβt ideal, but is required because of memory-constraints. Now letβs create some 3D convolutional and residual block layers which weβll use to define our model:"
},
{
"code": null,
"e": 20702,
"s": 20241,
"text": "Iβm closely following the definition of the 2D convolutional and residual block layers as defined in the fastai repository. As a side note, I left the spectral normalization and weight normalization routines in the conv3d definition, but disappointingly received worse results with those methods than when using batch norm (and Iβm still not sure whether batch norm is applied before or after the activation). Now letβs define our model using the above layers:"
},
{
"code": null,
"e": 21680,
"s": 20702,
"text": "Here I have just defined the very small resnet model. Why so few layers? I am using as large of a network as my GPU can contain in memory. The creation of many channels with the entire 3D volume and the residual connections are burdens on the GPU memory. The only other thing of possible intrigue is that I use a 1x1x1 kernel at the end, which empirically produces crisper images (and I think is fairly standard). As a note, I realize that I should have removed the activation from the final layer; however, it is not a problem because I am z-score normalizing (i.e., mean subtracting and dividing by the standard deviation) the images with their backgrounds. The backgrounds, which are approximately zero, take up the vast majority of the volume of the image. Thus the z-score normalization essentially puts the background (corresponding to the mean) at zero, which makes the intensities of the head greater than zero. A fine result for the ReLU. Now letβs train this network:"
},
{
"code": null,
"e": 22303,
"s": 21680,
"text": "Again fairly normal. Mean square error is used because we want each voxel intensity in our source T1-weighted image to match the voxel intensity of the corresponding target FLAIR image. We use lr_find to help us pick a larger learning rate (as described here) for faster training, in addition to using the one-cycle policy. I always collect my training and validation data into a CSV file to look at how the network is converging, especially on machines where launching a jupyter notebook is a pain. I picked 100 epochs because I ran this a couple times and did not notice a great amount performance gain with more epochs."
},
{
"code": null,
"e": 22528,
"s": 22303,
"text": "After training completes, we input an entire image (not seen in either training or validation) into the network. An example is shown in below figure, where the synthesis result is the right-most image (with the title βSynβ)."
},
{
"code": null,
"e": 23017,
"s": 22528,
"text": "While the above figure could have been had better window/level settings for better comparison, we see that the T1-weighted image does take on many of the characteristics of the true FLAIR image. Most notably, inside the brain, we see that the white-matter becomes less bright than the grey-matter while the cerebrospinal fluid remains dark. The noise characteristics are not the same though and there are some bright spots in the true FLAIR that are not captured in the synthesized image."
},
{
"code": null,
"e": 23611,
"s": 23017,
"text": "This result is not state-of-the-art by any means, but itβs interesting to see that we can learn an approximate transform with such an incredibly small dataset, no data augmentation, and a very small network. This network would assuredly be better with more data, data augmentation and a larger network, but this is just a simple, pedagogical toy example. I should note that unless you have a particularly large GPU (and contradicting my last statement), you may not be able to train this network with the full images. Youβll probably have to use either 3D patches or 2D slices (or 2D patches)."
},
{
"code": null,
"e": 24332,
"s": 23611,
"text": "Hopefully this post provided you with a starting point for applying deep learning to MR and CT images with fastai. Like most machine learning tasks, there is a considerable amount of domain-specific knowledge, data-wrangling and preprocessing that is required to get started, but once you have this under your belt, it is fairly easy to get up-and-running with training a network with pytorch and fastai. Where to go from here? Iβd download a dataset from one of the links I posted in the Datasets section and try to do something similar to what I showed above, or even just try to recreate what I did. If you can get to that stage, youβll be in a comfortable place to apply deep learning to other problems in MR and CT."
},
{
"code": null,
"e": 25054,
"s": 24332,
"text": "I should note that there is work being done to create standard code bases from which you can apply deep learning to MR and CT images. The two that I am aware of are NiftyNet and medicaltorch. NiftyNet abstracts away most of the neural network design and data handling, so that the user only has to call some command-line interfaces by which to download a pre-trained network, fine-tune it, and do whatever. So if that is good enough for your needs, then go right ahead; it seems like a great tool and has some pre-trained networks available. medicaltorch provides some dataloaders and generic deep learning models with medical images in pytorch. I have not tested either extensively, so I cannot comment on their utility."
},
{
"code": null,
"e": 25347,
"s": 25054,
"text": "If you donβt like python, there is neuroconductor in R or NIfTI.jl and Flux.jl packages in Julia which can read NIfTI images and build neural networks, respectively. There are countless other relevant software packages, but those are the ones the first come to mind and that Iβve worked with."
}
] |
CSS Paged Media - @page Rule
|
Paged media differ from continuous media in that the content of the document is split into one or more discrete pages. Paged media includes paper, transparencies, pages that are displayed on computer screens, etc.
The CSS2 standard introduces some basic pagination control features that let authors help the browser figure out how to best print their documents.
The CSS2 page model specifies how a document is formatted within a rectangular area -- the page box -- that has a finite width and height. These features fall into two groups β
CSS2 features that define a particular page layout.
CSS2 features that control the pagination of a document.
The CSS2 defines a "page box", a box of finite dimensions in which content is rendered. The page box is a rectangular region that contains two areas β
The page area β The page area includes the boxes laid out on that page. The edges of the page area act as the initial containing block for layout that occurs between page breaks.
The page area β The page area includes the boxes laid out on that page. The edges of the page area act as the initial containing block for layout that occurs between page breaks.
The margin area β It surrounds the page area.
The margin area β It surrounds the page area.
You can specify the dimensions, orientation, margins, etc., of a page box within an @page rule. The dimensions of the page box are set with the 'size' property. The dimensions of the page area are the dimensions of the page box minus the margin area.
For example, the following @page rule sets the page box size to 8.5 Γ 11 inches and creates '2cm' margin on all sides between the page box edge and the page area β
<style type = "text/css">
<!--
@page { size:8.5in 11in; margin: 2cm }
-->
</style>
You can use the margin, margin-top, margin-bottom, margin-left, and margin-right properties within the @page rule to set margins for your page.
Finally, the marks property is used within the @page rule to create crop and registration marks outside the page box on the target sheet. By default, no marks are printed. You may use one or both of the crop and cross keywords to create crop marks and registration marks, respectively, on the target print page.
The size property specifies the size and orientation of a page box. There are four values which can be used for page size β
auto β The page box will be set to the size and orientation of the target sheet.
auto β The page box will be set to the size and orientation of the target sheet.
landscape β Overrides the target's orientation. The page box is the same size as the target, and the longer sides are horizontal.
landscape β Overrides the target's orientation. The page box is the same size as the target, and the longer sides are horizontal.
portrait β Overrides the target's orientation. The page box is the same size as the target, and the shorter sides are horizontal.
portrait β Overrides the target's orientation. The page box is the same size as the target, and the shorter sides are horizontal.
length β Length values for the 'size' property create an absolute page box. If only one length value is specified, it sets both the width and height of the page box. Percentage values are not allowed for the 'size' property.
length β Length values for the 'size' property create an absolute page box. If only one length value is specified, it sets both the width and height of the page box. Percentage values are not allowed for the 'size' property.
In the following example, the outer edges of the page box will align with the target. The percentage value on the 'margin' property is relative to the target size so if the target sheet dimensions are 21.0cm Γ 29.7cm (i.e., A4), the margins are 2.10cm and 2.97cm.
<style type = "text/css">
<!--
@page {
size: auto; /* auto is the initial value */
margin: 10%;
}
-->
</style>
The following example sets the width of the page box to be 8.5 inches and the height to be 11 inches. The page box in this example requires a target sheet size of 8.5" Γ 11" or larger.
<style type = "text/css">
<!--
@page {
size: 8.5in 11in; /* width height */
}
-->
</style>
Once you create a named page layout, you can use it in your document by adding the page property to a style that is later applied to an element in your document. For example, this style renders all the tables in your document on landscape pages β
<style type = "text/css">
<!--
@page { size : portrait }
@page rotated { size : landscape }
table { page : rotated }
-->
</style>
Due to the above rule, while printing, if the browser encounters a <table> element in your document and the current page layout is the default portrait layout, it starts a new page and prints the table on a landscape page.
When printing double-sided documents, the page boxes on left and right pages should be different. It can be expressed through two CSS pseudo-classes as follows β
<style type = "text/css">
<!--
@page :left {
margin-left: 4cm;
margin-right: 3cm;
}
@page :right {
margin-left: 3cm;
margin-right: 4cm;
}
-->
</style>
You can specify the style for the first page of a document with the :first pseudo-class β
<style type = "text/css">
<!--
@page { margin: 2cm } /* All margins set to 2cm */
@page :first {
margin-top: 10cm /* Top margin on first page 10cm */
}
-->
</style>
Unless you specify otherwise, page breaks occur only when the page format changes or when the content overflows the current page box. To otherwise force or suppress page breaks, use the page-break-before, page-break-after, and page-break-inside properties.
Both the page-break-before and page-break-after accept the auto, always, avoid, left, and right keywords.
The keyword auto is the default, it lets the browser generate page breaks as needed. The keyword always forces a page break before or after the element, while avoid suppresses a page break immediately before or after the element. The left and right keywords force one or two page breaks, so that the element is rendered on a left-hand or right-hand page.
Using pagination properties is quite straightforward. Suppose your document has level-1 headers start new chapters with level-2 headers to denote sections. You'd like each chapter to start on a new, right-hand page, but you don't want section headers to be split across a page break from the subsequent content. You can achieve this using following rule β
<style type = "text/css">
<!--
h1 { page-break-before : right }
h2 { page-break-after : avoid }
-->
</style>
Use only the auto and avoid values with the page-break-inside property. If you prefer that your tables not be broken across pages if possible, you would write the rule β
<style type = "text/css">
<!--
table { page-break-inside : avoid }
-->
</style>
In typographic lingo, orphans are those lines of a paragraph stranded at the bottom of a page due to a page break, while widows are those lines remaining at the top of a page following a page break. Generally, printed pages do not look attractive with single lines of text stranded at the top or bottom. Most printers try to leave at least two or more lines of text at the top or bottom of each page.
The orphans property specifies the minimum number of lines of a paragraph that must be left at the bottom of a page.
The orphans property specifies the minimum number of lines of a paragraph that must be left at the bottom of a page.
The widows property specifies the minimum number of lines of a paragraph that must be left at the top of a page.
The widows property specifies the minimum number of lines of a paragraph that must be left at the top of a page.
Here is the example to create 4 lines at the bottom and 3 lines at the top of each page β
<style type = "text/css">
<!--
@page{orphans:4; widows:2;}
-->
</style>
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2840,
"s": 2626,
"text": "Paged media differ from continuous media in that the content of the document is split into one or more discrete pages. Paged media includes paper, transparencies, pages that are displayed on computer screens, etc."
},
{
"code": null,
"e": 2988,
"s": 2840,
"text": "The CSS2 standard introduces some basic pagination control features that let authors help the browser figure out how to best print their documents."
},
{
"code": null,
"e": 3165,
"s": 2988,
"text": "The CSS2 page model specifies how a document is formatted within a rectangular area -- the page box -- that has a finite width and height. These features fall into two groups β"
},
{
"code": null,
"e": 3217,
"s": 3165,
"text": "CSS2 features that define a particular page layout."
},
{
"code": null,
"e": 3274,
"s": 3217,
"text": "CSS2 features that control the pagination of a document."
},
{
"code": null,
"e": 3427,
"s": 3274,
"text": "The CSS2 defines a \"page box\", a box of finite dimensions in which content is rendered. The page box is a rectangular region that contains two areas β"
},
{
"code": null,
"e": 3606,
"s": 3427,
"text": "The page area β The page area includes the boxes laid out on that page. The edges of the page area act as the initial containing block for layout that occurs between page breaks."
},
{
"code": null,
"e": 3785,
"s": 3606,
"text": "The page area β The page area includes the boxes laid out on that page. The edges of the page area act as the initial containing block for layout that occurs between page breaks."
},
{
"code": null,
"e": 3831,
"s": 3785,
"text": "The margin area β It surrounds the page area."
},
{
"code": null,
"e": 3877,
"s": 3831,
"text": "The margin area β It surrounds the page area."
},
{
"code": null,
"e": 4128,
"s": 3877,
"text": "You can specify the dimensions, orientation, margins, etc., of a page box within an @page rule. The dimensions of the page box are set with the 'size' property. The dimensions of the page area are the dimensions of the page box minus the margin area."
},
{
"code": null,
"e": 4292,
"s": 4128,
"text": "For example, the following @page rule sets the page box size to 8.5 Γ 11 inches and creates '2cm' margin on all sides between the page box edge and the page area β"
},
{
"code": null,
"e": 4387,
"s": 4292,
"text": "<style type = \"text/css\">\n <!--\n @page { size:8.5in 11in; margin: 2cm }\n -->\n</style>"
},
{
"code": null,
"e": 4531,
"s": 4387,
"text": "You can use the margin, margin-top, margin-bottom, margin-left, and margin-right properties within the @page rule to set margins for your page."
},
{
"code": null,
"e": 4843,
"s": 4531,
"text": "Finally, the marks property is used within the @page rule to create crop and registration marks outside the page box on the target sheet. By default, no marks are printed. You may use one or both of the crop and cross keywords to create crop marks and registration marks, respectively, on the target print page."
},
{
"code": null,
"e": 4967,
"s": 4843,
"text": "The size property specifies the size and orientation of a page box. There are four values which can be used for page size β"
},
{
"code": null,
"e": 5048,
"s": 4967,
"text": "auto β The page box will be set to the size and orientation of the target sheet."
},
{
"code": null,
"e": 5129,
"s": 5048,
"text": "auto β The page box will be set to the size and orientation of the target sheet."
},
{
"code": null,
"e": 5259,
"s": 5129,
"text": "landscape β Overrides the target's orientation. The page box is the same size as the target, and the longer sides are horizontal."
},
{
"code": null,
"e": 5389,
"s": 5259,
"text": "landscape β Overrides the target's orientation. The page box is the same size as the target, and the longer sides are horizontal."
},
{
"code": null,
"e": 5519,
"s": 5389,
"text": "portrait β Overrides the target's orientation. The page box is the same size as the target, and the shorter sides are horizontal."
},
{
"code": null,
"e": 5649,
"s": 5519,
"text": "portrait β Overrides the target's orientation. The page box is the same size as the target, and the shorter sides are horizontal."
},
{
"code": null,
"e": 5874,
"s": 5649,
"text": "length β Length values for the 'size' property create an absolute page box. If only one length value is specified, it sets both the width and height of the page box. Percentage values are not allowed for the 'size' property."
},
{
"code": null,
"e": 6099,
"s": 5874,
"text": "length β Length values for the 'size' property create an absolute page box. If only one length value is specified, it sets both the width and height of the page box. Percentage values are not allowed for the 'size' property."
},
{
"code": null,
"e": 6363,
"s": 6099,
"text": "In the following example, the outer edges of the page box will align with the target. The percentage value on the 'margin' property is relative to the target size so if the target sheet dimensions are 21.0cm Γ 29.7cm (i.e., A4), the margins are 2.10cm and 2.97cm."
},
{
"code": null,
"e": 6512,
"s": 6363,
"text": "<style type = \"text/css\">\n <!--\n @page {\n size: auto; /* auto is the initial value */\n margin: 10%;\n }\n -->\n</style>"
},
{
"code": null,
"e": 6697,
"s": 6512,
"text": "The following example sets the width of the page box to be 8.5 inches and the height to be 11 inches. The page box in this example requires a target sheet size of 8.5\" Γ 11\" or larger."
},
{
"code": null,
"e": 6816,
"s": 6697,
"text": "<style type = \"text/css\">\n <!--\n @page {\n size: 8.5in 11in; /* width height */\n }\n -->\n</style>"
},
{
"code": null,
"e": 7063,
"s": 6816,
"text": "Once you create a named page layout, you can use it in your document by adding the page property to a style that is later applied to an element in your document. For example, this style renders all the tables in your document on landscape pages β"
},
{
"code": null,
"e": 7218,
"s": 7063,
"text": "<style type = \"text/css\">\n <!--\n @page { size : portrait }\n @page rotated { size : landscape }\n table { page : rotated }\n -->\n</style>\n"
},
{
"code": null,
"e": 7441,
"s": 7218,
"text": "Due to the above rule, while printing, if the browser encounters a <table> element in your document and the current page layout is the default portrait layout, it starts a new page and prints the table on a landscape page."
},
{
"code": null,
"e": 7603,
"s": 7441,
"text": "When printing double-sided documents, the page boxes on left and right pages should be different. It can be expressed through two CSS pseudo-classes as follows β"
},
{
"code": null,
"e": 7821,
"s": 7603,
"text": "<style type = \"text/css\">\n <!--\n @page :left {\n margin-left: 4cm;\n margin-right: 3cm;\n }\n\n @page :right {\n margin-left: 3cm;\n margin-right: 4cm;\n }\n -->\n</style>"
},
{
"code": null,
"e": 7911,
"s": 7821,
"text": "You can specify the style for the first page of a document with the :first pseudo-class β"
},
{
"code": null,
"e": 8113,
"s": 7911,
"text": "<style type = \"text/css\">\n <!--\n @page { margin: 2cm } /* All margins set to 2cm */\n\n @page :first {\n margin-top: 10cm /* Top margin on first page 10cm */\n }\n -->\n</style>"
},
{
"code": null,
"e": 8370,
"s": 8113,
"text": "Unless you specify otherwise, page breaks occur only when the page format changes or when the content overflows the current page box. To otherwise force or suppress page breaks, use the page-break-before, page-break-after, and page-break-inside properties."
},
{
"code": null,
"e": 8476,
"s": 8370,
"text": "Both the page-break-before and page-break-after accept the auto, always, avoid, left, and right keywords."
},
{
"code": null,
"e": 8831,
"s": 8476,
"text": "The keyword auto is the default, it lets the browser generate page breaks as needed. The keyword always forces a page break before or after the element, while avoid suppresses a page break immediately before or after the element. The left and right keywords force one or two page breaks, so that the element is rendered on a left-hand or right-hand page."
},
{
"code": null,
"e": 9187,
"s": 8831,
"text": "Using pagination properties is quite straightforward. Suppose your document has level-1 headers start new chapters with level-2 headers to denote sections. You'd like each chapter to start on a new, right-hand page, but you don't want section headers to be split across a page break from the subsequent content. You can achieve this using following rule β"
},
{
"code": null,
"e": 9314,
"s": 9187,
"text": "<style type = \"text/css\">\n <!--\n h1 { page-break-before : right }\n h2 { page-break-after : avoid }\n -->\n</style>"
},
{
"code": null,
"e": 9484,
"s": 9314,
"text": "Use only the auto and avoid values with the page-break-inside property. If you prefer that your tables not be broken across pages if possible, you would write the rule β"
},
{
"code": null,
"e": 9576,
"s": 9484,
"text": "<style type = \"text/css\">\n <!--\n table { page-break-inside : avoid }\n -->\n</style>"
},
{
"code": null,
"e": 9977,
"s": 9576,
"text": "In typographic lingo, orphans are those lines of a paragraph stranded at the bottom of a page due to a page break, while widows are those lines remaining at the top of a page following a page break. Generally, printed pages do not look attractive with single lines of text stranded at the top or bottom. Most printers try to leave at least two or more lines of text at the top or bottom of each page."
},
{
"code": null,
"e": 10094,
"s": 9977,
"text": "The orphans property specifies the minimum number of lines of a paragraph that must be left at the bottom of a page."
},
{
"code": null,
"e": 10211,
"s": 10094,
"text": "The orphans property specifies the minimum number of lines of a paragraph that must be left at the bottom of a page."
},
{
"code": null,
"e": 10324,
"s": 10211,
"text": "The widows property specifies the minimum number of lines of a paragraph that must be left at the top of a page."
},
{
"code": null,
"e": 10437,
"s": 10324,
"text": "The widows property specifies the minimum number of lines of a paragraph that must be left at the top of a page."
},
{
"code": null,
"e": 10527,
"s": 10437,
"text": "Here is the example to create 4 lines at the bottom and 3 lines at the top of each page β"
},
{
"code": null,
"e": 10611,
"s": 10527,
"text": "<style type = \"text/css\">\n <!--\n @page{orphans:4; widows:2;}\n -->\n</style>"
},
{
"code": null,
"e": 10646,
"s": 10611,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 10660,
"s": 10646,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 10695,
"s": 10660,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 10712,
"s": 10695,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 10747,
"s": 10712,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 10778,
"s": 10747,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 10813,
"s": 10778,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 10844,
"s": 10813,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 10879,
"s": 10844,
"text": "\n 51 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 10910,
"s": 10879,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 10943,
"s": 10910,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 10974,
"s": 10943,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 10981,
"s": 10974,
"text": " Print"
},
{
"code": null,
"e": 10992,
"s": 10981,
"text": " Add Notes"
}
] |
Creating Streamlit Dashboard from scratch. | by Himanshu Sharma | Towards Data Science
|
Building Dashboards was never easy, creating a dashboard requires knowledge of bootstrap, HTML, CSS, a lot of time etc.but by using streamlit we can create highly interactive and visually appealing dashboards just with a few lines of code. So letβs start building our dashboard but first let us take a look to understand streamlit.
Streamlit is an open-source Python library which is blazingly fast that makes it easy to build beautiful custom web-apps for machine learning and data science. It is an awesome tool that allows you to create highly interactive dashboards just with some knowledge of python. We will start by installing the streamlit and see how it works.
Installing Streamlit
pip install streamlit
Checking out some demos available on streamlit. For this, we need to run the command given below in the command prompt. This command allows you to explore Streamlit demos that are preloaded. You must check these out as they are really interesting.
streamlit hello
Now let us create our own dashboard. Here I will be creating a dashboard for Analyzing the Top 5 Gainers and Losers of the Indian stock market from May 2019-May 2020. For building this let us import some of the libraries that we need. Please note you need to create a script for streamlit and run it, so we will be using any code editor like Atom or Notepad++ and save it with .py format.
import streamlit as stimport pandas as pdimport numpy as npimport plotly.express as pxfrom plotly.subplots import make_subplotsimport plotly.graph_objects as goimport matplotlib.pyplot as plt
All these libraries will be used for mathematical computation and visualization of the stock data. Now let us import our data by using pandas, here I have created separate files for gainers and losers, so we will import both the files.
DATA_URL = ("C:/Users/Divya/gainers.csv")DATA_UR= ("C:/Users/Divya/losers.csv")df=pd.read_csv(DATA_URL)df1=pd.read_csv(DATA_UR)
After importing our data files let us begin by setting the title of our dashboard. For this, we will be using st.title for the main title and st.sidebar.title for sidebar title as given below.
st.title("Share Price analysis for May 2019 to May 2020:")st.sidebar.title("Share Price analysis for May 2019 to May 2020:")st.markdown("This application is a Share Price dashboard for Top 5 Gainers and Losers:")st.sidebar.markdown("This application is a Share Price dashboard for Top 5 Gainers and Losers:")
You can save this file and run it in streamlit to view changes. You will see your dashboard with the titles you mentioned. I store my file as share_new.py so I will run by typing the command given below.
streamlit run share_new.py
The best thing about streamlit is that it is blazingly fast i.e. you can save changes in your script and the application will immediately reflect the changes, you donβt need to refresh the application again and again.
In this dashboard, we are going to create the candlestick charts for all the stocks in our dataset. Also, we will be plotting the Moving Averages for these stocks. Starting with creating heading for Gainers and creating a selectbox for selecting the share you want to analyze.
st.sidebar.title("Gainers")select = st.sidebar.selectbox('Share', ['Adani Green Energy', 'GMM Pfaudler', 'AGC Networks', 'Alkyl Amines Chem', 'IOL Chem & Pharma'], key='1')
As soon as you save the file the changes will be reflected in your application.
Now we will write code for creating a checkbox to enable or disable the visualization of the candlestick chart and create a candlestick chart for all the stocks. The code given below will create the candlestick chart for βAdani Green Energyβ and will also calculate and display the Moving averages for this share.
if not st.sidebar.checkbox("Hide", True, key='1'): st.title("Gainers") if select == 'Adani Green Energy': for i in ['AdaLow', 'AdaHigh', 'AdaClose', 'AdaOpen']: df[i] = df[i].astype('float64')avg_20 = df.AdaClose.rolling(window=20, min_periods=1).mean()avg_50 = df.AdaClose.rolling(window=50, min_periods=1).mean()avg_200 = df.AdaClose.rolling(window=200, min_periods=1).mean()set1 = { 'x': df.AdaDate, 'open': df.AdaOpen, 'close': df.AdaClose, 'high': df.AdaHigh, 'low': df.AdaLow, 'type': 'candlestick',} set2 = { 'x': df.AdaDate, 'y': avg_20, 'type': 'scatter', 'mode': 'lines', 'line': { 'width': 1, 'color': 'blue' },'name': 'MA 20 periods'}set3 = { 'x': df.AdaDate, 'y': avg_50, 'type': 'scatter', 'mode': 'lines', 'line': { 'width': 1, 'color': 'yellow' },'name': 'MA 50 periods'} set4 = { 'x': df.AdaDate, 'y': avg_200, 'type': 'scatter', 'mode': 'lines', 'line': { 'width': 1, 'color': 'black' },'name': 'MA 200 periods'} data = [set1, set2, set3, set4] fig = go.Figure(data=data) st.plotly_chart(fig)
Similarly, we can create the candlestick chart for all the shares listed in the dataset but repeating the code mentioned above, the final dashboard will display all the share mentioned in the dataset.
The video displays the final dashboard created, the candlestick charts are created using Plotly so that they are interactive and the moving averages can be enabled or disabled accordingly. This dashboard is created in less than 2 hours and is highly interactive and visually appealing.
This is just an example of what streamlit can do. You can explore more to learn about infinite features that streamlit provide to create web-apps and dashboards. Please write in response if you find any difficulty in creating your own dashboards and share your experiences with me.
towardsdatascience.com
Thanks for reading! If you want to get in touch with me, feel free to reach me on [email protected] or my LinkedIn Profile. You can also view the code and data set I have used here in my Github. Also, feel free to explore my profile and read different articles I have written related to Data Science.
|
[
{
"code": null,
"e": 504,
"s": 172,
"text": "Building Dashboards was never easy, creating a dashboard requires knowledge of bootstrap, HTML, CSS, a lot of time etc.but by using streamlit we can create highly interactive and visually appealing dashboards just with a few lines of code. So letβs start building our dashboard but first let us take a look to understand streamlit."
},
{
"code": null,
"e": 842,
"s": 504,
"text": "Streamlit is an open-source Python library which is blazingly fast that makes it easy to build beautiful custom web-apps for machine learning and data science. It is an awesome tool that allows you to create highly interactive dashboards just with some knowledge of python. We will start by installing the streamlit and see how it works."
},
{
"code": null,
"e": 863,
"s": 842,
"text": "Installing Streamlit"
},
{
"code": null,
"e": 885,
"s": 863,
"text": "pip install streamlit"
},
{
"code": null,
"e": 1133,
"s": 885,
"text": "Checking out some demos available on streamlit. For this, we need to run the command given below in the command prompt. This command allows you to explore Streamlit demos that are preloaded. You must check these out as they are really interesting."
},
{
"code": null,
"e": 1149,
"s": 1133,
"text": "streamlit hello"
},
{
"code": null,
"e": 1538,
"s": 1149,
"text": "Now let us create our own dashboard. Here I will be creating a dashboard for Analyzing the Top 5 Gainers and Losers of the Indian stock market from May 2019-May 2020. For building this let us import some of the libraries that we need. Please note you need to create a script for streamlit and run it, so we will be using any code editor like Atom or Notepad++ and save it with .py format."
},
{
"code": null,
"e": 1730,
"s": 1538,
"text": "import streamlit as stimport pandas as pdimport numpy as npimport plotly.express as pxfrom plotly.subplots import make_subplotsimport plotly.graph_objects as goimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 1966,
"s": 1730,
"text": "All these libraries will be used for mathematical computation and visualization of the stock data. Now let us import our data by using pandas, here I have created separate files for gainers and losers, so we will import both the files."
},
{
"code": null,
"e": 2094,
"s": 1966,
"text": "DATA_URL = (\"C:/Users/Divya/gainers.csv\")DATA_UR= (\"C:/Users/Divya/losers.csv\")df=pd.read_csv(DATA_URL)df1=pd.read_csv(DATA_UR)"
},
{
"code": null,
"e": 2287,
"s": 2094,
"text": "After importing our data files let us begin by setting the title of our dashboard. For this, we will be using st.title for the main title and st.sidebar.title for sidebar title as given below."
},
{
"code": null,
"e": 2596,
"s": 2287,
"text": "st.title(\"Share Price analysis for May 2019 to May 2020:\")st.sidebar.title(\"Share Price analysis for May 2019 to May 2020:\")st.markdown(\"This application is a Share Price dashboard for Top 5 Gainers and Losers:\")st.sidebar.markdown(\"This application is a Share Price dashboard for Top 5 Gainers and Losers:\")"
},
{
"code": null,
"e": 2800,
"s": 2596,
"text": "You can save this file and run it in streamlit to view changes. You will see your dashboard with the titles you mentioned. I store my file as share_new.py so I will run by typing the command given below."
},
{
"code": null,
"e": 2827,
"s": 2800,
"text": "streamlit run share_new.py"
},
{
"code": null,
"e": 3045,
"s": 2827,
"text": "The best thing about streamlit is that it is blazingly fast i.e. you can save changes in your script and the application will immediately reflect the changes, you donβt need to refresh the application again and again."
},
{
"code": null,
"e": 3322,
"s": 3045,
"text": "In this dashboard, we are going to create the candlestick charts for all the stocks in our dataset. Also, we will be plotting the Moving Averages for these stocks. Starting with creating heading for Gainers and creating a selectbox for selecting the share you want to analyze."
},
{
"code": null,
"e": 3495,
"s": 3322,
"text": "st.sidebar.title(\"Gainers\")select = st.sidebar.selectbox('Share', ['Adani Green Energy', 'GMM Pfaudler', 'AGC Networks', 'Alkyl Amines Chem', 'IOL Chem & Pharma'], key='1')"
},
{
"code": null,
"e": 3575,
"s": 3495,
"text": "As soon as you save the file the changes will be reflected in your application."
},
{
"code": null,
"e": 3889,
"s": 3575,
"text": "Now we will write code for creating a checkbox to enable or disable the visualization of the candlestick chart and create a candlestick chart for all the stocks. The code given below will create the candlestick chart for βAdani Green Energyβ and will also calculate and display the Moving averages for this share."
},
{
"code": null,
"e": 4952,
"s": 3889,
"text": "if not st.sidebar.checkbox(\"Hide\", True, key='1'): st.title(\"Gainers\") if select == 'Adani Green Energy': for i in ['AdaLow', 'AdaHigh', 'AdaClose', 'AdaOpen']: df[i] = df[i].astype('float64')avg_20 = df.AdaClose.rolling(window=20, min_periods=1).mean()avg_50 = df.AdaClose.rolling(window=50, min_periods=1).mean()avg_200 = df.AdaClose.rolling(window=200, min_periods=1).mean()set1 = { 'x': df.AdaDate, 'open': df.AdaOpen, 'close': df.AdaClose, 'high': df.AdaHigh, 'low': df.AdaLow, 'type': 'candlestick',} set2 = { 'x': df.AdaDate, 'y': avg_20, 'type': 'scatter', 'mode': 'lines', 'line': { 'width': 1, 'color': 'blue' },'name': 'MA 20 periods'}set3 = { 'x': df.AdaDate, 'y': avg_50, 'type': 'scatter', 'mode': 'lines', 'line': { 'width': 1, 'color': 'yellow' },'name': 'MA 50 periods'} set4 = { 'x': df.AdaDate, 'y': avg_200, 'type': 'scatter', 'mode': 'lines', 'line': { 'width': 1, 'color': 'black' },'name': 'MA 200 periods'} data = [set1, set2, set3, set4] fig = go.Figure(data=data) st.plotly_chart(fig)"
},
{
"code": null,
"e": 5153,
"s": 4952,
"text": "Similarly, we can create the candlestick chart for all the shares listed in the dataset but repeating the code mentioned above, the final dashboard will display all the share mentioned in the dataset."
},
{
"code": null,
"e": 5439,
"s": 5153,
"text": "The video displays the final dashboard created, the candlestick charts are created using Plotly so that they are interactive and the moving averages can be enabled or disabled accordingly. This dashboard is created in less than 2 hours and is highly interactive and visually appealing."
},
{
"code": null,
"e": 5721,
"s": 5439,
"text": "This is just an example of what streamlit can do. You can explore more to learn about infinite features that streamlit provide to create web-apps and dashboards. Please write in response if you find any difficulty in creating your own dashboards and share your experiences with me."
},
{
"code": null,
"e": 5744,
"s": 5721,
"text": "towardsdatascience.com"
}
] |
Joining 4 Tables in SQL - GeeksforGeeks
|
01 Sep, 2021
The purpose of this article is to make a simple program to Join two tables using Join and Where clause in SQL. Below is the implementation for the same using MySQL. The prerequisites of this topic are MySQL and the installment of Apache Server on your computer.
Introduction :In SQL, a query is a request with some instruction such that inserting, reading, deleting, and updating, etc. record from the database. This data can be used for various purposes like Training a model, finding the patterns in the data, etc. Here, we will discuss the approach for Joining 4 Tables in SQL and will implement using SQL query for each table for better understanding.
Approach :Here, we will discuss the approach and steps to implement Joining 4 Tables in SQL. So, letβs start by creating a Database.
Step-1: Create a database βHere first, we will create the database using SQL query as follows.
CREATE DATABASE geeksforgeeks;
Step-2: Use the database βNow, we will use the database using SQL query as follows.
USE geeksforgeeks;
Step-3: Creating table1 βCreate a table 1, name as s_marks using SQL query as follows.
CREATE TABLE s_marks
(
studentid int(10) PRIMARY KEY,
subjectid VARCHAR(10),
professorid int(10)
);
Step-4: Creating table2 β Create a table2 for the professor details as p_details using SQL query as follows.
CREATE TABLE p_details
(
pid int(10) PRIMARY KEY,
pname VARCHAR(50),
pemail VARCHAR(50)
);
Step-5: Creating table3 β Create a table for subjects as subjects using SQL query as follows.
CREATE TABLE subjects
(
subjectid VARCHAR(10) PRIMARY KEY,
total_marks INT(5)
);
Step-6: Creating table4 β Create a table for the subject marks details using SQL query as follows.
CREATE TABLE marks_details
(
total_marks INT(5) PRIMARY KEY,
theory INT(5),
practical INT(5)
);
Output :The output of tables as follows.
Step-7: Inserting data :Insert some data in the above-created tables using SQL query as follows.
Insert into s_marks β
INSERT INTO `s_marks` (`studentid`, `subjectid`, `professorid`) VALUES ('1', 'KCS101', '1');
INSERT INTO `s_marks` (`studentid`, `subjectid`, `professorid`) VALUES ('2', 'KCS102', '2');
Insert into p_details β
INSERT INTO `p_details` (`pid`, `pname`, `pemail`) VALUES ('1', 'Devesh', '[email protected]');
INSERT INTO `p_details` (`pid`, `pname`, `pemail`) VALUES ('2', 'Aditya', '[email protected]');
Insert into subjects β
INSERT INTO `subjects` (`subjectid`, `total_marks`) VALUES ('KCS101', '100');
INSERT INTO `subjects` (`subjectid`, `total_marks`) VALUES ('KCS102', '150');
Insert into marks_details β
INSERT INTO `marks_details` (`total_marks`, `theory`, `practical`) VALUES ('100', '70', '30');
INSERT INTO `marks_details` (`total_marks`, `theory`, `practical`) VALUES ('150', '100', '50');
Step-8: Verifying and joining tables βRun the query to find out the ID, professor name of a student whose subjectβs practical marks are 50 as follows.
SELECT s_marks.studentid, p_details.pname FROM s_marks
JOIN subjects ON s_marks.subjectid = subjects.subjectid
JOIN marks_details ON subjects.total_marks = marks_details.total_marks
JOIN p_details ON p_details.pid = s_marks.professorid
WHERE marks_details.practical = '50';
Output :
rajeev0719singh
DBMS-SQL
Picked
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Convert VARCHAR to INT
SQL Query to Delete Duplicate Rows
SQL Query to Compare Two Dates
Window functions in SQL
|
[
{
"code": null,
"e": 23975,
"s": 23944,
"text": " \n01 Sep, 2021\n"
},
{
"code": null,
"e": 24237,
"s": 23975,
"text": "The purpose of this article is to make a simple program to Join two tables using Join and Where clause in SQL. Below is the implementation for the same using MySQL. The prerequisites of this topic are MySQL and the installment of Apache Server on your computer."
},
{
"code": null,
"e": 24632,
"s": 24237,
"text": "Introduction :In SQL, a query is a request with some instruction such that inserting, reading, deleting, and updating, etc. record from the database. This data can be used for various purposes like Training a model, finding the patterns in the data, etc. Here, we will discuss the approach for Joining 4 Tables in SQL and will implement using SQL query for each table for better understanding. "
},
{
"code": null,
"e": 24765,
"s": 24632,
"text": "Approach :Here, we will discuss the approach and steps to implement Joining 4 Tables in SQL. So, letβs start by creating a Database."
},
{
"code": null,
"e": 24860,
"s": 24765,
"text": "Step-1: Create a database βHere first, we will create the database using SQL query as follows."
},
{
"code": null,
"e": 24891,
"s": 24860,
"text": "CREATE DATABASE geeksforgeeks;"
},
{
"code": null,
"e": 24975,
"s": 24891,
"text": "Step-2: Use the database βNow, we will use the database using SQL query as follows."
},
{
"code": null,
"e": 24994,
"s": 24975,
"text": "USE geeksforgeeks;"
},
{
"code": null,
"e": 25081,
"s": 24994,
"text": "Step-3: Creating table1 βCreate a table 1, name as s_marks using SQL query as follows."
},
{
"code": null,
"e": 25184,
"s": 25081,
"text": "CREATE TABLE s_marks \n(\nstudentid int(10) PRIMARY KEY, \nsubjectid VARCHAR(10), \nprofessorid int(10)\n);"
},
{
"code": null,
"e": 25293,
"s": 25184,
"text": "Step-4: Creating table2 β Create a table2 for the professor details as p_details using SQL query as follows."
},
{
"code": null,
"e": 25387,
"s": 25293,
"text": "CREATE TABLE p_details \n(\npid int(10) PRIMARY KEY, \npname VARCHAR(50), \npemail VARCHAR(50)\n);"
},
{
"code": null,
"e": 25481,
"s": 25387,
"text": "Step-5: Creating table3 β Create a table for subjects as subjects using SQL query as follows."
},
{
"code": null,
"e": 25565,
"s": 25481,
"text": "CREATE TABLE subjects \n(\nsubjectid VARCHAR(10) PRIMARY KEY, \ntotal_marks INT(5)\n);"
},
{
"code": null,
"e": 25665,
"s": 25565,
"text": "Step-6: Creating table4 β Create a table for the subject marks details using SQL query as follows. "
},
{
"code": null,
"e": 25763,
"s": 25665,
"text": "CREATE TABLE marks_details \n(\ntotal_marks INT(5) PRIMARY KEY, \ntheory INT(5),\npractical INT(5)\n);"
},
{
"code": null,
"e": 25804,
"s": 25763,
"text": "Output :The output of tables as follows."
},
{
"code": null,
"e": 25902,
"s": 25804,
"text": "Step-7: Inserting data :Insert some data in the above-created tables using SQL query as follows. "
},
{
"code": null,
"e": 25925,
"s": 25902,
"text": "Insert into s_marks β "
},
{
"code": null,
"e": 26111,
"s": 25925,
"text": "INSERT INTO `s_marks` (`studentid`, `subjectid`, `professorid`) VALUES ('1', 'KCS101', '1');\nINSERT INTO `s_marks` (`studentid`, `subjectid`, `professorid`) VALUES ('2', 'KCS102', '2');"
},
{
"code": null,
"e": 26135,
"s": 26111,
"text": "Insert into p_details β"
},
{
"code": null,
"e": 26317,
"s": 26135,
"text": "INSERT INTO `p_details` (`pid`, `pname`, `pemail`) VALUES ('1', 'Devesh', '[email protected]');\nINSERT INTO `p_details` (`pid`, `pname`, `pemail`) VALUES ('2', 'Aditya', '[email protected]');"
},
{
"code": null,
"e": 26340,
"s": 26317,
"text": "Insert into subjects β"
},
{
"code": null,
"e": 26496,
"s": 26340,
"text": "INSERT INTO `subjects` (`subjectid`, `total_marks`) VALUES ('KCS101', '100');\nINSERT INTO `subjects` (`subjectid`, `total_marks`) VALUES ('KCS102', '150');"
},
{
"code": null,
"e": 26525,
"s": 26496,
"text": "Insert into marks_details β "
},
{
"code": null,
"e": 26716,
"s": 26525,
"text": "INSERT INTO `marks_details` (`total_marks`, `theory`, `practical`) VALUES ('100', '70', '30');\nINSERT INTO `marks_details` (`total_marks`, `theory`, `practical`) VALUES ('150', '100', '50');"
},
{
"code": null,
"e": 26867,
"s": 26716,
"text": "Step-8: Verifying and joining tables βRun the query to find out the ID, professor name of a student whose subjectβs practical marks are 50 as follows."
},
{
"code": null,
"e": 27143,
"s": 26867,
"text": "SELECT s_marks.studentid, p_details.pname FROM s_marks \nJOIN subjects ON s_marks.subjectid = subjects.subjectid \nJOIN marks_details ON subjects.total_marks = marks_details.total_marks\nJOIN p_details ON p_details.pid = s_marks.professorid\nWHERE marks_details.practical = '50';"
},
{
"code": null,
"e": 27152,
"s": 27143,
"text": "Output :"
},
{
"code": null,
"e": 27168,
"s": 27152,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 27179,
"s": 27168,
"text": "\nDBMS-SQL\n"
},
{
"code": null,
"e": 27188,
"s": 27179,
"text": "\nPicked\n"
},
{
"code": null,
"e": 27194,
"s": 27188,
"text": "\nSQL\n"
},
{
"code": null,
"e": 27399,
"s": 27194,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 27465,
"s": 27399,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 27497,
"s": 27465,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 27575,
"s": 27497,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 27592,
"s": 27575,
"text": "SQL using Python"
},
{
"code": null,
"e": 27607,
"s": 27592,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 27673,
"s": 27607,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 27709,
"s": 27673,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 27744,
"s": 27709,
"text": "SQL Query to Delete Duplicate Rows"
},
{
"code": null,
"e": 27775,
"s": 27744,
"text": "SQL Query to Compare Two Dates"
}
] |
General Sibling Selectors in CSS
|
The CSS general sibling selector is used to select all elements that follow the first element such that both are children of the same parent.
The syntax for CSS general sibling selector is as follows
element ~ element {
/*declarations*/
}
The following examples illustrate CSS general sibling selector β
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
* {
float: left;
padding-left: 14px;
list-style: none;
}
p ~ ul {
box-shadow: inset 4px 0 3px lime;
}
</style>
</head>
<body>
<ul>
<li><img src="https://www.tutorialspoint.com/images/pl-sql.png"></li>
</ul>
<p>We provide learning tutorials, quizzes and video tutorials.</p>
<ul>
<li>Tutorials on databases and programming languages.</li>
<li>Quizzes to check knowledge of databases and languages.</li>
<li>Video Tutorials to easily understand the technologies.</li>
</ul>
<ul>
<li><img src="https://www.tutorialspoint.com/images/mongodb.png"></li>
<li><img src="https://www.tutorialspoint.com/images/db2.png"></li>
<li><img src="https://www.tutorialspoint.com/images/sql.png"></li>
</ul>
</body>
</html>
This gives the following output β
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
* {
float: left;
padding: 10px;
list-style: none;
}
img ~ p {
background-color: burlywood;
}
</style>
</head>
<body>
<p>This is demo text.</p>
<img src="https://www.tutorialspoint.com/big_data_analytics/images/big-data-analytics-mini-logo.jpg">
<p>Learn Big Data Analytics at no cost.</p>
</body>
</html>
This gives the following output β
|
[
{
"code": null,
"e": 1204,
"s": 1062,
"text": "The CSS general sibling selector is used to select all elements that follow the first element such that both are children of the same parent."
},
{
"code": null,
"e": 1262,
"s": 1204,
"text": "The syntax for CSS general sibling selector is as follows"
},
{
"code": null,
"e": 1304,
"s": 1262,
"text": "element ~ element {\n /*declarations*/\n}"
},
{
"code": null,
"e": 1369,
"s": 1304,
"text": "The following examples illustrate CSS general sibling selector β"
},
{
"code": null,
"e": 1380,
"s": 1369,
"text": " Live Demo"
},
{
"code": null,
"e": 2134,
"s": 1380,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n* {\n float: left;\n padding-left: 14px;\n list-style: none;\n}\np ~ ul {\n box-shadow: inset 4px 0 3px lime;\n}\n</style>\n</head>\n<body>\n<ul>\n<li><img src=\"https://www.tutorialspoint.com/images/pl-sql.png\"></li>\n</ul>\n<p>We provide learning tutorials, quizzes and video tutorials.</p>\n<ul>\n<li>Tutorials on databases and programming languages.</li>\n<li>Quizzes to check knowledge of databases and languages.</li>\n<li>Video Tutorials to easily understand the technologies.</li>\n</ul>\n<ul>\n<li><img src=\"https://www.tutorialspoint.com/images/mongodb.png\"></li>\n<li><img src=\"https://www.tutorialspoint.com/images/db2.png\"></li>\n<li><img src=\"https://www.tutorialspoint.com/images/sql.png\"></li>\n</ul>\n</body>\n</html>"
},
{
"code": null,
"e": 2168,
"s": 2134,
"text": "This gives the following output β"
},
{
"code": null,
"e": 2179,
"s": 2168,
"text": " Live Demo"
},
{
"code": null,
"e": 2534,
"s": 2179,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n* {\n float: left;\n padding: 10px;\n list-style: none;\n}\nimg ~ p {\n background-color: burlywood;\n}\n</style>\n</head>\n<body>\n<p>This is demo text.</p>\n<img src=\"https://www.tutorialspoint.com/big_data_analytics/images/big-data-analytics-mini-logo.jpg\">\n<p>Learn Big Data Analytics at no cost.</p>\n</body>\n</html>"
},
{
"code": null,
"e": 2568,
"s": 2534,
"text": "This gives the following output β"
}
] |
PHP strftime() Function
|
The strftime function accepts a format string as a parameter, and formats the locale date/time according to the locale settings..
strftime($format [, $timestamp])
format(Optional)
This is a string value representing the format in which you need to format the date/time.
timestamp(Mandatory)
This is an integer value representing the Unix time stamp specifying the current time value.
PHP strftime() function retrurns a string value representing the formatted time. You can change the month and week day names to other language using the setlocale() method.
This function was first introduced in PHP Version 5.3 and, works with all the later versions.
Following example demonstrates the usage of the strftime() function β
<?php
$date = strftime("%A %d %B %G");
$time = strftime("%T");
print("Date: ".$date ."\n");
print("Time: ".$time);
?>
This will produce following result β
Date: Wednesday 13 May 2020
Time: 06:28:07
Let us try this function by passing the time stamp parameter (along with the format) β
<?php
$timestamp = mktime(7, 36, 45, 06, 25, 2017);
$date = strftime("%A %d %B %G %T", $timestamp );
print("Date: ".$date ."\n");
?>
This will produce following result β
Date: Sunday 25 June 2017 07:36:45
following example prints the day of the week and month of a particular date in Catalan language β
<?php
setlocale(LC_TIME, 'ca_ES', 'Catalan_Spain', 'Catalan');
$date = strftime("%A %d %B %G %T");
print("Date: ".$date ."\n");
?>
This will produce following result β
Date: dimecres 13 maig 2020 08:14:19
<?php
setlocale(LC_TIME, 'en_US');
echo strftime("%b %d %Y %H:%M:%S", mktime(20, 0, 0, 12, 31, 2015)) . "\n";
echo gmstrftime("%b %d %Y %H:%M:%S", mktime(20, 0, 0, 12, 31, 2015)) . "\n";
?>
This produces the following result β
Dec 31 2015 20:00:00
Dec 31 2015 20:00:00
Following are the various characters to format the date/time using strftime β
%a β abbreviated weekday name
%a β abbreviated weekday name
%A β full weekday name
%A β full weekday name
%b β abbreviated month name
%b β abbreviated month name
%B β full month name
%B β full month name
%c β preferred date and time representation
%c β preferred date and time representation
%C β century number (the year divided by 100, range 00 to 99)
%C β century number (the year divided by 100, range 00 to 99)
%d β day of the month (01 to 31)
%d β day of the month (01 to 31)
%D β same as %m/%d/%y
%D β same as %m/%d/%y
%e β day of the month (1 to 31)
%e β day of the month (1 to 31)
%g β like %G, but without the century
%g β like %G, but without the century
%G β 4-digit year corresponding to the ISO week number (see %V).
%G β 4-digit year corresponding to the ISO week number (see %V).
%h β same as %b
%h β same as %b
%H β hour, using a 24-hour clock (00 to 23)
%H β hour, using a 24-hour clock (00 to 23)
%I β hour, using a 12-hour clock (01 to 12)
%I β hour, using a 12-hour clock (01 to 12)
%j β day of the year (001 to 366)
%j β day of the year (001 to 366)
%m β month (01 to 12)
%m β month (01 to 12)
%M β minute
%M β minute
%n β newline character
%n β newline character
%p β either am or pm according to the given time value
%p β either am or pm according to the given time value
%r β time in a.m. and p.m. notation
%r β time in a.m. and p.m. notation
%R β time in 24 hour notation
%R β time in 24 hour notation
%S β second
%S β second
%t β tab character
%t β tab character
%T β current time, equal to %H:%M:%S
%T β current time, equal to %H:%M:%S
%u β weekday as a number (1 to 7), Monday=1. Warning: In Sun Solaris Sunday=1
%u β weekday as a number (1 to 7), Monday=1. Warning: In Sun Solaris Sunday=1
%U β week number of the current year, starting with the first Sunday as the first day of the first week
%U β week number of the current year, starting with the first Sunday as the first day of the first week
%V β The ISO 8601 week number of the current year (01 to 53), where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week
%V β The ISO 8601 week number of the current year (01 to 53), where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week
%W β week number of the current year, starting with the first Monday as the first day of the first week
%W β week number of the current year, starting with the first Monday as the first day of the first week
%w β day of the week as a decimal, Sunday=0
%w β day of the week as a decimal, Sunday=0
%x β preferred date representation without the time
%x β preferred date representation without the time
%X β preferred time representation without the date
%X β preferred time representation without the date
%y β year without a century (range 00 to 99)
%y β year without a century (range 00 to 99)
%Y β year including the century
%Y β year including the century
%Z or %z β time zone or name or abbreviation
%Z or %z β time zone or name or abbreviation
%% β a literal % character
%% β a literal % character
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2887,
"s": 2757,
"text": "The strftime function accepts a format string as a parameter, and formats the locale date/time according to the locale settings.."
},
{
"code": null,
"e": 2921,
"s": 2887,
"text": "strftime($format [, $timestamp])\n"
},
{
"code": null,
"e": 2938,
"s": 2921,
"text": "format(Optional)"
},
{
"code": null,
"e": 3028,
"s": 2938,
"text": "This is a string value representing the format in which you need to format the date/time."
},
{
"code": null,
"e": 3049,
"s": 3028,
"text": "timestamp(Mandatory)"
},
{
"code": null,
"e": 3142,
"s": 3049,
"text": "This is an integer value representing the Unix time stamp specifying the current time value."
},
{
"code": null,
"e": 3316,
"s": 3142,
"text": "PHP strftime() function retrurns a string value representing the formatted time. You can change the month and week day names to other language using the setlocale() method. "
},
{
"code": null,
"e": 3410,
"s": 3316,
"text": "This function was first introduced in PHP Version 5.3 and, works with all the later versions."
},
{
"code": null,
"e": 3480,
"s": 3410,
"text": "Following example demonstrates the usage of the strftime() function β"
},
{
"code": null,
"e": 3610,
"s": 3480,
"text": "<?php\n $date = strftime(\"%A %d %B %G\");\n $time = strftime(\"%T\");\n print(\"Date: \".$date .\"\\n\");\n print(\"Time: \".$time);\n?>"
},
{
"code": null,
"e": 3647,
"s": 3610,
"text": "This will produce following result β"
},
{
"code": null,
"e": 3691,
"s": 3647,
"text": "Date: Wednesday 13 May 2020\nTime: 06:28:07\n"
},
{
"code": null,
"e": 3778,
"s": 3691,
"text": "Let us try this function by passing the time stamp parameter (along with the format) β"
},
{
"code": null,
"e": 3921,
"s": 3778,
"text": "<?php\n $timestamp = mktime(7, 36, 45, 06, 25, 2017); \n $date = strftime(\"%A %d %B %G %T\", $timestamp );\n print(\"Date: \".$date .\"\\n\");\n?>"
},
{
"code": null,
"e": 3958,
"s": 3921,
"text": "This will produce following result β"
},
{
"code": null,
"e": 3994,
"s": 3958,
"text": "Date: Sunday 25 June 2017 07:36:45\n"
},
{
"code": null,
"e": 4092,
"s": 3994,
"text": "following example prints the day of the week and month of a particular date in Catalan language β"
},
{
"code": null,
"e": 4232,
"s": 4092,
"text": "<?php\n setlocale(LC_TIME, 'ca_ES', 'Catalan_Spain', 'Catalan');\n $date = strftime(\"%A %d %B %G %T\");\n print(\"Date: \".$date .\"\\n\");\n?>"
},
{
"code": null,
"e": 4269,
"s": 4232,
"text": "This will produce following result β"
},
{
"code": null,
"e": 4307,
"s": 4269,
"text": "Date: dimecres 13 maig 2020 08:14:19\n"
},
{
"code": null,
"e": 4510,
"s": 4307,
"text": "<?php\n setlocale(LC_TIME, 'en_US'); \n echo strftime(\"%b %d %Y %H:%M:%S\", mktime(20, 0, 0, 12, 31, 2015)) . \"\\n\";\n echo gmstrftime(\"%b %d %Y %H:%M:%S\", mktime(20, 0, 0, 12, 31, 2015)) . \"\\n\"; \n?>"
},
{
"code": null,
"e": 4547,
"s": 4510,
"text": "This produces the following result β"
},
{
"code": null,
"e": 4590,
"s": 4547,
"text": "Dec 31 2015 20:00:00\nDec 31 2015 20:00:00\n"
},
{
"code": null,
"e": 4668,
"s": 4590,
"text": "Following are the various characters to format the date/time using strftime β"
},
{
"code": null,
"e": 4698,
"s": 4668,
"text": "%a β abbreviated weekday name"
},
{
"code": null,
"e": 4728,
"s": 4698,
"text": "%a β abbreviated weekday name"
},
{
"code": null,
"e": 4751,
"s": 4728,
"text": "%A β full weekday name"
},
{
"code": null,
"e": 4774,
"s": 4751,
"text": "%A β full weekday name"
},
{
"code": null,
"e": 4802,
"s": 4774,
"text": "%b β abbreviated month name"
},
{
"code": null,
"e": 4830,
"s": 4802,
"text": "%b β abbreviated month name"
},
{
"code": null,
"e": 4851,
"s": 4830,
"text": "%B β full month name"
},
{
"code": null,
"e": 4872,
"s": 4851,
"text": "%B β full month name"
},
{
"code": null,
"e": 4916,
"s": 4872,
"text": "%c β preferred date and time representation"
},
{
"code": null,
"e": 4960,
"s": 4916,
"text": "%c β preferred date and time representation"
},
{
"code": null,
"e": 5022,
"s": 4960,
"text": "%C β century number (the year divided by 100, range 00 to 99)"
},
{
"code": null,
"e": 5084,
"s": 5022,
"text": "%C β century number (the year divided by 100, range 00 to 99)"
},
{
"code": null,
"e": 5117,
"s": 5084,
"text": "%d β day of the month (01 to 31)"
},
{
"code": null,
"e": 5150,
"s": 5117,
"text": "%d β day of the month (01 to 31)"
},
{
"code": null,
"e": 5172,
"s": 5150,
"text": "%D β same as %m/%d/%y"
},
{
"code": null,
"e": 5194,
"s": 5172,
"text": "%D β same as %m/%d/%y"
},
{
"code": null,
"e": 5226,
"s": 5194,
"text": "%e β day of the month (1 to 31)"
},
{
"code": null,
"e": 5258,
"s": 5226,
"text": "%e β day of the month (1 to 31)"
},
{
"code": null,
"e": 5296,
"s": 5258,
"text": "%g β like %G, but without the century"
},
{
"code": null,
"e": 5334,
"s": 5296,
"text": "%g β like %G, but without the century"
},
{
"code": null,
"e": 5399,
"s": 5334,
"text": "%G β 4-digit year corresponding to the ISO week number (see %V)."
},
{
"code": null,
"e": 5464,
"s": 5399,
"text": "%G β 4-digit year corresponding to the ISO week number (see %V)."
},
{
"code": null,
"e": 5480,
"s": 5464,
"text": "%h β same as %b"
},
{
"code": null,
"e": 5496,
"s": 5480,
"text": "%h β same as %b"
},
{
"code": null,
"e": 5540,
"s": 5496,
"text": "%H β hour, using a 24-hour clock (00 to 23)"
},
{
"code": null,
"e": 5584,
"s": 5540,
"text": "%H β hour, using a 24-hour clock (00 to 23)"
},
{
"code": null,
"e": 5628,
"s": 5584,
"text": "%I β hour, using a 12-hour clock (01 to 12)"
},
{
"code": null,
"e": 5672,
"s": 5628,
"text": "%I β hour, using a 12-hour clock (01 to 12)"
},
{
"code": null,
"e": 5706,
"s": 5672,
"text": "%j β day of the year (001 to 366)"
},
{
"code": null,
"e": 5740,
"s": 5706,
"text": "%j β day of the year (001 to 366)"
},
{
"code": null,
"e": 5762,
"s": 5740,
"text": "%m β month (01 to 12)"
},
{
"code": null,
"e": 5784,
"s": 5762,
"text": "%m β month (01 to 12)"
},
{
"code": null,
"e": 5796,
"s": 5784,
"text": "%M β minute"
},
{
"code": null,
"e": 5808,
"s": 5796,
"text": "%M β minute"
},
{
"code": null,
"e": 5831,
"s": 5808,
"text": "%n β newline character"
},
{
"code": null,
"e": 5854,
"s": 5831,
"text": "%n β newline character"
},
{
"code": null,
"e": 5909,
"s": 5854,
"text": "%p β either am or pm according to the given time value"
},
{
"code": null,
"e": 5964,
"s": 5909,
"text": "%p β either am or pm according to the given time value"
},
{
"code": null,
"e": 6000,
"s": 5964,
"text": "%r β time in a.m. and p.m. notation"
},
{
"code": null,
"e": 6036,
"s": 6000,
"text": "%r β time in a.m. and p.m. notation"
},
{
"code": null,
"e": 6066,
"s": 6036,
"text": "%R β time in 24 hour notation"
},
{
"code": null,
"e": 6096,
"s": 6066,
"text": "%R β time in 24 hour notation"
},
{
"code": null,
"e": 6108,
"s": 6096,
"text": "%S β second"
},
{
"code": null,
"e": 6120,
"s": 6108,
"text": "%S β second"
},
{
"code": null,
"e": 6139,
"s": 6120,
"text": "%t β tab character"
},
{
"code": null,
"e": 6158,
"s": 6139,
"text": "%t β tab character"
},
{
"code": null,
"e": 6195,
"s": 6158,
"text": "%T β current time, equal to %H:%M:%S"
},
{
"code": null,
"e": 6232,
"s": 6195,
"text": "%T β current time, equal to %H:%M:%S"
},
{
"code": null,
"e": 6310,
"s": 6232,
"text": "%u β weekday as a number (1 to 7), Monday=1. Warning: In Sun Solaris Sunday=1"
},
{
"code": null,
"e": 6388,
"s": 6310,
"text": "%u β weekday as a number (1 to 7), Monday=1. Warning: In Sun Solaris Sunday=1"
},
{
"code": null,
"e": 6492,
"s": 6388,
"text": "%U β week number of the current year, starting with the first Sunday as the first day of the first week"
},
{
"code": null,
"e": 6596,
"s": 6492,
"text": "%U β week number of the current year, starting with the first Sunday as the first day of the first week"
},
{
"code": null,
"e": 6780,
"s": 6596,
"text": "%V β The ISO 8601 week number of the current year (01 to 53), where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week"
},
{
"code": null,
"e": 6964,
"s": 6780,
"text": "%V β The ISO 8601 week number of the current year (01 to 53), where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week"
},
{
"code": null,
"e": 7068,
"s": 6964,
"text": "%W β week number of the current year, starting with the first Monday as the first day of the first week"
},
{
"code": null,
"e": 7172,
"s": 7068,
"text": "%W β week number of the current year, starting with the first Monday as the first day of the first week"
},
{
"code": null,
"e": 7216,
"s": 7172,
"text": "%w β day of the week as a decimal, Sunday=0"
},
{
"code": null,
"e": 7260,
"s": 7216,
"text": "%w β day of the week as a decimal, Sunday=0"
},
{
"code": null,
"e": 7312,
"s": 7260,
"text": "%x β preferred date representation without the time"
},
{
"code": null,
"e": 7364,
"s": 7312,
"text": "%x β preferred date representation without the time"
},
{
"code": null,
"e": 7416,
"s": 7364,
"text": "%X β preferred time representation without the date"
},
{
"code": null,
"e": 7468,
"s": 7416,
"text": "%X β preferred time representation without the date"
},
{
"code": null,
"e": 7513,
"s": 7468,
"text": "%y β year without a century (range 00 to 99)"
},
{
"code": null,
"e": 7558,
"s": 7513,
"text": "%y β year without a century (range 00 to 99)"
},
{
"code": null,
"e": 7590,
"s": 7558,
"text": "%Y β year including the century"
},
{
"code": null,
"e": 7622,
"s": 7590,
"text": "%Y β year including the century"
},
{
"code": null,
"e": 7667,
"s": 7622,
"text": "%Z or %z β time zone or name or abbreviation"
},
{
"code": null,
"e": 7712,
"s": 7667,
"text": "%Z or %z β time zone or name or abbreviation"
},
{
"code": null,
"e": 7739,
"s": 7712,
"text": "%% β a literal % character"
},
{
"code": null,
"e": 7766,
"s": 7739,
"text": "%% β a literal % character"
},
{
"code": null,
"e": 7799,
"s": 7766,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 7815,
"s": 7799,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7848,
"s": 7815,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7859,
"s": 7848,
"text": " Syed Raza"
},
{
"code": null,
"e": 7894,
"s": 7859,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7911,
"s": 7894,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7944,
"s": 7911,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7959,
"s": 7944,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 7994,
"s": 7959,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 8006,
"s": 7994,
"text": " Azaz Patel"
},
{
"code": null,
"e": 8041,
"s": 8006,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 8069,
"s": 8041,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 8076,
"s": 8069,
"text": " Print"
},
{
"code": null,
"e": 8087,
"s": 8076,
"text": " Add Notes"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.